Fill Percent stacked barchart according to value of each group, R

Viewed 22

I again have a question about Percent stacked barcharts. This time I have this data:

structure(list(month.int = 1:12, n = c(14L, 28L, 19L, 35L, 31L, 
62L, 96L, 44L, 15L, 38L, 127L, 14L), share = c(0.0267686424474187, 
0.0535372848948375, 0.0363288718929254, 0.0669216061185468, 0.0592734225621415, 
0.118546845124283, 0.183556405353728, 0.0841300191204589, 0.0286806883365201, 
0.0726577437858509, 0.24282982791587, 0.0267686424474187), month = structure(1:12, .Label = c("Jan", 
"Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", 
"Nov", "Dec"), class = "factor"), x = c("month", "month", "month", 
"month", "month", "month", "month", "month", "month", "month", 
"month", "month")), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

which with the following code:

ggplot(df, aes(fill = month,
               x = x,
               y = share)) +
  scale_fill_viridis_d() +
  geom_bar(position = "fill",
           stat = "identity",
           color = "black",
           show.legend = F) +
  geom_text(
    aes(
      label = glue("{month}: {round(share, 2)}"),
      group = month
    ),
    position = position_stack(vjust=.5)
  ) +
  theme_void()

prodcues this plot:

enter image description here

However, I would like to fill the rectangle for each month according to the value in either nor share.

I tried this:

ggplot(df, aes(fill = factor(n, ordered = T),
               x = x,
               y = share)) +
  scale_fill_viridis_d() +
  geom_bar(position = "fill",
           stat = "identity",
           color = "black",
           show.legend = F) +
  geom_text(
    aes(
      label = glue("{month}: {round(share, 2)}"),
      group = month
    ),
    position = position_stack(vjust=.5)
  ) +
  theme_void()

But it actually just made things worse...

enter image description here

1 Answers

Ok it works, when I do it like this:

ggplot(df, aes(fill = n,
               x = x,
               y = share)) +
  scale_fill_viridis_c() +
  geom_bar(position = "fill",
           stat = "identity",
           color = "black",
           show.legend = F) +
  geom_text(
    aes(
      label = glue("{month}: {round(share, 2)} ({n})"),
      group = month %>% rev()
    ),
    family = "Times",
    position = position_stack(vjust=.5)
  ) +
  theme_void()

enter image description here

But I doubt that this is the best answer

I personally do not understand why the December is plotted at the top and January at the bottom. And why I need to reverse the text to make it fit... Any explanations would be super welcome:)

Related