我有以下情节和代码。我想绘制"计划"数据
这是我使用的简单数据版本:
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
非常感谢任何帮助!
答案 0 :(得分:1)
如果您调用原始图表@ def stuffs[H <: HList, PA <: HList, SA <: HList, PB <: HList, SB <: HList] (hl:H)(
implicit
pa:Partition.Aux[H,List[A],PA, SA ],
pb:Partition.Aux[H,B,PB, SB ],
prefixToTraversableA: ToTraversable[SA, List],
prefixToTraversableB: ToTraversable[SB, List]
) = (hl.filter[List[A]].to[List], hl.filter[B].to[List])
Compilation Failed
Main.scala:380: could not find implicit value for parameter ts: shapeless.ops.hlist.ToTraversable[pa.Prefix,List]
) = (hl.filter[List[A]].to[List], hl.filter[B].to[List])
^
Main.scala:380: could not find implicit value for parameter ts: shapeless.ops.hlist.ToTraversable[pb.Prefix,List]
) = (hl.filter[List[A]].to[List], hl.filter[B].to[List])
^
,请使用:
g
Ggplot最适合数据框中的数据,因此您已经 g + geom_line(data = graph_df,
mapping = aes(x = Time, y = Plan, group = 1),
inherit.aes = F)
保留了它!此外,您已建立因子x轴,因此尝试将graph_df
转换为数字是相互矛盾的。
通常,为多个分类值添加一行时,您需要一个分组美学,以便知道要连接的点。由于您只绘制一行,我们可以将group设置为常量。
最后,由于Time
位于您的初始图中,因此您的线图层将继承该美学 - 这是一个问题。我通过为行图层设置fill = variable
来解决这个问题,但正如Frank建议您也可以将inherit.aes = F
映射移动到条形图层而不是初始化...尽管fill
可能仍会抛出关闭(我没有测试)。