r - 如何手动增加R中分组箱形图中两个特定框之间的间距?
问题描述
有没有办法增加这个盒子图中黄色和红色盒子之间的间距?
set.seed(40)
df <- data.frame(
Outcome = runif(60),
Fruit = rep(1:3, each = 10),
Freshness = rep(c(0, 0.5), each = 30),
Farm = factor(rep(c("A", "B"), each = 5))
) %>%
transform(
Outcome = Outcome*Fruit+Freshness,
Fruit = as.factor(Fruit),
Freshness = as.factor(Freshness)
)
ggplot(data = df, aes(Farm, Outcome, col = Freshness, fill = Fruit)) +
geom_boxplot() +
scale_color_manual(values = c("lightslategrey", "black"), labels = c("Stale", "Fresh")) +
scale_fill_manual(values = c("red", "orange", "yellow"), labels = c("Apples", "Oranges", "Bananas"))
我想增加每个“农场”组中“新鲜度”颜色组之间的间距(或放置一个间隙),但不要太多,以至于盒子会像“农场”组那样分开。也就是说,我只想增加黄色和红色框之间的间距,以强调“新鲜度”组之间的区别。
“水果”组仍将保持组内盒子之间的距离。也就是说,相邻的红色、橙色和黄色框将保持靠近。
解决方案
您可以通过添加并使用宽度选择来修改框之间的间距,直到满意position=position_dodge(width =...))
为止。geom_boxplot()
ggplot(data = df, aes(Farm, Outcome, col = Freshness, fill = Fruit)) +
geom_boxplot(position=position_dodge(width = 1)) +
scale_color_manual(values = c("lightslategrey", "black"), labels = c("Stale", "Fresh")) +
scale_fill_manual(values = c("red", "orange", "yellow"), labels = c("Apples", "Oranges", "Bananas"))
这里是原作对比。
而修改后的 (with width=1
)
增加 X 轴上类别之间的间距是一个不同的问题,也是一个更难解决的问题。一种简单的解决方法是在 X 轴上使用具有自由比例的刻面。
ggplot(data = df, aes(Farm, Outcome, col = Freshness, fill = Fruit)) +
geom_boxplot(position=position_dodge(width = 1)) +
scale_color_manual(values = c("lightslategrey", "black"), labels = c("Stale", "Fresh")) +
scale_fill_manual(values = c("red", "orange", "yellow"), labels = c("Apples", "Oranges", "Bananas")) +
facet_wrap(~Farm, ncol = 2, scales = "free_x")
推荐阅读
- javascript - 我可以使用哪些搜索选项来限制 marklogic 搜索 API 关键字搜索,使其不在提到的 json 属性值中搜索?
- ssl - 如何修复:Digital Ocean SSL Cert 托管的子域未提取所有资源
- php - Laravel 5.5 mysql驱动使用两个数据库时出错
- r - 如何在带有变异函数的向量中使用条件?
- .net - fitSharp.Machine.Exception.TypeMissingException:在程序集中找不到类型“a1”
- python - Pandas 数据框在迭代期间不更新(itertuples),但在函数之外独立工作
- java - .ViewOnClickListener 上的空指针异常
- java - 关于设置对象属性的机制
- excel - Excel“匹配”返回#N/A,直到在相关单元格内单击“输入”,然后它返回正确的匹配值
- solr6 - 如何在 apache solr 中进行索引时将自定义分隔符添加到 csv 文件