R中水平条上的plottext

时间:2018-05-19 08:05:53

标签: r ggplot2 statistics

我正在尝试绘制条形图,并希望在水平线末端显示百分比..无法得到..出现错误

y <- c('Others(27%)','Environment','Family Life & children','Combating terrorism','Pensions',
   'Europe', 'Housing', 'Education', 'Tax','Benefits','Immigration & Assylum','Health','Economy')
x <- c(27,10,12,15,18,20,20,21,21,25,42,46,49)

mylabels <- c('....27%','10%','12%','15%','18%','20%','20%','21%','21%','25%','42%','46%','49%')

par(mar=c(5,10,4,2)+0.1)
usr <- par( "usr" )
my_bar<-barplot(x,main="British Voters Election Priority (2015)", horiz=TRUE,las = 1,
        names.arg=y, xlim=c(0, 60), border = 'black',         
col=rev(topo.colors(14)),
        xlab="Percentage (%)")  
abline(v=x, col='grey', type="l", lty=2)
#text(myvect1, b[1,], mylabels, col="white", adj=1) 
text(my_bar, mylabels, cex=1) 

2 个答案:

答案 0 :(得分:1)

如果您希望数字显示在条形的末尾,只需从&#34; mylabels&#34;中提取数字字符。获取适当的x坐标并设置pos = 4以在条形图的右侧显示它们。至于条形的颜色,只需选择一些适合您的愿望的调色板或手动指定所有13种颜色。整个网络上有大量的秘籍表,R有不同的颜色模式。

 my_bar<-barplot(x,main="British Voters Election Priority (2015)",      horiz=TRUE,las = 1,
            names.arg=y, xlim=c(0, 60), border = 'black',         
            col = palette(rainbow(13)),
            xlab="Percentage (%)")  
 abline(v=x, col='grey', type="l", lty=2)
 #text(myvect1, b[1,], mylabels, col="white", adj=1) 
 text(as.numeric(gsub("\\D", "", mylabels)), my_bar, mylabels, cex=1, pos = 4) 

enter image description here

答案 1 :(得分:0)

您未指定应绘制tekst的位置的x坐标。您的代码现在为x坐标和y坐标获取my_bar的值。如果我是对的你想要这样的东西。

enter image description here

只需在最后使用这行代码即可:

text(60, my_bar, mylabels, cex=1, pos = 2)