Jones
Jones

Reputation: 343

Plotting a time series + stacked bar chart

I have this dataset 'Sales':

Date <- c("2010-01-28", "2010-01-28", "2010-01-28", "2010-01-28",
 "2010-02-28","2010-02-28", "2010-02-28", "2010-02-28")

Type <- c("A", "B", "C", "D", "A", "B", "C", "D")

Dollars <- c(1787, 800, 500, 300, 1950, 1100, 890, 450)
Sales <- data.frame(Date, Type, Dollars)

So, I have four types of products (A, B, C, D) which the sales are released monthly. I would like a time series of this: the months in the X-Axis and, for each month (or quarter, whatever), a stacked bar plot representing the Dollar columns (Y-axis). My skills with ggplot2 are not that good, so I appreciate it if someone can help.

An example of what I want:

enter image description here

Ps: to be clear, each bar shows the proportion of each type.

Upvotes: 0

Views: 1406

Answers (1)

Duck
Duck

Reputation: 39595

Try any of these approaches:

library(tidyverse)
#Data
Date <- c("2010-01-28", "2010-01-28", "2010-01-28", "2010-01-28",
          "2010-02-28","2010-02-28", "2010-02-28", "2010-02-28")
Type <- c("A", "B", "C", "D", "A", "B", "C", "D")
Dollars <- c(1787, 800, 500, 300, 1950, 1100, 890, 450)
Sales <- data.frame(Date, Type, Dollars)
#Month plot 1
Sales %>% mutate(Date=format(as.Date(Date),'%Y-%m')) %>%
  ggplot(aes(x=Date,y=Dollars,fill=Type,group=Type))+
  geom_bar(stat = 'identity',color='black')+
  scale_y_continuous(labels = scales::comma)+
  theme_bw()+
  theme(legend.position = 'top',
        plot.title = element_text(hjust=0.5))+
  ggtitle('Title of my plot')

Output:

enter image description here

Or this:

#Month plot 2
Sales %>% mutate(Date=format(as.Date(Date),'%Y-%m')) %>%
  ggplot(aes(x=Date,y=Dollars,fill=Type,group=Type))+
  geom_bar(stat = 'identity',color='black',position='fill')+
  scale_y_continuous(labels = scales::percent)+
  theme_bw()+
  theme(legend.position = 'top',
        plot.title = element_text(hjust=0.5))+
  ggtitle('Title of my plot')+ylab('Proportion of Dollars')

Output:

enter image description here

Upvotes: 1

Related Questions