简体   繁体   English

用 geom_jitter 绘制一个 ggplot geom_boxplot,用一个因子分隔,只显示盒子中值

[英]Plot a ggplot geom_boxplot with geom_jitter, separated by a factor and showing only box median

I have a data.frame with two factor variables ( type and age in df below) and a single numeric variable ( value in df below):我有一个带有两个factor变量(下面df中的typeage )和一个数字变量(下面df中的value )的data.frame

set.seed(1)
df <- data.frame(type = c(rep("t1", 8), rep("t2", 8), rep("t3", 8), rep("t4", 8), rep("t5", 8), rep("t6", 8)),
                 age = rep(c(rep("y", 4),rep("o", 4)), 6),
                 value = rep(c(runif(4, 5, 10), runif(4, 7.5, 12.5)), 6),
                 stringsAsFactors = F)
df$type <- factor(df$type, levels = c("t1", "t2", "t3", "t4", "t5", "t6"), ordered = T)
df$age <- factor(df$age, levels = c("y", "o"), ordered = T)

I want to use R 's ggplot2 to plot df$value as jittered points, grouped and color-coded by df$type , but within df$type separated by df$age .我想使用Rggplot2df$value绘制为抖动点,按df$type分组和颜色编码,但在df$type内由df$age分隔。 In addition, I want to show the median line for each group of df$type and df$age .此外,我想显示每组df$typedf$age的中线。

So far I can only get the points plotted without the median lines:到目前为止,我只能得到没有中线的点:

library(ggplot2)
ggplot(df, aes(x = age, y = value, color = type)) + 
  geom_jitter(width = 0.3) +
  facet_wrap(~type,nrow = 1) + theme_minimal()

在此处输入图像描述

Any idea how to add the median lines?知道如何添加中线吗?

Your example data was the same for all types, so I changed it a bit:您的示例数据对于所有类型都是相同的,所以我对其进行了一些更改:

set.seed(1)
df <- data.frame(type = c(rep("t1", 8), rep("t2", 8), rep("t3", 8), rep("t4", 8), rep("t5", 8), rep("t6", 8)),
                 age = rep(c(rep("y", 4),rep("o", 4)), 6),
                 value = runif(48, 5, 10),
                 stringsAsFactors = F)
df$type <- factor(df$type, levels = c("t1", "t2", "t3", "t4", "t5", "t6"), ordered = T)
df$age <- factor(df$age, levels = c("y", "o"), ordered = T)

You can use stat_summary for this:您可以为此使用stat_summary

ggplot(df) + 
  geom_jitter(aes(x = age, 
                  y = value,
                  color = type,
                  group = age),
              width = 0.2) +
  
  stat_summary(aes(x = age,
                   y = value,
                   color = type,
                   group = interaction(age, type)), 
               fun = median,
               geom = "crossbar") +
  
  scale_color_brewer(palette = "Dark2") +
  
  facet_wrap(~type,nrow = 1) + 
  
  theme_bw()

在此处输入图像描述

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

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