0

Im trying to group bars in R to have them based on two variables, type (Tax, income and VAT) and group (A and B). I succeeded to group based on the type, however when I´m trying to group it seem not to work.

plot <- ggplot(data=df, aes(x=Person, y=Amount, fill=FIAT ))+
  geom_bar(aes(), stat="identity", position="fill")+ 
  facet_grid(~type, scales="free_x")

The outcome I receive is this:

Plot bar with type-variable

The wanted outcome should look something like this, with group in the bottom:

Wanted plot bar

The output from dput:

dput(head(df.new))
structure(list(Person = c("Jon", "Bill", "Maria", "Ben", "Tina", 
"lisa"), Amount = c(23, 41, 32, 58, 26, 54), type = c("Tax", 
"Tax", "VAT", "Income", "Tax", "Income"), group = c("A", "B", 
"B", "A", "B", "A"), FIAT = c("BTC", "GBP", "BTC", "EURO", "USD", 
"USD")), row.names = c(NA, 6L), class = "data.frame")
Yoshi
  • 1
  • 1

1 Answers1

1

I see two options, both with the {ggh4x} package. I'd personally prefer the facet_nested approach, as easier to code, looks neater, and also no warning (which I don't know where it's coming from, I assume from the unique group and absence of all levels in your last facet), but there is - to my knowledge - no easy way to switch the side from the nested strips only. This can of course be achieved but would (IMO) require some grob hacking.

Option 1 - facet_nested

library(ggh4x)
#> Loading required package: ggplot2
ggplot(data=df, aes(x=Person, y=Amount, fill=FIAT ))+
  geom_bar(aes(), stat="identity", position="fill")+ 
  facet_nested(~ type + group, scales="free_x")

Option 2 - guide_axis_nested


## make a combined group from your x Person and group
ggplot(data=df, aes(x=interaction(Person, group, sep = "&"), y=Amount, fill=FIAT ))+
  geom_bar(aes(), stat="identity", position="fill")+ 
  facet_grid(~ type, scales="free_x") +
  scale_x_discrete(guide = guide_axis_nested(delim = "&"), name = NULL)
#> Warning in min(diff(position)): no non-missing arguments to min; returning Inf

Created on 2023-03-22 with reprex v2.0.2

tjebo
  • 21,977
  • 7
  • 58
  • 94