Reputation: 155
I am trying to build a plot that compares two groups in four different categories, side by side, all with the same y scale (example data below). I have tried to use the group_by
function to group data prior to plotting however I only get data for both groups combined in all categories (shown in image). I do not want to facet the plots, although if there is no other option, this may have to work. I feel this should be a simple answer, but if anyone could help with where I am going wrong, I would be very appreciative.
Example data:
Group Category yvar
1 cat1 76.41383
1 cat2 51.24885
1 cat3 68.20408
1 cat4 79.14243
2 cat1 72.35527
2 cat2 64.61710
2 cat3 75.75096
2 cat4 73.71880
Script used:
my_data %>%
group_by(Group) %>%
ggplot(aes(x = Category, y = yvar)) +
geom_jitter(width = 0.1) +
geom_boxplot(alpha = 0)
Upvotes: 0
Views: 611
Reputation: 24790
Here's an approach with stat_boxplot
and geom_dotplot
:
ggplot(data, aes(x = as.factor(Category), y = yvar, fill = as.factor(Group))) +
stat_boxplot(outlier.shape = NA, alpha = 0) +
geom_dotplot(binaxis = "y",
stackdir = "center",
position = position_dodge(0.75),
dotsize = 0.7, binwidth = 0.5) +
scale_fill_manual(values = c("firebrick3","cornflowerblue")) +
labs(fill = "Group", y = "Y Variable", x = "Category")
Data
set.seed(3)
data <- data.frame(Group = rep(1:2,each = 80),
Category = rep(LETTERS[1:4], each = 20),
yvar = do.call(c,lapply(1:8,function(x){rnorm(20,x,2)})))
Upvotes: 1
Reputation: 143
What if you added fill
or color
to aes()
and assigned the Group
variable to one of them? That should give you the same plot as the one above, but now with one set of four box plots in one color representing Group 1
and another four in a different color for Group 2
.
Upvotes: 0