如何在R绘图中减小图例的大小,同时仍使其可读? [英] How to reduce the size of the legend in R Plot, while still making it readable?

查看:57
本文介绍了如何在R绘图中减小图例的大小,同时仍使其可读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用R中的两个y轴绘制多年来的某些数据.但是,每当我尝试添加图例时,图例就占据了我的图面.当我使用其他建议的解决方案(例如 keyword 和/或使用 cex 参数)时,在另一篇帖子中建议

当我在 legend()中使用 cex = 0.5 参数时,它开始变得不可读:

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

解决方案

图例中的空白告诉我您手动扩大了绘图窗口.当涉及到手动调整大小时,图例无法很好地缩放.

解决方案是在绘制之前打开一个您需要的确切大小的图.在Windows中,这是通过 windows(width = 10,height = 8)完成的.单位为英寸.如您在下面看到的,图例紧紧地位于角落.

I am trying to plot some data over years with two y-axes in R. However, whenever I try to include a legend, the the legend dominates my plot. When I use solutions suggested elsewhere like keyword and/or using the cex argument, suggested in another post here, it either becomes unreadable or is still too big.

Here is my example with randomly generated data:

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

I want a second y-axis, the difference of the two means over the years

df$diff <- abs(df$mean1 - df$mean2)

When I plot using the code below to create two y-axes:

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:

When I use the cex=0.5 argument in the legend(), it starts to become unreadable:

Is there a way to format my legend in a clear, readable manner? Better than what I have?

解决方案

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.

这篇关于如何在R绘图中减小图例的大小,同时仍使其可读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆