I have three factors and have produced the following plot
mtcars%>% ggplot( aes(as.factor(carb),fill=as.factor(am)))+
geom_bar(aes( y=..count../tapply(..count.., ..fill.. ,sum)[..fill..]),
position="fill")+
facet_wrap(~as.factor(vs))+
theme(legend.position = "bottom")
I can get what I want side by side but I'd like to produce a version where both plots are in one. Plot I’m aiming for in picture below (bottom plot).
Originals were made using python but cannot find any ggplot2 code to reproduce.
I have three factors and have produced the following plot
mtcars%>% ggplot( aes(as.factor(carb),fill=as.factor(am)))+
geom_bar(aes( y=..count../tapply(..count.., ..fill.. ,sum)[..fill..]),
position="fill")+
facet_wrap(~as.factor(vs))+
theme(legend.position = "bottom")
I can get what I want side by side but I'd like to produce a version where both plots are in one. Plot I’m aiming for in picture below (bottom plot).
Originals were made using python but cannot find any ggplot2 code to reproduce.
Share Improve this question edited Feb 17 at 11:24 ismirsehregal 33.5k5 gold badges45 silver badges92 bronze badges asked Feb 17 at 11:13 ABC1ABC1 11 silver badge1 Answer
Reset to default 3You can create this kind of chart easily by using the negative values for the category to be shown on the left. To make things a bit easier I would suggest to first compute the proportions manually outside of ggplot
. Finally, to add the category labels you can use annotate
where I use coord_cartesian(clip="off")
to draw outside of the panel borders and added some more margin at the top to make room for the labels:
library(ggplot2)
library(dplyr, warn = FALSE)
mtcars |>
count(carb, am, vs) |>
mutate(prop = n / sum(n), .by = c(carb, vs)) |>
mutate(prop = if_else(vs == 0, -1, 1) * prop) |>
ggplot(aes(
y = as.factor(carb), x = prop,
fill = as.factor(am)
)) +
geom_col(color = "white") +
scale_x_continuous(labels = ~ scales::percent(abs(.x))) +
theme(legend.position = "bottom") +
annotate(
x = c(-Inf, Inf),
y = Inf,
label = c("vs = 0", "vs = 1"),
geom = "label",
hjust = c(0, 1),
vjust = 0,
fill = NA,
label.size = 0,
fontface = "bold"
) +
coord_cartesian(clip = "off") +
theme(
plot.margin = margin(22, 5.5, 5.5, 5.5)
)