簡體   English   中英

如何在 R 中的箱形圖中連接點的連接線中添加組

[英]How to add groups in connecting lines connecting dots in boxplots in R

我制作了以下數據集:

before <- c(100, 120, 140, 130, 120, 100, 100)  
after <- c(140, 100, 160, 120, 90, 70, 70)  
pain_group <- c(1, 0, 1, 0, 0, 0, 0)  
d <- data.frame(before=before, after=after, pain_group=pain_group)

d$id <- 1:nrow(d)
d <- tidyr::gather(d, Measurement, quantity, -id)

我用單獨的點和連接線在箱線圖中繪制了數據:

ggplot(d2, aes(Measurement, quantity_cluster2)) + 
  geom_boxplot() +  
  geom_point() +
  geom_line(aes(group = id), color = 'grey') +
  scale_x_discrete(limits = c('before', 'after'))

在此處輸入圖像描述

但是我希望pain_group用不同的顏色線(和點)分隔。 我怎樣才能做到這一點?

提前致謝!

您需要從gather中排除pain_group ,因此它仍然是長格式數據中的一列,然后將color = factor(pain_group)添加到aes()

d2 <- tidyr::gather(d, Measurement, quantity, -id, -pain_group)

ggplot(d2, aes(Measurement, quantity)) + 
  geom_boxplot() +  
  geom_point(aes(color = factor(pain_group))) +
  geom_line(aes(group = id, color = factor(pain_group))) +
  scale_x_discrete(limits = c('before', 'after'))

在此處輸入圖像描述

您可以使用labs()自定義圖例標題,或者使用scale_color_continuous()自定義圖例標題、標簽和 colors。

不是對您的問題的直接回答,而是對(可能)更引人注目的可視化的建議。 您正在處理成對的數據,因此將其分為兩個維度。 散點圖 plot 非常適合此目的。 您的數據已經處於正確的形狀,您可以添加一條等號線以使比較更容易。

library(ggplot2)
before <- c(100, 120, 140, 130, 120, 100, 100)  
after <- c(140, 100, 160, 120, 90, 70, 70)  
pain_group <- c(1, 0, 1, 0, 0, 0, 0)  
d <- data.frame(before=before, after=after, pain_group=pain_group)

lims <- range(c(before, after))

ggplot(d) +
  geom_point(aes(before, after, color = as.character(pain_group))) +
  geom_abline(intercept = 0, slope = 1) +
  coord_cartesian(xlim = lims, ylim = lims)

代表 package (v2.0.1) 於 2021 年 12 月 20 日創建

暫無
暫無

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

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