How to reduce the size of the legend in R Plot, while still making it readable?

时光怂恿深爱的人放手 提交于 2020-12-12 04:03:08

问题


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?


回答1:


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.




回答2:


Apparently, I forgot to do the first step of troubleshooting: turn things off an turn it on. I woke up this morning and ran the script again. Even with cex = 0.5 and it turned out fine. I chose to use cex = 0.75. I would still appreciate any help in why that might be. Spent many hours yesterday trying to fix my legend and the same code works and receives this product (cex=0.75):



来源:https://stackoverflow.com/questions/39133170/how-to-reduce-the-size-of-the-legend-in-r-plot-while-still-making-it-readable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!