如何在R中的条形图中向轴添加百分比符号?

时间:2014-02-27 23:00:01

标签: r bar-chart axis-labels

我目前有以下代码

    testdata <- data.frame(one=c(.25),two=c(.25),three=c(.5))

b <- barplot(t(testdata*100), col=c("darkred","darkblue","darkgoldenrod"), cex.axis=0.7,horiz=TRUE,border=NA)
text(b, x = c(.125,.375,.75)*100, c("Label1", "Label2", "Label3"), cex=.7, col="white")
text(b, x = c(0,20,40,60,80,100), y=0, labels = rep("%",6), cex=.7)

但是我想要而不是必须乘以100,将其解释为百分比并在轴标签中的每个增量之后添加“%”(或者至少是后者)。

1 个答案:

答案 0 :(得分:5)

使用barplot()(使用axes = FALSE)进行绘图时,更容易抑制轴,然后手动添加轴,您可以控制刻度线的位置以及随附的标签。下面的代码是一种方法

b <- barplot(t(testdata), col = c("darkred","darkblue","darkgoldenrod"), 
             horiz = TRUE, border = NA, axes = FALSE)
labs <- seq(0, 1, by = 0.25)
text(b, x = c(0.125, 0.375, 0.75), labels = c("Label1", "Label2", "Label3"),
     cex = 0.7, col = "white")
axis(side = 1, at = labs, labels = paste0(labs * 100, "%"), cex.axis = 0.7)

产生

enter image description here

这是你想要得到的吗?