0

I have tried to create a 100% stacked bar chart in rstudio but haven't found a way that works yet (also tried with "position", but r somehow doest recognize that)

Right now my code looks like that:

ggplot(andmed, aes(x= eesmärk, group = Class)) + 
  geom_bar(aes(fill = factor(Class))) + 
  scale_fill_brewer(type = "div", palette = 2) + 
  labs(x = "eesmärk/kaaslane", y = "protsent", fill="Klass") + 
  ggtitle("...") 

(a normal bar chart graph.a pic of what it looks like) Would like it to look similar to that:(but this one was made in SAS)how i would like it to look like

MrFlick
  • 195,160
  • 17
  • 277
  • 295
PKaru
  • 1
  • 2
    Usually `geom_bar(..., position="fill")`. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Nov 28 '22 at 15:49

1 Answers1

0

Like MrFlick said, you can use position = "fill" to fill up the entire stacked barchart. Additionally, since it looks like one group (DSC) takes up most of the barchart, you might only want to plot geom_text() for a specific group, like in your example barchart. I went about this by putting geom_text() for all groups but only allowed one group (carb == 4) to be visible using alpha.

library(tidyverse)
library(scales)
data(mtcars)

# calculate percentages, put into dataframe
df <- mtcars %>%
  mutate(carb = factor(carb)) %>% mutate(gear = factor(gear)) %>%
  group_by(gear, carb) %>%
  summarize(n = n()) %>%
  mutate(freq = n / sum(n)) %>%
  mutate(per = label_percent()(freq))  # from the scales package

ggplot(df, aes(x = gear, fill = carb)) +
  geom_bar(position = "fill") +
  geom_text(aes(label = per), 
            stat = "count",
            alpha = ifelse(df$carb == "4", 1, 0), # conditional transparency for geom_text
            position = position_fill(vjust = 0.5)) 

enter image description here

jrcalabrese
  • 2,184
  • 3
  • 10
  • 30