2017-09-14 90 views
3

我正在嘗試使用R創建barplot,但傳奇中的組着色錯誤。R barplot的錯誤組着色

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,但是當我這樣做時,條不是均勻間隔的。

+0

也許我錯了,但你的傳奇有太少的顏色。如果你增加矢量的長度,legend.text = rev(rep(c(「1」,「2」,「3」,「4」,「5」),each = 2))',它不會看起來不再錯了。但那個傳說並不是你期望的那樣。 –

回答

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)) 
)