如何在R语言plot()函数中调整轴标签至更靠近绘图区域?
调整R语言plot()轴标签与绘图区域的距离问题
问题场景
使用以下R代码绘制图形时,轴标签与轴的距离过远,甚至出现标签覆盖刻度数字的情况:
plot(x= T38$Variables, y= T38$Q5_E_38, type = "b", pch=16, col = "red", xlab = "", ylab = "", yaxt = "n", xaxt= "n", main="RMSE ") title(xlab = "Variables", line =1.5, cex.lab = 1.5) title(ylab = "RMSE" , line =1.5, cex.lab = 1.5 ) axis(2, at= T38$Q5_E_38[37], col="red", cex.axis=0.6) axis(1, cex.axis=0.6)
解决方案
有两种简单的调整方式:
1. 修改title()函数的line参数
line参数控制轴标签距离轴线的行数,数值越小,标签越靠近绘图区域。将原代码中line=1.5改为更小的数值(比如0.8或0.5)即可:
plot(x= T38$Variables, y= T38$Q5_E_38, type = "b", pch=16, col = "red", xlab = "", ylab = "", yaxt = "n", xaxt= "n", main="RMSE ") title(xlab = "Variables", line = 0.8, cex.lab = 1.5) title(ylab = "RMSE" , line = 0.8, cex.lab = 1.5 ) axis(2, at= T38$Q5_E_38[37], col="red", cex.axis=0.6) axis(1, cex.axis=0.6)
2. 在plot()中直接设置标签并调整mgp参数
mgp是一个长度为3的向量,分别控制轴标签、刻度标签、轴线的位置(默认值为c(3,1,0))。调小第一个元素的值,就能让轴标签更靠近轴线:
plot(x= T38$Variables, y= T38$Q5_E_38, type = "b", pch=16, col = "red", xlab = "Variables", ylab = "RMSE", yaxt = "n", xaxt= "n", main="RMSE ", mgp = c(2, 1, 0), cex.lab = 1.5) axis(2, at= T38$Q5_E_38[37], col="red", cex.axis=0.6) axis(1, cex.axis=0.6)
这里mgp=c(2,1,0)表示轴标签距离轴线2行,刻度标签距离1行,轴线在0行位置,相比默认值大幅拉近了标签与绘图区域的距离。
内容的提问来源于stack exchange,提问作者BabakK
相关产品推荐
相关产品推荐

