简体   繁体   English

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

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

I am working on a project and trying to reproduce following plot.我正在做一个项目并试图重现 plot。

在此处输入图像描述

Here is my attempt.这是我的尝试。

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

But boxplot and dotplot are crowded together in my attempt.但是箱线图和点图在我的尝试中挤在一起。 Any advice is appreciated.任何建议表示赞赏。

You can nudge the position of geoms by using position = position_nudge(...) .您可以使用position = position_nudge(...)轻推几何图形的 position。 You can use this to offset the boxplot and dotplot in opposite directions.您可以使用它在相反方向上偏移箱线图和点图。 Example below:下面的例子:

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`.

Created on 2021-04-05 by the reprex package (v1.0.0)代表 package (v1.0.0) 于 2021 年 4 月 5 日创建

I would use the position_nudge(x = 0, y = 0) function.我会使用position_nudge(x = 0, y = 0) function。 This allows you to translate elements of a plot in x and y.这允许您在 x 和 y 中转换 plot 的元素。 The function can be used as the position argument in the geom_xxxx() functions. function 可用作geom_xxxx()函数中的 position 参数。 Such as by using geom_boxplot(..., position = position_nudge(x = -0.1)) which translates the boxplots 0.1 to the left.例如通过使用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`.

Created on 2021-04-04 by the reprex package (v2.0.0)reprex package (v2.0.0) 于 2021 年 4 月 4 日创建

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

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