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

Phi*_*hil 2 plot r legend

我试图用 R 中的两个 y 轴绘制多年来的一些数据。但是,每当我尝试包含一个图例时,图例主宰了我的情节。当我使用其他地方建议的解决方案时,例如keyword和/或使用此处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)) 
Run Code Online (Sandbox Code Playgroud)

我想要第二个 y 轴,多年来这两种平均值的差异

df$diff <- abs(df$mean1 - df$mean2)
Run Code Online (Sandbox Code Playgroud)

当我使用下面的代码绘制两个 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"))
Run Code Online (Sandbox Code Playgroud)

我得到: 在此处输入图片说明

当我在 中使用cex=0.5参数时legend(),它开始变得不可读: 在此处输入图片说明

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

Pie*_*nte 6

图例中的空白告诉我您手动加宽了绘图窗口。在手动调整大小时,图例无法很好地扩展。

解决方案是在绘图之前打开您需要的确切大小的绘图。在 Windows 中,这是通过windows(width=10, height=8). 单位为英寸。正如您在下面看到的,图例紧紧地坐在角落里。 在此处输入图片说明