簡體   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