【问题标题】:How to draw a combined histogram and cumulative line_plot using ggplot2如何使用 ggplot2 绘制组合直方图和累积 line_plot
【发布时间】:2014-07-24 12:28:12
【问题描述】:

我有 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

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

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

【问题讨论】:

标签: r ggplot2


【解决方案1】:

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

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

【讨论】:

  • 太好了,谢谢!您能否根据 CumulativeSales 添加 geom_point()?
  • 谢谢。最后一个问题。如何添加一个键(图例),说明黑线是累计销售额,红线是销售额?
猜你喜欢
  • 2013-08-23
  • 2021-05-04
  • 2017-01-10
  • 2014-02-02
  • 1970-01-01
  • 2021-05-12
  • 2015-12-05
  • 1970-01-01
  • 2014-05-30
相关资源
最近更新 更多