Gregory Anderson
Gregory Anderson

Reputation: 35

Both n and percent labels on geom_col, ggplot2

If I plot df with the code below, I can put the n for each column over the column itself, as seen in this example plot. What I would like to do is also put the percentage for each column in the label. That is the percentage of the total that the column makes up. So, for example, the label on the first column would read 127(42.9%), instead of just 127. How could I do that?

df <- structure(list(Letter = structure(1:7,
      .Label = c("A", "B", "C", "D", "E", "F", "G"),
      class = "factor"), Freq = c(127L, 101L, 24L, 19L, 3L, 0L, 22L)),
      .Names = c("Letter", "Freq"),
      row.names = c(NA, -7L),
      class = "data.frame")

ggplot(df, aes(Letter, Freq, label = Freq)) +
  geom_col() +
  geom_text(size = 3, position = position_dodge(width = 1), vjust = -0.25)

Upvotes: 1

Views: 1023

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145785

Just create the text you want to use as a label.

df$pct = df$Freq / sum(df$Freq) * 100
df$label = sprintf("%s (%s%%)", df$Freq, round(df$pct, 1))

ggplot(df, aes(Letter, Freq, label = label)) +
  geom_col() +
  geom_text(size = 3, position = position_dodge(width = 1), vjust = -0.25)

enter image description here

Upvotes: 2

Related Questions