1
votes

I have some dummy data and am able to create a bar chart and a stacked bar chart:

# some data
egdf <- data.frame(
  ch = c('a', 'b', 'c'),
  N = c(100, 110, 120),
  M = c(10, 15, 20)
)

Looks like this:

egdf
  ch   N  M
1  a 100 10
2  b 110 15
3  c 120 20

Now some charts:

# bar chart
ggplot(egdf, aes(x = ch, y = N)) +
  geom_bar(stat = 'identity')

enter image description here

# stacked bar chart
egdf %>% 
  pivot_longer(cols = c(N, M), names_to = 'metric') %>% 
  ggplot(aes(x = ch, y = value, fill = metric)) +
  geom_bar(stat = 'Identity')

enter image description here

My question is, is there a way to create the stacked bar chart from egdf directly without having to first transform with pivot_longer()?

[EDIT]

Why am I asking for this? My actual dataframe has some additional fields which are based on calculations off the current structure, e.g. it looks more like this:

egdf <- data.frame(
  ch = c('a', 'b', 'c'),
  N = c(120, 110, 100),
  M = c(10, 15, 20)
) %>% 
  mutate(drop =  N - lag(N),
         drop_pct = scales::percent(drop / N),
         Rate = scales::percent(M / N))

egdf
  ch   N  M drop drop_pct  Rate
1  a 120 10   NA     <NA>  8.3%
2  b 110 15  -10   -9.09% 13.6%
3  c 100 20  -10  -10.00% 20.0%

In my plot, I'm adding on some additional geoms. If I was to pivot_longer, these relationships would be buckled. If I was able to somehow tell ggplot to make a stacked bar just based on feature1, feature2 (N and M in the example) it would be much easier for this particular use case.

1

1 Answers

2
votes

Update: See valuable comment of stefan:

ggplot(egdf1, aes(x=ch, y=N+M)) +
    geom_col(aes(fill="N")) +
    geom_col(aes(x=ch, y=M, fill="M")) +
    ylab("N") +
    scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) 

enter image description here

First answer: Are you looking for such a solution?

ggplot(egdf1, aes(x=ch, y=N)) +
    geom_col(aes(fill="N")) +
    geom_col(aes(x=ch, y=M, fill="M"))

enter image description here