ggplot : label count and percent

Viewed 35

I have a chart that shows percentage as label. I would like to add next to the percentage, the count. Is it possible ? Here's my code :

 output$sortie4 <- renderPlot ({
        ggplot(filtered_data3(), aes(x= LV1,  group=Cycle)) + 
            geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
            geom_text(aes( label = scales::percent(round(..prop.., 2)),
            y= ..prop.. ), stat= "count", vjust = -.5) +
            labs(y = "Percent", fill="LV1") +
            facet_grid(~Cycle) +
            guides(fill="none")+
            scale_y_continuous(labels = scales::percent)+
            theme(text = element_text(size=17),
                  axis.text.x = element_text(angle=80, hjust=1))
        })

And here's my chart : enter image description here

Here's a part of my dataframe :

data.frame(
  Cycle = c("Cycle 1", "Cycle 2", "Cycle 3", "Cycle 2", " Cycle 1"),
  LV1 = c("Anglais", "Anglais", "Pas de LV1", "Italien", "Anglais"),
  Number = c(1, 1, 1, 1, 1)
)

Thank you !

1 Answers

I added an extra sample in the dataset:

example = data.frame(
  Cycle = c("Cycle 1", "Cycle 2", "Cycle 3", "Cycle 2", " Cycle 1","Cycle 2"),
  LV1 = c("Anglais", "Anglais", "Pas de LV1", "Italien", "Anglais", "Anglais"),
  Number = c(1, 1, 1, 1, 1, 1)
)

Using paste() you can combine the outputs of the stat ..count.. and ..prop.. as the label for geom_text().

library(ggplot2)

ggplot(example, aes(x= LV1,  group=Cycle)) + 
  geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
  geom_text(aes( label = paste( ..count..,
                                scales::percent(round(..prop.., 2)),
                                sep=" - "
                                ),
                 y= ..prop.. ), stat= "count", vjust = -.5) +
  labs(y = "Percent", fill="LV1") +
  facet_grid(~Cycle) +
  guides(fill="none")+
  scale_y_continuous(labels = scales::percent)+
  theme(text = element_text(size=17),
        axis.text.x = element_text(angle=80, hjust=1))

You can edit the inputs, the order, the separator, ..., in geom_text(aes( label = paste(...) ) ) to adapt it to your expectations.

enter image description here

Related