Home > OS >  Adding observations as proportions on a horizontal barplot in R using text() function
Adding observations as proportions on a horizontal barplot in R using text() function

Time:06-28

I cannot figure out how to get the percentage of responses at the end of the bars. I know I'm missing something within the text() function, just not sure what exactly I'm missing. Thank you!

#Training/Specialty Barplot
trainbarplot <- barplot(table(PSR$training), horiz = TRUE,
main="Respondent Distribution of Training", cex.main = 1.1, font.main = 2,
cex.lab = 0.8, cex.names = 0.4, font.axis = 4, las = 2,
xlab="Response Frequency", xlim=c(0, 40), cex.axis = 0.8,
border="black",
col=rgb (0.1, 0.1, 0.4, 0.5, 0.6),
density=c(50,40,30) , angle=c(9,11,36)
)

text(trainbarplot, table(PSR$training) - 3,
     labels=paste(round(proportions(table(PSR$training))*100, 0), "%"))

Training/Specialty Bar Plot w/ Squished Percentage Labels

CodePudding user response:

You are almost there.

## `trainbarplot` is the y-location, not x-location, because you have horiz = TRUE
text(table(PSR$training) - 3, trainbarplot,
     labels = paste0(round(proportions(table(PSR$training))*100, 0), "%"))

A reproducible example.

## a replacement of your table(PSR$training)
## obviously, you can improve your question by providing the output of
## `dput(table(PSR$training))`
x <- c(28, 40, 36, 32, 24)

trainbarplot <- barplot(x, horiz = TRUE,
main="Respondent Distribution of Training", cex.main = 1.1, font.main = 2,
cex.lab = 0.8, cex.names = 0.4, font.axis = 4, las = 2,
xlab="Response Frequency", xlim=c(0, 40), cex.axis = 0.8,
border="black",
col=rgb (0.1, 0.1, 0.4, 0.5, 0.6),
density=c(50,40,30) , angle=c(9,11,36)
)

## I am simply using 'x' as labels
text(x - 3, trainbarplot, labels = x)

example

CodePudding user response:

Generate data

I generated some sample data to replicate your problem. Please note that you should always try to provide an example dataset :)

set.seed(123)
df1 <- data.frame(x = rnorm(10, mean=10, sd=2), y = LETTERS[1:20])

Plot the data

Here's a plot that follows the same structure as your code:

bp <- barplot(df1$x, names.arg = df1$y,  col = df1$colour, horiz = T)
text(x= df1$x 0.5, y= bp, labels=paste0(round(df1$x),"%"), xpd=TRUE)

Using ggplot2

You can also plot your data using ggplot2. For instance, you could first create a new column in your dataset with information on the labels...

df1$perc <- paste0(round(df1$x),"%")

Next, you can plot your data using ggplot and adding different relevant layers.

library(ggplot2)
ggplot(df1, aes(x = x, y = y))  
  geom_col()  
  geom_text(aes(label = perc))  
  theme_minimal()

Good luck!

  • Related