0

I try to create a graph which combines both barplot and lineplot and I aim to assign the lineplot to the second axis. However, it seems not to work well.

region=c("central","east","north")
profit=c(100, 150, 200)
sales=c(1000, 2000, 5000)
df_test<-data.frame(region, profit,sales)
df_test2<-select(df_test,region, profit)
ggplot()+geom_bar(data=df_test,aes(x=region,y=sales),stat = 
"identity",fill=3)+geom_line(data=df_test2,aes(x=region, y=profit),inherit.aes = 
FALSE,group=1)+scale_y_continuous(sec.axis = sec_axis(~.*0.1,name = "profit"))

enter image description here

Bill P
  • 3,622
  • 10
  • 20
  • 32

1 Answers1

0

When you scale the second y-axis by 0.1 you need to multiply your y-values (df_test2$profit) with the reciprocal, 10.

ggplot()+geom_bar(data=df_test,aes(x=region,y=sales),stat = "identity",fill=3)+geom_line(data=df_test2,aes(x=region, y=profit*10),inherit.aes = FALSE,group=1)+scale_y_continuous(sec.axis = sec_axis(~.*0.1,name = "profit"))

Jeppe
  • 1