ggplot2 rstudio code help

Anyone know how to get the count on the y axis, to be normal percentages?

Here are two methods. The first calculates the percentages within ggplot and the second does it externally.

library(tidyverse)
DF <- data.frame(Type=sample(c("A","B","C"),50,replace = TRUE),
                 Gender=sample(c("F","M"),replace = TRUE,prob=c(0.6,0.4)))

ggplot(DF, aes(x=Type, fill=Gender)) + 
  geom_bar(aes(y=(..count..)/sum(..count..))) +
  scale_y_continuous(labels = scales::percent)

#method2
DF_summary <- DF |> group_by(Type,Gender) |> 
  summarize(Perc=n()/nrow(DF))
#> `summarise()` has grouped output by 'Type'. You can override using the `.groups` argument.
DF_summary
#> # A tibble: 6 x 3
#> # Groups:   Type [3]
#>   Type  Gender  Perc
#>   <chr> <chr>  <dbl>
#> 1 A     F       0.16
#> 2 A     M       0.14
#> 3 B     F       0.12
#> 4 B     M       0.18
#> 5 C     F       0.22
#> 6 C     M       0.18

ggplot(DF_summary, aes(x=Type, y=Perc, fill=Gender)) + geom_col() +
  scale_y_continuous(labels = scales::percent)

Created on 2022-01-15 by the reprex package (v2.0.1)

Thanks but i dont really need to show the gender, its just there to fill the ggplot.


I got it already, but need to get the percentages on top of the bars now, so you can read better how much percent every bar is

ggplot(kpi1, aes(x = Opleidingsniveau, y = stat(count/sum(count)), fill = Gender))+ 
    geom_bar(position ="stack") +
    scale_y_continuous(labels = scales::percent)+
    scale_fill_brewer(palette = "Pastel2")+
    ylab("Aantal gebruikers (in procenten)")+
  ggtitle("Het opleidingsniveau van onze gebruikers") 

my code

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.