R barplot错误的组着色

yel*_*w01 3 plot r

我正在尝试使用R创建一个条形图,但图例中的组颜色看起来不对.

在此输入图像描述

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))
)
Run Code Online (Sandbox Code Playgroud)

我能想象是什么造成了这种情况.我最初的猜测是我应该使用矩阵而不是矢量然后设置beside = True,但是当我这样做时,条形间距不均匀.

Kot*_*ori 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))
)
Run Code Online (Sandbox Code Playgroud)