簡體   English   中英

將 geom_bar 與 geom_line 結合在一個 plot

[英]Combining geom_bar with geom_line in one plot

我試圖將 2 個地塊合並為 1 個 plot。 但是 geom_line 沒有出現,並且右邊的 y 軸不在 % 中。

geom_bar 顯示了我想要的,但 geom_line 沒有出現在 ggplot 中。 geom_line 是一個 %,表示 BV 和 FV 之間的關系,% = BG/FV。

我的表在 Excel 中的樣子。

歐洲人的逗號:

阿爾 類型 mia_kr BG
2004年 FV 1918050 0,489221
2004年 BG 938350,0583
2005年 FV 2312210 0,447918
2005年 BG 1035680,125
2006年 FV 2842071 0,416046
2006年 BG 1182431,742
2007年 FV 2910107 0,447245
2007年 BG 1301530,525

所有不使用逗號的人:

阿爾 類型 mia_kr BG
2004年 FV 1918050 0.489221
2004年 BG 938350.0583
2005年 FV 2312210 0.447918
2005年 BG 1035680.125
2006年 FV 2842071 0.416046
2006年 BG 1182431.742
2007年 FV 2910107 0.447245
2007年 BG 1301530.525

我的代碼:

    library(ggplot2)
SAMLET <- data.frame(Aar=c(2004, 2004, 2005, 2005, 2006, 2006, 2007, 2007),
                  Type=c(FV, BG, FV, BG,FV, BG,FV, BG,),
                  mia_kr=c(1918050,938350.0583, 2312210, 1035680.125, 2842071, 1182431.742, 2910107, 1301530.525))
SAMLET_2 <- data.frame(Aar=c(2004, 2005, 2006, 2007,),
BG=c(0.489221, ,0.447918, ,0.416046, , 0.447245, ))



ggplot() + 
  geom_bar(mapping = aes(x= SAMLET$Aar, y= SAMLET$mia_kr, fill = SAMLET$Type), stat="identity",position = "identity")+
  geom_line(mapping = aes(x= SAMLET_2$Aar, y = SAMLET_2$BG),size = 2, color = "blue") +
  scale_y_continuous(labels = scales::format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE),
                     sec.axis = sec_axis(~ ./4,labels = scales::format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE) ))

顯示帶有 2 個 y 軸的條形圖

它應該是什么樣子

你可以試試

ggplot(df, aes(x = Aar)) + 
   geom_col(aes(y = mia_kr, fill = Type)) + 
   geom_line(aes(y = BG*max(mia_kr), group =Type))  +
   scale_y_continuous(labels = scales::format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE),
                     sec.axis = sec_axis(~ ./max(df$mia_kr)))

在此處輸入圖像描述

請注意,線值會根據最大mia_kr值進行放大。

暫無
暫無

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

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