在条形图图例中使用名称而不是颜色

时间:2016-04-27 21:21:16

标签: r bar-chart

我在RStudio中有一个表(名为“c2”),其中包含以下值:

c2 = c(AB=6821, SK=1896, MB=1182, NT=112, YT=88, NU=74, BC=10, ON=3, CA=1, NB=1, PL=1)
c2
#   AB   SK   MB   NT   YT   NU   BC   ON   CA   NB   PL 
# 6821 1896 1182  112   88   74   10    3    1    1    1 

我希望显示一个条形图,其中包含总结计数的图例。我的剧本是:

barplot(c2, main="Active Subscriber Counts", 
        xlab="PO", col = rainbow(20),
        ylim = c(0,7000), beside=TRUE, legend.text=c2)

这给了我:

enter image description here

我的问题在于图例 - 而不是按颜色显示计数,我希望它按“PO”(“AB”,“SK”,“MB”等)显示计数。我如何修改我的代码来完成它?

1 个答案:

答案 0 :(得分:0)

如果您有一个命名向量,只需将legend.text参数从c2切换为FALSE,然后使用legend()函数即可获得更好的控制效果。以下是一个kluge,但可能运作良好。问题是pch参数似乎需要单个字符串:

c2 <- c(AB=6821, SK=1896, MB=1182, NT=112, YT=88, NU=74, BC=10, ON=3, CA=1, NB=1, PL=1)

windows()
  barplot(c2, main="Active Subscriber Counts", 
          xlab="PO", col = rainbow(20),
          ylim = c(0,7000), beside=TRUE, legend.text=FALSE)
  legend("topright", legend=paste(names(c2), c2), pch="")

enter image description here