【问题标题】:R plot: Legend background sizeR plot:图例背景大小
【发布时间】:2021-03-17 04:59:48
【问题描述】:

我正在使用 R 绘制图(特别是散点图),并注意到图例的背景尺寸过大(如下所示):

有什么办法可以缩小面积吗?

我尝试更改cex,但它不仅缩小了面积,还缩小了字体大小。我想保持字体大小,但缩小图例区域。

以防万一,我附上了我用过的图例代码:

legend(x="bottomleft", legend = c("Survived (0)", "Died (1)"), 
         col=c(1:length(levels(Noadr.for.plot2$Death))), pch = c(19, 17),
         y.intersp = 0.4,
         bg = "gray")

[更新] 在这里,修改后的情节。我能够修改文本宽度,但不能修改高度(如下所示):

【问题讨论】:

    标签: r plot legend scatter-plot


    【解决方案1】:

    您可以执行以下操作:

    attach(mtcars)
    plot(wt, mpg, main="Scatterplot Example",
         xlab="Car Weight ", ylab="Miles Per Gallon ", pch=19)
    # op <- par(cex = 1)
    
    text = c("Survived (0)", "Died (1)")
    cex_val = 1
    
    legend(x="bottomleft", legend = text,
           pch = c(19, 17), cex=cex_val,
           y.intersp = 1,
           bg = "gray",
           text.width = strwidth(text)[1]*cex_val)
    

    图例宽度的一部分由您使用的标签的最长宽度决定,该宽度是通过strwidth 计算的,因此通过将其设置为文本宽度,您可以在保持字体大小的同时缩小框。

    【讨论】:

    • @@David S 嗨,大卫!感谢您的评论。我成功工作了!但是,我能够修改文本宽度,而不是高度。请看上图(我上传了更新的图)。我以为会有一个类似text.height的函数,但不幸的是它不存在......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2019-10-03
    • 2013-03-30
    • 2019-08-18
    • 2018-02-03
    相关资源
    最近更新 更多