R barplot错误的组着色

时间:2017-09-14 15:20:09

标签: r plot

我尝试使用R创建条形图,但图例中的组着色看起来不对。

enter image description here

data = c(29,5,22,12,20,11,14,15,21,8)

colors = c(gray.colors(1, start = .1),gray.colors(1, start = .1),
           gray.colors(1, start = .3),gray.colors(1, start = .3),
           gray.colors(1, start = .5),gray.colors(1, start = .5),
           gray.colors(1, start = .7),gray.colors(1, start = .7),
           gray.colors(1, start = .9),gray.colors(1, start = .9))

names = c('1','1','2','2','3','3','4','4','5','5')

barplot(rev(data), horiz=TRUE, col = rev(colors), names.arg = rev(names),
        legend.text = rev(c("1","2","3","4","5")), las=1, xlim = c(0,30), 
        args.legend = list(x ='bottomright', inset=c(0,0.05))
)

我可以想象造成这种情况的原因。我最初的猜测是我应该使用矩阵而不是矢量,然后设置beside = True,但是当我这样做时,条形均匀分布。

1 个答案:

答案 0 :(得分:6)

您可以覆盖图例的fill选项。

barplot(rev(data), horiz=TRUE, col = rev(colors), 
        names.arg = rev(names),
        legend.text = rev(c("1","2","3","4","5")), 
        las=1, xlim = c(0,30), 
        args.legend = list(x ='bottomright', inset=c(0,0.05), 
                           fill=unique(colors))
)