WindSur
WindSur

Reputation: 140

R add frequency count labels to ggplot geombar

I have a plot like this:

enter image description here

with the following code:

df.m <- reshape2::melt(ngli,id.vars = "Hugo_Symbol")

plot <- ggplot(df.m, aes(x = Hugo_Symbol, y = value, fill=variable)) +
  geom_bar(stat='identity') + 
  #geom_text(aes(label=len), vjust=1.6, color="white", size=3.5)+
  #geom_text(stat = "count", aes(label = after_stat(count)), vjust = -1)
  theme(axis.text.x=element_text(angle = 90, vjust = 0.5))

And I have tried, with the commented code, add the count for each label, something like that:

enter image description here

but it does not work. Any ideas? thanks!

Upvotes: 0

Views: 1217

Answers (1)

dc37
dc37

Reputation: 16178

Without a reproducible example of your dataset, it it hard to be sure of what will be the solution to your question.

However, based on your code, it looks like you are trying to get a barchart representing the sum of all values observed for each x values (with geom_bar(stat = "identity")) and add the number of observation for each categories and each x values with geom_text.

A possible solution is to calculate those values outside of ggplot2. Here, an example using iris dataset. You can first reshape your data in a longer format (as you did with melt) and then calculate the sum and the number of observations of grouped variables and categories (I add the mean just for fun)

library(tidyr)
library(dplyr)

df <- iris %>% pivot_longer(-Species, names_to = "variable", values_to = "val") %>%
  group_by(Species, variable) %>%
  summarise(Mean = mean(val),
            Sum = sum(val),
            count = n())

# A tibble: 12 x 5
# Groups:   Species [3]
   Species    variable      Mean   Sum count
   <fct>      <chr>        <dbl> <dbl> <int>
 1 setosa     Petal.Length 1.46   73.1    50
 2 setosa     Petal.Width  0.246  12.3    50
 3 setosa     Sepal.Length 5.01  250.     50
 4 setosa     Sepal.Width  3.43  171.     50
 5 versicolor Petal.Length 4.26  213      50
 6 versicolor Petal.Width  1.33   66.3    50
 7 versicolor Sepal.Length 5.94  297.     50
 8 versicolor Sepal.Width  2.77  138.     50
 9 virginica  Petal.Length 5.55  278.     50
10 virginica  Petal.Width  2.03  101.     50
11 virginica  Sepal.Length 6.59  329.     50
12 virginica  Sepal.Width  2.97  149.     50

Then, you can plot your bargraph as follow by using geom_col (which is the same than writing geom_bar(stat = "identity") and place your label on the stacked barchart by using position_stack function:

library(ggplot2)

ggplot(df, aes(x = variable, y = Sum, fill = Species))+
  geom_col()+
  geom_text(aes(label = count),position = position_stack(0.5))

enter image description here

Does it answer your question ?

If not, please provide a reproducible example of your dataset by folloing this guide: How to make a great R reproducible example

Upvotes: 3

Related Questions