简体   繁体   中英

Combining geom_bar with geom_line in one plot

I have tried to combine 2 plots into 1 plot. But the geom_line doesn't show up and, the y-axis to the right is not in %.

The geom_bar shows what i want it to, but the geom_line does not show up in the ggplot. The geom_line is a %, and shows the relationship between BV and FV, % = BG/FV.

My table as it looks like in Excel.

Comma for Europeans:

Aar Type 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

All those who doesn't use comma:

Aar Type 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

My code:

    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) ))

Shows the barplots with 2 y-axis

How it should look like

you can try

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)))

在此处输入图像描述

Note that the line values are upscaled according the max mia_kr value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM