Home > Software engineering >  How to display the values of every single bar in a barplot in R (without using ggplot)?
How to display the values of every single bar in a barplot in R (without using ggplot)?

Time:11-21

I am a beginner in R and thanks to the provided help here so far, I managed to create the following Barplot by using the code below. However, one issue is still open and I couldn't resolve it so far, even after reading all the answers provided in similar questions.

Code:

res <- data.frame( aggregate( rentals ~ weatherCond   season, bikes, sum ))

res$weatherCond <- ordered(res$weatherCond,
levels = c(1, 2, 3, 4),
labels = c("Clear", "Fog", "Snow", "Storm"))

res$season <- factor(res$season,
levels = c(1, 2, 3, 4),
labels = c("Winter", "Spring", "Summer", "Autumn"))

par(mar=c(10,4,2,1) .5) 
barplot(res[,"rentals"], names=apply( res[,1:2], 1, function(x) paste0(x[1],"_",x[2]) ), las=3, main = "Weather and Rentals", ylab = "Rentals", col = c('blue', 'red', 'green', 'grey')[res$weatherCond])

The plot visualizes the connection between the number of RENTED bikes and the SEASONs depending on the WEATHER conditions (3 variables). The bars in the plot show the amount of bikes RENTED, separated into the corresponding SEASON/WEATHER combinations.

enter image description here

My question: how exactly should I modify the code above so that the count of the value of every single bar can be displayed (in the bar or on top of the bar)? Every single bar represents the number of rentals.

UPDATE: I managed to display the values by adding the following lines of code:

y <- as.matrix(res$rentals)
text(b, y 2, labels=as.character(y)) <!-- the "b" is the barplot -->

However, the result is horrifying. Is there a way to make it look better?

enter image description here

CodePudding user response:

barplot() returns the midpoints of each bar (see ?barplot). This can be used in combination with the function text() to display the numbers.

I your case, it would become:

mid_points <- barplot(res[,"rentals"], ...)
text(x = mid_points, y = res[,"rentals"], text = res[,"rentals"])

Further parameters can be used the modify the placement of the numbers. Since I don't have your data, I used a modified base R example:

b <- barplot(GNP ~ Year, data = longley, ylim = c(0, 700))
text(
  x = b,
  y = longley$GNP,
  labels = round(longley$GNP, 1),
  pos = 3,
  srt = 90,
  offset = 1.5
)

enter image description here

  • Related