R ggplot2在同一图表上绘制条形图和线条

R ggplot2在同一图表上绘制条形图和线条,r,R,我有两个数据框,我想创建一个图,其中“现在”数据框中的数据是条形图,“历史”数据框中的数据是折线图 我已经创建了条形图,但不确定如何将“历史”数据框中的数据叠加为一条线,并且只有一个图例。传说 应包含4个元素:a_today、b_today、a_hist、b_hist historical= data.frame(x = c("10:00","10:30","11:00","10:00","10:30","11:00"), value= c(1,2,3,4,5,6), category = c(

我有两个数据框,我想创建一个图,其中“现在”数据框中的数据是条形图,“历史”数据框中的数据是折线图

我已经创建了条形图,但不确定如何将“历史”数据框中的数据叠加为一条线,并且只有一个图例。传说 应包含4个元素:a_today、b_today、a_hist、b_hist

historical= data.frame(x = c("10:00","10:30","11:00","10:00","10:30","11:00"), value= c(1,2,3,4,5,6), category = c("a_hist","a_hist","a_hist","b_hist","b_hist","b_hist"))
historical

now= data.frame(x = c("10:00","10:30","10:00","10:30"), value= c(8,6,10,10), category = c("a_today","a_today","b_today","b_today"))
now

ggplot(now, aes(x=x, y=value, fill = category )) + 
  geom_bar(stat= "identity",position=position_dodge()) + ggtitle("this is my plot")




ggplot(now, aes(x=x, y=value, fill = category )) + geom_bar(stat= "identity",position=position_dodge()) + ggtitle("this is my plot") + 
  geom_line(data = historical, aes(x=x, y=value, group = category, col=category)) + scale_color_discrete(guide = F) + 
  scale_fill_manual(values = c("a_hist"= "green","b_hist" ="salmon","a_today" = "yellow", "b_today" = "red") ) + geom_point()


你知道如何让分数正确地显示在直线上而不是条形图上吗?

现在这应该是你想要的全部(但颜色非常难看):

给予

对于您要求的其他噱头,有很多关于SO的参考资料,例如,我使用了:


+geom_线(数据=历史,aes(x=x,y=value,fill=category))
ggplot(现在,aes(x=x,y=value,fill=category))+geom_条(stat=“identity”,position=position\u dodge())+ggtitle(“这是我的绘图”)+geom_线(数据=历史,aes(x=x,y=value,group=category,col=category))+scale\u离散(guide=F)
几乎就是您想要的,但在图例中,我假设您想要历史数据行?!?差不多了。如果传说中有台词那就太好了。如何设置4个时间序列的颜色并向线条添加点?谢谢。对于后一个问题,请尝试谷歌:对于手动图例构建,哦,如果您想添加点
+geom_点(数据=历史,aes(x=x,y=value,group=category,col=category))
就可以了,我会在添加geom_点()时更新我的答案,它会添加到条形图而不是折线图中。有什么想法吗?请看我对上述问题的评论,您需要重新指定映射和数据,从而添加
+geom_点(数据=历史,aes(x=x,y=value,group=category,col=category))
#data
historical= data.frame(x = c("10:00","10:30","11:00","10:00","10:30","11:00"), value= c(1,2,3,4,5,6), category = c("a_hist","a_hist","a_hist","b_hist","b_hist","b_hist"))
now= data.frame(x = c("10:00","10:30","10:00","10:30"), value= c(8,6,10,10), category = c("a_today","a_today","b_today","b_today"))
#plot
ggplot() + 


geom_bar(data = now, aes(x=x, y=value, fill = category ), stat= "identity",position=position_dodge()) + 
  ggtitle("this is my plot") +
  geom_line(data = historical, aes(x=x, y=value, group = category, col=category)) + 
  geom_point(data = historical, aes(x=x, y=value, group = category, col=category)) +
  scale_fill_manual(name = "today", 
                    values = c("a_today"="green", "b_today" = "purple"), 
                    labels = c("a_today", "b_today")) + 
  scale_color_manual(name = "historical", 
                     values = c("a_hist"="red", "b_hist"="blue"),
                     labels = c("a_hist", "b_hist"))