【问题标题】:Overlaying a Bar chart with multiple bars with a line graph with ggplot2 in R在R中使用带有ggplot2的折线图覆盖具有多个条形的条形图
【发布时间】:2018-06-20 14:41:10
【问题描述】:

我正在尝试使用 ggplot2 创建一个特定的图表,这是我的数据集。

df.1 <- data.frame(
Month = c("Dec-17", "Jan-18", "Feb-18", "Mar-18", "Apr-18", "May-18"), 
Total_1 = c(25, 14, 8, 16, 137, 170), 
Total_2 = c(3, 2, 3, 2, 18, 27), 
Total_3 = c(5, 4, 3, 2, 16, 54)
)

我希望 Total_2 和 Total_3 是条形图,而 Total_1 是一个折线图,都在同一个图表上。我的编码已经做到了这一点:

df.1 <- melt(df.1,id.vars = "Month")
#reorder the month column so it isn't alphabetical
df.1$Month <- factor(df.1$Month, levels(df.1$Month)[c(2,4,3,5,1,6)])
#partition my data into the 2 different graphs I need
df.1.1 <- df.1[7:18,]
df.1.2 <- df.1[1:6,]

ggplot(data = df.1.1, aes(x = df.1.1$Month, y = df.1.1$value, fill = df.1.1$variable)) + 
  geom_bar(position = position_dodge(),stat = 'identity') +
  geom_line(data = df.1.2, aes(x=df.1.2$id, y=df.1.2$value, group=1))

这给了我错误:

错误:美学必须是长度1或与数据相同(6):x,y,填充

我的ggplot代码的前半部分,即:

    ggplot(data = df.1.1, aes(x = df.1.1$Month, y = df.1.1$value, fill = df.1.1$variable)) + 
  geom_bar(position = position_dodge(),stat = 'identity')

这给了我以下图表:

我只需要线条部分位于此之上。我可以使用这段代码自己生成折线图:

ggplot(data = df.1.2, aes(x = df.1.2$Month, y = df.1.2$value, group = 1)) + 
      geom_line()

看起来像这样:

非常感谢任何帮助使其工作的帮助,如果您需要更多信息,请不要害怕询问。

谢谢!

【问题讨论】:

    标签: r ggplot2 bar-chart linegraph


    【解决方案1】:

    这里的主要问题是ggplot 调用中的fill。因为你在ggplot(aes()) 中有它,所以它同时传播到geom_bargeom_line。如果你只是在 ggplot(aes()) 中设置fill = variable,你不会得到错误,但你会在图例中有一个 Total_1,这不是我认为你想要的。

    您也不需要在aes() 中使用df.1.1$df.1.2$。您希望将数据放入 data 参数中,然后将变量放入 aes() 中,而无需再次调用数据框。

    这里有一个解决方案。

    ggplot(data = df.1.1, aes(x = Month, y = value)) + 
      geom_bar(aes(fill = variable), position = position_dodge(),stat = 'identity') +
      geom_line(data = df.1.2, aes(x=Month, y=value, group=1))
    

    另一个注意事项是您可以使用geom_col 而不是geom_barstat='identity'

    ggplot(data = df.1.1, aes(x = Month, y = value)) + 
      geom_col(aes(fill = variable), position = position_dodge()) +
      geom_line(data = df.1.2, aes(x=Month, y=value, group=1))
    

    【讨论】:

    • 非常感谢您的快速回复,这非常有效!