我有2个数据框,我想创建一个图,其中来自"现在"数据框是一个条形图和来自"历史"的数据。数据框是折线图。
我创建了条形图,但我不确定如何覆盖"历史"数据框作为一条线,只有一个图例。传奇 应包含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()
任何想法如何让积分显示在线上而不是条形图上?
答案 0 :(得分:2)
现在这应该是你所要求的(但是颜色非常难看):
#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"))
给出
对于你要求的额外噱头,有很多关于SO的参考资料,例如:我用过: