jpd527
jpd527

Reputation: 1551

How do I add percentage signs to an axis in barplot in R?

I currently have the following code

    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)

but I want instead of having to multiply by 100, have it interpret as a percentage and add "%" after each increment in the axis label (or at least the latter).

Upvotes: 3

Views: 5312

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174853

It is easier to suppress the axis when plotting with barplot() (using axes = FALSE) and then add the axis by hand where you can control the positioning of the ticks and the labels that go with them. The code below is one way to do this

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)

which produces

enter image description here

Is that what you were looking to get?

Upvotes: 7

Related Questions