1

I didn't use r but I have recently decided to use it to plot graphs – because of its great capability to do so. I would like to make my graph better. Specifically, I'd plot numbers over bars. I saw Adding labels to ggplot bar chart and I tried to use

geom_text(aes(x=years, y=freq, ymax=freq, label=value, 
                hjust=ifelse(sign(value)>0, 1, 0)), 
            position = position_dodge(width=1)) +

But the numbers failed to show up.

Here's my code:

# Load ggplot2 graphics package
library(ggplot2)

# Create dataset
dat <- data.frame(years = c("1991", "1993", "1997", "2001", "2005", "2007", "2011", "2015"),
freq = c(43.20, 52.13, 47.93, 46.29, 40.57, 53.88, 48.92, 50.92))

# Plot dataset with ggplot2
ggplot(dat, aes(years, freq)) + geom_bar(stat = "identity", width=0.55)
+ labs(x="Year",y="") + theme_classic()

# Comma as decimal mark
format(df, decimal.mark=",")
Community
  • 1
  • 1
menteith
  • 596
  • 14
  • 51

1 Answers1

5

In ggplot2 you can achieve this by using geom_text(). aes() for this geometry needs to be provided with what is to be displayed (label) and the positioning.

You may use format in the call of aes() to get the comma as a decimal separator.

 ggplot(dat, aes(years, freq)) + 
    geom_bar(stat = "identity", width=0.55) +
    geom_text(aes(label=format(freq,decimal.mark = ","), y=freq+1.1)) + 
    scale_y_continuous(breaks = seq(0,50,10)) + 
    theme_classic()

It's slightly more idiomatic to do:

 library(scales)

 ggplot(dat, aes(years, freq)) + 
    geom_bar(stat = "identity", width=0.55) +
    geom_text(aes(label=comma(freq), y=freq+1.1)) + 
    scale_y_continuous(breaks = seq(0,50,10)) + 
    theme_classic()

as the scales package has many handy labelers built-in.

Martin C. Arnold
  • 9,483
  • 1
  • 14
  • 22
  • Thanks for this. I've made one change: `y=freq+2` and the values are a bit higher now. @hrbrmstr please feel free to supply your more idiomatic code. – menteith Apr 25 '16 at 11:33
  • M. A. has it covered here. Tis a gd answer (and I just added the idiomatic vs to it). You can use `nudge_y` std param vs adding to the `aes()` `y` param to move the label as well. – hrbrmstr Apr 25 '16 at 11:35
  • When I use your more idiomatic code I get : `Don't know how to automatically pick scale for object of type function. Defaulting to continuous Error in data.frame(y = c(44.3, 53.23, 49.03, 47.39, 41.67, 54.98, 50.02, : arguments imply differing number of rows: 8, 0` – menteith Apr 25 '16 at 11:46
  • Was in a hurry before and forgot the parameter. Fixed. – hrbrmstr Apr 25 '16 at 13:00