I asked a question before but I think it was not quite clear. Here, I try to elaborate the details.
We have this data frame
t = c(0, 1, 2, 3, 4, 5, 6)
x = c("b", "b", "w", "w", "b", "b", "b")
y = c("b", "b", "b", "b", "w", "w", "w")
df = data.frame(t, x, y)
and would like to have a flipped stacked bar plot using ggplo2
in R
.
I am using this code
colors <- c("b" = "black", "w" = "white")
df_long <- pivot_longer(df, cols = c("x", "y"), names_to = "variable", values_to = "value")
df_long$value <- factor(df_long$value, levels = c("b", "w"))
to define the colors, and this code for plotting
ggplot(df_long, aes(x = variable, fill = value)) +
geom_bar(position = position_stack(reverse = FALSE)) +
scale_fill_manual(values = colors) +
coord_flip()
Ideally, for x
, we should get black-white-black
and for y
, it should be black-white
but when I run this code, I’m getting a very messed up plot which for both x
and y
is white-black
(the platform doesn’t allow me to post an image of the plot).
I checked the structure of both df
and df_long
and they make sense but I’m not sure what’s happening with the ggplot
function. Could someone help?
Vultra Uiolet is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.