簡體   English   中英

ggplot2在同一圖表上繪制條形圖和折線圖

[英]ggplot2 plotting bars and lines on same chart

我有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()

在此處輸入圖片說明

知道如何獲取點以正確顯示在直線上而不是條形圖上嗎?

現在,這應該是您所要求的(但實際上是難看的顏色):

#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的參考,例如,我曾經使用過:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM