更改 R 中图例的边距

twe*_*kye 5 r legend bar-chart

我对 R 很陌生,所以我在这里遇到了一些困难,而且我还没有找到问题的答案。

我正在尝试在 R 中生成一个简单的条形图,并且我已将 x 轴变量标签设置为垂直,使用las=2. par(mar=c(20,15,5,3))然后,我使用和更改了条形图的边距,以便标签不会与 xlab 标签重叠par(mgp=c(6,1,0))

我想为此添加一个图例,但我的图例采用了图表本身的边距尺寸,因此它看起来太大并且不适合。我尝试使用cex,但这只会影响图例中的文本。无论如何,我是否可以独立更改图例边距(或图形边距)?

这是我编码的内容:

par(mar=c(20,15,5,3))
par(mgp=c(6,1,0))
par(xpd=TRUE)
barplot(
  names.arg=c("Africa", "Central America, South America, Caribbean", 
              "Middle East", "Central and Eastern Europe", 
              "South and East Asia"),
  cex.names=0.8, las=2, t(YLL), 
  ylab="Percentage (%)", ylim=c(0,100), main="", beside=TRUE, 
  col= c("green4", "orange"),xlab="Regions", mar=c(20,15,5,3)
)
legend(
  10, 100, 
  legend=c("Communicable diseases", "Communicable diseases"), 
  fill= c("green4", "orange"), cex=0.7
)
Run Code Online (Sandbox Code Playgroud)

我将非常感谢您的帮助,谢谢。

Sta*_*AGV 5

legend您还可以使用function:y.interspx.intersp的参数text.width来减小图例的大小。

\n\n

这里有一个例子:

\n\n
set.seed(55) # Set the seed of R\xe2\x80\x98s random number generator\nx <- 1:10\ny <- runif(10, min=0, max=100) # Generating random numbers\nz <- runif(10, min=0, max=100) # Generating random numbers\nplot(x,y, type="l", ylim=c(0,100), ylab="y and z")\npar(new=TRUE)\nplot(x,z, type="l", col="red", ylim=c(0,100), ylab=NA, xaxt=\'n\', yaxt=\'n\')\nlegend("topright", c("y","z"), lty="solid", col=c("black", "red"))\n
Run Code Online (Sandbox Code Playgroud)\n\n

前

\n\n

并修改该函数的相同代码legend

\n\n
set.seed(55) # Set the seed of R\xe2\x80\x98s random number generator\nx <- 1:10\ny <- runif(10, min=0, max=100) # Generating random numbers\nz <- runif(10, min=0, max=100) # Generating random numbers\nplot(x,y, type="l", ylim=c(0,100), ylab="y and z")\npar(new=TRUE)\nplot(x,z, type="l", col="red", ylim=c(0,100), ylab=NA, xaxt=\'n\', yaxt=\'n\')\nlegend("topright", c("y","z"), lty="solid", col=c("black", "red"), y.intersp=0.5,x.intersp=0.5,text.width=0.1)\n
Run Code Online (Sandbox Code Playgroud)\n\n

后

\n


小智 0

我不知道我是否正确理解你的问题,但也许你可以尝试 x.intersp 或 y.intersp 来修改图例的 x 和 y 轴的间距。例如,您可以添加 x.intersp=0.5 以使图例的元素在 x 轴上更靠近。

如果这不起作用并且您提供了屏幕截图,也许我可以尝试更好地帮助您。