在ggplot2中向双条形图添加线条

Add line to double bar graph in ggplot2

我有以下情节和代码。我想绘制 "Plan" 数据

这是我使用的数据的简单版本:

  times=c("12AM", "1AM", "2AM")
  times = factor(times, levels=c("12AM", "1AM", "2AM"),ordered = TRUE)

  graph_df=data.frame(times,
                      c(12,15,18),
                      c(12,16,14),
                      c(12,17,20))
  colnames(graph_df)=c("Time","LY", "TY", "Plan")

这是我用于 ggplot 的代码:

      library(ggplot2)
      library(scales) 

      df_long=melt(graph_df)

      ggplot(df_long,aes(Time,value,fill=variable))+
            geom_bar(stat="identity",position="dodge")+ 
            theme(text = element_text(size=10),axis.title.y=element_blank(),legend.title=element_blank(),
                  axis.title.x=element_blank(),plot.title = element_text(size=20),
                  axis.text.x = element_text(angle=45, vjust=1,colour = "black"),
                  axis.text.y = element_text(colour = "black"))+
            #scale_y_continuous(expand = c(0,0), limits = c(0,1.1*max(graph_df[,2:4])),labels = dollar)+
            ggtitle("Total Revenue to Plan")

您可以 运行 提供的代码并查看它生成的图表。

这是我的问题:如何使 Plan 变量成为我已有的双条形图上的一条线?我将以下内容添加到我的 ggplot

geom_line(aes(x=as.numeric(Time),y=graph_df$Plan))+

但出现错误:

Error: Aesthetics must either be length one, or the same length as the dataProblems:graph_df$Plan

如有任何帮助,我们将不胜感激!

如果您调用原始图表 g,则使用:

  g + geom_line(data = graph_df,
      mapping = aes(x = Time, y = Plan, group = 1),
      inherit.aes = F)

Ggplot 最适合处理数据框中的数据,所以既然你已经有了 graph_df,就把它放在那里!此外,您已经建立了一个因子 x 轴,因此尝试将您的 Time 转换为数字是矛盾的。

通常,当为多个分类值添加一条线时,您需要一种分组美学,以便它知道要连接哪些点。由于您只画一条线,我们可以将 group 设置为常量。

最后,由于 fill = variable 在您的初始情节中,您的线层将继承这种美感 - 这是一个问题。我通过为线层设置 inherit.aes = F 来解决这个问题,但正如弗兰克建议的那样,您也可以将 fill 映射移动到条形层而不是初始化...尽管 y = value 可能仍然会抛出一切顺利(我没有测试)。