如何使用ggplot2绘制组合直方图和累积line_plot

时间:2014-07-24 12:28:12

标签: r ggplot2

我有10家商店的销售数据。我希望有一个组合图,显示每个商店的销售直方图和累计销售的线图。

我可以单独绘制两个,但我不知道如何在同一个图表上重现这两个图。我是新手使用ggplot2,所以任何额外的指针都会非常感激。

我的数据:

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")

自行绘制直方图:

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

自行绘制线条:

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

如何在一张图上一起绘制它们?

注意:对原始代码的任何修改都非常受欢迎(任何使图表看起来更好的东西)。

1 个答案:

答案 0 :(得分:3)

您可以使用原始数据框,然后使用Sales作为geom_bar()CumulativeSales的y值作为geom_line()geom_point()的y。在group=1的{​​{1}}内添加aes()可确保数据已连接。如果您还需要一个图例,那么一种方法是将geom_line()fill=放在linetype=中,并附上您要显示的名称。

aes()

enter image description here

相关问题