ggplot2:添加另一个具有不同比例的y轴

时间:2019-08-27 20:05:30

标签: r ggplot2 yaxis

在绘制第二个y轴时,第一个y轴会变形,请参见下文:

Treatment<-c("T1-Control", "T1-Control", "T1-Control", "T1-Control", "T1-Control",
             "T1-Inseticide", "T1-Inseticide", "T1-Inseticide", "T1-Inseticide", "T1-Inseticide",
             "T2-Control", "T2-Control", "T2-Control", "T2-Control", "T2-Control",
             "T2-Inseticide", "T2-Inseticide", "T2-Inseticide", "T2-Inseticide", "T2-Inseticide")
Measurement<-rep(c(1, 2, 3, 4, 5), 4)
Infestation<-c(12, 8, 9, 4, 5, 1, 0, 0, 2, 1, 18, 11, 28, 9, 15, 0, 2, 1, 0, 2)
Rainfall<-rep(c(56.8, 236.1, 71, 259, 145), 4)
d<-data.frame(cbind(Treatment, Measurement, Infestation, Rainfall))
i<-c(2,3,4)
d[,i]<-apply(d[,i],2,function(x) as.numeric(as.character(x)))

max(d$Rainfall)/max(d$Infestation)

library(ggplot2)
p<-ggplot(d, aes(x= Measurement,y=Infestation,linetype = factor(Treatment))) +
       geom_point(mapping=aes(x= Measurement, y=Infestation, shape = factor(Treatment))) +
       geom_line(mapping=aes(x= Measurement, y=Infestation, linetype = factor(Treatment)), size=0.3) +
       geom_line(aes(y= Rainfall))+
       scale_y_continuous(name="Infestation", sec.axis = sec_axis(~9.25*., name=" Rainfall "))
p

Result with distorted first y axis

0至28之间的黑线是根据处理(4)的昆虫侵染的结果。蓝线表示评估期间的降雨量。轴的尺寸不同。我需要固定第二个y轴刻度,而首先不要变形。这是数据库的一小部分样本。 我需要第二个y轴限制在0到260之间。

我该如何解决?拜托,有什么想法吗?

0 个答案:

没有答案