user3206440
user3206440

Reputation: 5049

R ggplot2 - adding value to bar plot

Following the example below from R cookbook

dat <- data.frame(
  time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
  total_bill = c(14.89, 17.23)
)

ggplot(data=dat, aes(x=time, y=total_bill, fill=time)) +
    geom_bar(colour="black", stat="identity") +
    guides(fill=FALSE)

How do I add the values (14.89, 17.23) for total_bill to be displayed at the top inside each bar with value rounded to 1 decimal like - 14.9, 17.2

Figure with above code

Upvotes: 1

Views: 5722

Answers (1)

Haboryme
Haboryme

Reputation: 4761

You could do:

ggplot(data=dat, aes(x=time, y=total_bill, fill=time)) +
  geom_bar(colour="black", stat="identity") +
  geom_text(aes(label = sprintf("%.1f", total_bill), y= total_bill),  vjust = 3)+
  guides(fill=FALSE)

You can adjust vjust to move the labels up or down.

Upvotes: 6

Related Questions