【问题标题】:Displaying correctly legends in barplot在条形图中正确显示图例
【发布时间】:2019-11-04 16:15:52
【问题描述】:

我想在 y 轴下显示图例,而不是垂直列表,而是水平列表。如果不可能,您是否有任何解决方案可以建议不要让图例与图形重叠? 我找到了这类问题的答案,但我不明白。

meute1 = c(78.6,9.7,0.6,11.1)
meute2 = c(60.8,35.7,0.2,3.3) 
meute3 = c(61.2,16.5,2.3,20.0) 
meute4 = c(54.6,10.7,9.8,24.9)
meutes=cbind(meute1,meute2,meute3,meute4)
coul= brewer.pal(n = length(meute1), name = 'Set3')

barplot(height = meutes, col=coul, horiz=T,
        names.arg = c("Meute 1","Meute 2","Meute 3", "Meute 4"),
        legend.text = c("Ongulés sauvage", "Petits et moyens mammifères", "Micro-mammifères", "Appâts"), 
        args.legend = list(x = "topright"),las=1)

【问题讨论】:

    标签: r bar-chart


    【解决方案1】:

    我认为您正在寻找类似以下的内容。您只需向args.legend 添加一些参数,即horiz = T 使其水平,x 将图例移动到图的底部,inset 将图例向下移动,cex 用于更改字体大小。我无法让颜色发挥作用,但你明白了:

    barplot(height = meutes, horiz=T,
            names.arg = c("Meute 1","Meute 2","Meute 3", "Meute 4"),
            legend.text = c("Ongulés sauvage",
                            "Petits et moyens mammifères",
                            "Micro-mammifères", "Appâts"
                            ), 
            args.legend = list(x = "bottom",       # <- move legend to bottom
                               inset = c(0, -.25), # <- move legend outside plot
                               horiz = T,          # <- make legend horizontal
                               cex = .8),          # <- change legend font size
            las=1
            )
    

    【讨论】:

    • 我确实是这么想的!您是否知道如何在图例框中平均分配标签?我试过'text.width,但是找到正确的间距很长,而且不是很准确。
    • @HannahTamia 我认为这个问题没有简单的答案。我已经设法使用text.width = c(20, 25, 0, 17) 获得一些控制,调整cex,并设置bty = "n" 以关闭该框(当您开始移动文本时,该框看起来很奇怪)。你只需要摆弄参数。
    • @HannahTamia 如果我的回答解决了您的问题,您可以投票并点击 √ 接受吗?这样我就能得到一些代表,其他有同样问题的人知道什么对你有用。
    【解决方案2】:

    使用xpd=TRUE 允许将图例定位在情节之外

    # Add extra space at the bottom of plot area; change clipping to figure
    par(mar=c(8.1, 4.1, 4.1, 2.1), xpd=TRUE)
    library(RColorBrewer)
    
    barplot(height = meutes, col=coul, horiz=T,
            names.arg = c("Meute 1","Meute 2","Meute 3", "Meute 4"),
            legend.text = c("Ongulés sauvage", "Petits et moyens mammifères", "Micro-mammifères", "Appâts"), 
            args.legend = list(x = "bottom", text.width = c(25, 30, 0, 17), 
                           bty='n', horiz = T, inset=-0.2, cex = .8), las=1)
    

    【讨论】:

    • 我在 'x="topright" 之后添加了 'xpd=TRUE',但什么也没发生
    猜你喜欢
    • 2012-12-05
    • 2019-11-19
    • 1970-01-01
    • 2013-07-14
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    相关资源
    最近更新 更多