如何在R Plot中减小图例的大小,同时仍然使其可读?

时间:2016-08-24 21:17:07

标签: r plot legend

我试图用R中的两个y轴绘制一些数据。但是,每当我尝试包含一个图例时,这个图例就会占据我的情节。当我使用其他地方建议的解决方案,例如cex和/或使用#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)) 参数,在另一篇帖子here中建议时,它会变得不可读或仍然太大。

以下是我随机生成数据的示例:

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

当我使用下面的代码绘制以创建两个y轴时:

cex=0.5

我得到: enter image description here

当我在legend()中使用{{1}}参数时,它开始变得不可读: enter image description here

有没有办法以清晰,可读的方式格式化我的图例?比我的更好?

2 个答案:

答案 0 :(得分:3)

The white space in the legend tells me that you manually widened your plot window. Legends do not scale well when it comes to manual re-sizing.

The solution is opening a plot of the exact size you need before plotting. In Windows, this is done with windows(width=10, height=8). Units are in inches. As you can see below, the legend sits tightly in the corner. enter image description here

答案 1 :(得分:1)

显然,我忘记了进行故障排除的第一步:关闭它。我今天早上醒来又跑了剧本。即使使用cex = 0.5,结果也很好。我选择使用cex = 0.75。我仍然感谢任何帮助,为什么会这样。昨天花了很多时间试图修复我的图例,相同的代码工作并收到此产品(cex=0.75): enter image description here