Search code examples
rggplot2bar-chartgeom-bar

Intuitive illustration of n observation in each group of stacked bar plot


I would like to illustrate my number of observation I made in each group in a stacked percentage bar plot in a more intuitive way than just adding the numbers. I was thinking of dividing each "color" into n sections.

So for instance in the following, I would like to make lines or similar to split "feminine, female" into 16 sections, "masculine, male" into 60 etc.

df \<- dplyr::starwars
df_sum \<- na.omit( df %\>% count(gender, sex))

# gender    sex                n
# \<chr\>     \<chr\>          \<int\>
# 1 feminine  female            16
# 2 feminine  none               1
# 3 masculine hermaphroditic     1
# 4 masculine male              60
# 5 masculine none               5

ggplot(df_sum, aes(fill=sex, y=gender, x = n)) +
geom_bar(position="fill", stat="identity")

(https://i.sstatic.net/wtwFt.png) (https://i.sstatic.net/t0vhO.png)

Other suggestions for an intuitive way of illustration the number of observations are also welcome


Solution

  • If you keep using the original data you have stored in df you can add color = "white" to separate each observation.

    df %>%
      drop_na(gender) %>%
      ggplot(aes(y = gender, x = 1, fill = sex)) +
      geom_bar(position = "fill", stat = "identity", color = "white")
    

    with separators