How do have both count and percent on barcharts in ggplot2? R

Viewed 991

this is my data

data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))

This is my plot

ggplot(data, aes(x=Name, y=Freq)) + 
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

4 Answers

Compose the text label with paste/paste0.

ggplot(data, aes(x = Name, y = as.numeric(Freq))) + 
  geom_bar(stat = "identity", color = "black", fill = "dodgerblue1")+
  geom_text(label = with(data, paste(Freq, paste0('(', Percent, ')'))), vjust=-1) +
  ylim(0, 8)

enter image description here

I think it is important that if you want to plot numeric variables you make sure they are numbers, rather than factors as in your example, otherwise the proportions will be wrong:

data$Freq <- as.numeric(as.character(data$Freq))
labs <- paste0(format(100 * data$Freq/sum(data$Freq), digits = 4), "%")

ggplot(data, aes(x=Name, y=Freq)) + 
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label = labs, vjust=-1) + coord_cartesian(ylim = c(0, 8))

enter image description here

The first excellent answer uses a simple general strategy for labeling each bar, but did not work in my hands because as.numeric(Freq) returns c(2,3,1), not the expected c(5,7,3) (as a result, I could not reproduce the chart shown). The third answer fixes the factor problem, but does not label the bars as asked in the question. The simple solution would be to have the Freq numbers be numbers, then the first answer works:

data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c(5,7,3),
                   "Percent" = c("33%", "47%", "20%"))

And, once we have numbers, we can have 'R' calculate percentages:

ggplot(data, aes(x = Name, y = Freq)) + 
  geom_bar(stat = "identity", color = "black", fill = "dodgerblue1") +
  geom_text(label = with(data, sprintf("%d (%.0f%%)",Freq, 100*Freq/sum(Freq))), vjust=-1)+
  ylim(0,8)

enter image description here

Is this what you're looking for?

ggplot(data, aes(x=Name, y=Percent)) + 
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=paste0("N = ",data$Freq), vjust=-1) +
  ylab("")

Related