I have a data set that has an uneven number of subcategories ('Thingies') per each main category ('Whereabouts'). I want to build a barplot that shows the subcategories on the x-axis, grouped by main category. However, I keep running into the issue where all of my subcategories are grouped into each category on the bar graph.
I can get the axis correct when I produce a box plot:
SpookyReport <- HalloweenData %>% mutate(Whereabouts = fct_relevel(Whereabouts, c("Dead", "Halfdead", "Alive"))) %>%
ggplot(HalloweenData, mapping = aes(y = Totalspook, x = Whereabouts, fill = Thingies)) +
geom_boxplot() +
scale_fill_manual(values=SpookyPalette) +
labs(y="Total spook (spook-o-meters)", x=NULL) + ggtitle("Effect of losing my mind over this") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(legend.position="right") +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank()) +
theme(text = element_text(size = 15))
SpookyReport
However, when I try to produce a bar plot with the following code:
SpookySumReport2<-ddply(HalloweenData, .(Thingies), summarise, .progress="text", mean.cm=mean(Totalspook),
SD.cm=sd(Totalspook),SE.cm=sd(Totalspook)/sqrt(length(Totalspook)))
SpookySumReport2
SpookyReport2 <- HalloweenData %>% mutate(Whereabouts = fct_relevel(Whereabouts, c("Dead", "Halfdead", "Alive"))) %>%
ggplot(LiveInocsContrasts, mapping = aes(x=Thingies, y=Totalspook, fill= Thingies)) +
geom_bar(stat='summary') +
geom_beeswarm(aes(x = Thingies, y = Totalspook), dodge.width = 0.9, alpha = 0.5)+
geom_errorbar(data = SpookySumReport2, aes(x = Thingies, y = mean.cm, ymin=mean.cm-SE.cm,ymax=mean.cm+SE.cm, colour=Thingies),
color = 'black', width = 0.2, position = position_dodge(width = 0.9)) +
scale_fill_manual(values=SpookyPalette) +
facet_grid(~ Whereabouts,
scales = "free_x",
space = "free_x",
switch = "x") +
theme(panel.spacing = unit(0, units = "cm"),
strip.placement = "outside",
strip.background = element_rect(fill = "white")) +
theme(legend.position="none") +
labs(y="Total spook (spook-o-meters)", x=NULL) + ggtitle("Effect of losing my mind over this") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank()) +
theme(text = element_text(size = 15))
SpookyReport2
I get something like this: Bad bar plot
As you can see, all of the subcategories are present in the main categories, but that's not how my data is grouped in my dataset. This is my first time working with facet_grid, so perhaps I am doing something wrong? Can anyone identify the problem? Thank you so much!