我试图用 R 中的两个 y 轴绘制多年来的一些数据。但是,每当我尝试包含图例时,图例就会主导我的绘图。当我使用其他地方建议的解决方案时,例如keyword
和/或使用cex
论据,在另一篇文章中建议here https://stackoverflow.com/questions/30402254/printing-too-big-legend-box-in-rstudio,它要么变得不可读,要么仍然太大。
这是我使用随机生成的数据的示例:
#Create years
year.df <- seq(1974, 2014, 1)
# Create y-axis data
set.seed(75)
mean1 <- rnorm(length(year.df), 52.49, 0.87)
mean2 <- rnorm(length(year.df), 52.47, 0.96)
#Create dataframe
df <- data.frame(cbind(year.df, mean1, mean2))
我想要第二个 y 轴,多年来这两个平均值的差异
df$diff <- abs(df$mean1 - df$mean2)
当我使用下面的代码绘图来创建两个 y 轴时:
par(mfrow=c(1,1), mar=c(5.1,4.1,4.1,5.1))
with(df, plot(year.df, mean1, type = "l", lwd=4, xlab="Year", ylab="Mean", ylim=c(48,58)))
with(df, lines(year.df, mean2, type = "l", col="green", lwd=4))
par(new=TRUE)
with(df, plot(year.df, diff, type="l", axes=FALSE, xlab=NA, ylab=NA, col="red", lty=5, ylim=c(0,10)))
axis(side = 4)
mtext(side = 4, line = 3, "Annual Difference")
legend("topleft",
legend=c("Calculated", "MST", "Diff"),
lty=c(1,1,5), col=c("black", "green", "red"))
I get:
![enter image description here](https://i.stack.imgur.com/pahuv.png)
When I use the cex=0.5
argument in the legend()
, it starts to become unreadable:
![enter image description here](https://i.stack.imgur.com/Izg9m.png)
有没有办法以清晰易读的方式格式化我的图例?比我拥有的更好吗?