我正在尝试构建一个图,该图将四个不同类别的两组并排比较,且所有组均具有相同的y比例(以下示例数据)。我试图在绘制之前使用group_by
函数对数据进行分组,但是我只获得在所有类别中组合的两组数据(如图所示)。我不想讨论这些情节,尽管如果没有其他选择,则可能必须这样做。我认为这应该是一个简单的答案,但是如果有人可以帮助我解决问题,我将非常感激。
示例数据:
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
使用的脚本:
my_data %>%
group_by(Group) %>%
ggplot(aes(x = Category, y = yvar)) +
geom_jitter(width = 0.1) +
geom_boxplot(alpha = 0)
答案 0 :(得分:1)
这是使用stat_boxplot
和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")
数据
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)})))
答案 1 :(得分:0)
如果您将fill
或color
添加到aes()
并将Group
变量分配给其中之一怎么办?那应该为您提供与上述相同的图,但是现在有了一组四个方框图,其中一种颜色代表Group 1
,另一组四个代表Group 2
的颜色。