簡體   English   中英

R ggplot2:geom_jitter 和 fill,問題是在右邊的箱線圖上有點

[英]R ggplot2 : geom_jitter and fill, problem to have the dots on the right boxplot

這是我的 R 代碼

ggplot(dat = Table, aes(x = Group, y = value, fill = Type)) +
    geom_boxplot(alpha=0.08)+
    geom_jitter()+
    scale_fill_brewer(palette="Spectral")+
    theme_minimal()

在此處輸入圖像描述

就像您看到的那樣,這些點位於箱線圖的中間。 我可以在 geom_jitter 中添加什么,讓每個點都在右箱圖中,而不是像這樣在中間? 我也試過 geom_point,它給出了相同的結果!


多虧了現在的幫助,它可以工作,但是我想添加一條線來連接點,我明白了……有人能告訴我如何真正將點與線連接起來嗎

在此處輸入圖像描述

我認為如果你按interaction(Group, Type)並使用position_jitterdodge()你應該得到你正在尋找的東西。

ggplot(mtcars, aes(as.character(am), mpg, color = as.character(vs),
                   group = interaction(as.character(vs), as.character(am)))) +
  geom_boxplot() +
  geom_jitter(position = position_jitterdodge())  # same output with geom_point()

在此處輸入圖像描述


編輯 - 這是一個手動抖動應用於數據的示例,其中每個主題在每個組中出現一次。

我尋找了一種內置的方法來做到這一點, 這個答案很接近,但是我無法使用position_jitterdodge和由 Group/Type 組定義的 position,但由id單獨定義的行分組來工作而不是按組/類型。 兩種美學(位置調整和系列識別)都依賴於相同的group參數,但它們各自需要不同的值。

Table = data.frame(id = 1:4, 
                   value = rnorm(8),
                   Group = rep(c("a","b"), each = 4),
                   Type = c("1", "2"))
library(dplyr)
Table %>%
  mutate(x = as.numeric(as.factor(Group)) + 
           0.2 * scale(as.numeric(as.factor(Type))) +
           rnorm(n(), sd = 0.06)) %>%
  ggplot(aes(x = Group, y = value, fill = Type, group = interaction(Group, Type))) +
  geom_boxplot(alpha=0.2)+
  geom_point(aes(x = x)) +
  geom_line(aes(x = x, group = id), alpha = 0.1) +
  scale_fill_brewer(palette="Spectral")+
  theme_minimal()

在此處輸入圖像描述

如果你想讓他們排隊,最好使用 position_dodge 代替:

library(ggplot2)

Table <- tibble::tibble(
  Group = rep(c("A", "B"), each = 20),
  Type = factor(rep(c(1:2, 1:2), each = 10)),
  value = rnorm(40, mean = 10)
)

ggplot(dat = Table, aes(x = Group, y = value, fill = Type)) +
  geom_boxplot(alpha=0.08)+
  geom_point(position = position_dodge(width = 0.75))+
  scale_fill_brewer(palette="Spectral")+
  theme_minimal()

要添加一條線,請確保group = ID進入geom_pointgeom_line調用:

library(ggplot2)

Table <- tibble::tibble(
  Group = rep(c("A", "B"), each = 20),
  Type = factor(rep(c(1:2, 1:2), each = 10)),
  ID = factor(rep(1:20, times = 2)),
  value = rnorm(40, mean = 10)
)

ggplot(dat = Table, aes(x = Group, y = value, fill = Type)) +
  geom_boxplot(alpha = 0.08) +
  geom_point(aes(group = ID), position = position_dodge(width = 0.75))+
  geom_line(aes(group = ID), position = position_dodge(width = 0.75), colour = "grey")+
  scale_fill_brewer(palette = "Spectral") +
  theme_minimal()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM