繁体   English   中英

当 plot 同时显示时,如何在 ggplot2 中显示 `geom_boxplot` 和 `geom_dotplot`?

[英]How to display `geom_boxplot` and `geom_dotplot` spaced in ggplot2 when plot both at same time?

我正在做一个项目并试图重现 plot。

在此处输入图像描述

这是我的尝试。

test<-data.frame(
  x=factor(rep(1:3, each=20)),
  y=runif(60)
)
p<-ggplot(test, aes(x=x, y=y,fill=x)) +
  geom_boxplot(width=0.2) +
  geom_dotplot(binaxis = "y")
p

但是箱线图和点图在我的尝试中挤在一起。 任何建议表示赞赏。

您可以使用position = position_nudge(...)轻推几何图形的 position。 您可以使用它在相反方向上偏移箱线图和点图。 下面的例子:

library(ggplot2)
test<-data.frame(
  x=factor(rep(1:3, each=20)),
  y=runif(60)
)
ggplot(test, aes(x=x, y=y,fill=x)) +
  geom_boxplot(width=0.2, position = position_nudge(x = -0.1)) +
  geom_dotplot(binaxis = "y", position = position_nudge(x = 0.1))
#> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

代表 package (v1.0.0) 于 2021 年 4 月 5 日创建

我会使用position_nudge(x = 0, y = 0) function。 这允许您在 x 和 y 中转换 plot 的元素。 function 可用作geom_xxxx()函数中的 position 参数。 例如通过使用geom_boxplot(..., position = position_nudge(x = -0.1))将箱线图 0.1 向左平移。

library(tidyverse)

test<-data.frame(
  x=factor(rep(1:3, each=20)),
  y=runif(60)
)
p<-ggplot(test, aes(x=x, y=y,fill=x)) +
  #Translate left
  geom_boxplot(width=0.2, position = position_nudge(-0.1)) +
  #Translate right
  geom_dotplot(binaxis = "y", width = 0.2, position = position_nudge(x = 0.1))
p
#> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

reprex package (v2.0.0) 于 2021 年 4 月 4 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM