为什么线图不跟随ggplot中的第二个y轴?

时间:2019-09-24 10:06:51

标签: r ggplot2

我尝试创建一个结合了barplot和lineplot的图形,我的目标是将lineplot分配给第二个轴。但是,它似乎不能很好地工作。

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

1 个答案:

答案 0 :(得分:0)

将第二个y轴缩放0.1时,需要将y值(df_test2 $ profit)乘以倒数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"))

相关问题