user3580643
user3580643

Reputation: 111

How to draw a combined histogram and cumulative line_plot using ggplot2

I have sales data for 10 stores. I would like to have a combined plot that shows both a histogram of the sales per store and a line plot of cumulative sales.

I can plot the two separately, but I don't know how to reproduce both plots on the same graph. I am new to using ggplot2, so any extra pointers would be much appreciated.

My data:

data <- structure(list(Stores = c("store1", "store2", "store3", "store4", 
"store5", "store6", "store7", "store8", "store9", "store10"), 
Sales = c(243.42, 180.02, 156.51, 145.09, 141.9, 104.9, 102.61, 
101.09, 88.53, 84.2), CumulativeSales = c(243.42, 423.44, 
579.95, 725.04, 866.94, 971.84, 1074.45, 1175.54, 1264.07, 
1348.27)), .Names = c("Stores", "Sales", "CumulativeSales"
), row.names = c(NA, 10L), class = "data.frame")

Plotting the histogram by itself:

data_hist <- data[,1:2]
p_hist <- (ggplot(data=data_hist, aes(x=Stores, y=Sales, fill=Stores)) + 
                         geom_bar(fill="#DD8888", width=.7, stat="identity") +
                         guides(fill=FALSE) +
                         xlab("Stores") + ylab("Sales") +
                         theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) +
                         scale_y_continuous(breaks=seq(0,2600,50))) +
  scale_x_discrete(limits=data[,1])
p_hist

Plotting the line by itself:

data_line <- data[,c(1,3)]
p_line <- (ggplot(data=data_line, aes(x=Stores, y=CumulativeSales, group=1)) + 
         geom_line(fill="#DD8888", size=1.5) +
         geom_point(size=3, fill="white") +
         xlab("Stores") + ylab("Sales") +
         theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) +
         scale_y_continuous(breaks=seq(0,2600,50))) +
 scale_x_discrete(limits=data[,1])
p_line

How can I plot them together on one graph?

Note: Any modifications to the original code are more than welcome (anything to make the graphs look better).

Upvotes: 2

Views: 5405

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98579

You can use your original data frame and then use Sales as y values for geom_bar() and CumulativeSales as y for geom_line() and geom_point(). Adding group=1 inside the aes() of geom_line() will ensure that data are connected. If you need also a legend, then one way is to put fill= and linetype= inside the aes() with name you want to show.

ggplot(data=data, aes(x=Stores)) + 
      geom_bar(aes(y=Sales,fill="Sales"), width=.7, stat="identity") +
      geom_line(aes(y=CumulativeSales,group=1,linetype="Cumulative sales"))+
      geom_point(aes(y=CumulativeSales))+
      xlab("Stores") + ylab("Sales") +
      labs(fill="",linetype="")+
      theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) +
      scale_x_discrete(limits=data[,1])

enter image description here

Upvotes: 3

Related Questions