I'm trying to use geom_bar
to plot values in a sorted manner, but things get messy when I'm adding more conditions. I started with that:
library(ggplot2)
ggplot(dummy, aes(y = Value, x = reorder(Index, Value))) +
geom_bar(stat = "identity") +
coord_flip() +
theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank()) +
ylim(c(-1,1))
Which nicely generated this:
Then I wanted to color the different groups in different colors, so I added fill = Group to aes:
ggplot(dummy, aes(y = Value, x = reorder(Index, Value), fill = Group)) +
geom_bar(stat = "identity") +
coord_flip() +
theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank()) +
ylim(c(-1,1))
Which worked:
But then... I wanted to use facet_wrap(~Condition) to show it in two separate panels. Here's the code:
ggplot(dummy, aes(y = Value, x = reorder(Index, Value), fill = Group)) +
geom_bar(stat = "identity") +
coord_flip() +
theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank()) +
ylim(c(-1,1)) +
facet_wrap(~Condition)
This was the result:
How can I fix this issue? I want them stacked on top of each other without spaces...
Here's a code to generate my data frame:
structure(list(Index = structure(1:30, .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26",
"27", "28", "29", "30"), class = "factor"), Group = c("A", "A",
"A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B",
"B", "B"), Condition = c("Easy", "Hard", "Easy", "Hard", "Easy",
"Hard", "Easy", "Hard", "Easy", "Hard", "Easy", "Hard", "Easy",
"Hard", "Easy", "Hard", "Easy", "Hard", "Easy", "Hard", "Easy",
"Hard", "Easy", "Hard", "Easy", "Hard", "Easy", "Hard", "Easy",
"Hard"), Value = c(-0.75, -0.44, -0.27, 0.49, 0.04, 0.74, -0.95,
-0.59, 0.73, 0.93, -0.29, -0.47, -0.01, -0.65, -0.02, 0.32, -0.56,
-0.66, 0.95, -0.13, -0.42, -0.25, -0.07, 0.06, 0.46, -0.74, -0.25,
-0.37, -0.82, 0.86)), row.names = c(NA, 30L), class = "data.frame")
Thanks!
There's a scale
parameter in facet_wrap
, set it to free_y
to have independent scales in different facet sections.
library(ggplot2)
ggplot(dummy, aes(y = Value, x = reorder(Index, Value), fill = Group)) +
geom_bar(stat = "identity") +
coord_flip() +
theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank()) +
ylim(c(-1,1)) +
facet_wrap(~Condition, scale = "free_y")