我制作了以下資料集:
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用不同顏色的線(和點)分開。我怎樣才能做到這一點?
提前致謝!
uj5u.com熱心網友回復:
您需要pain_group從您的中排除,gather以便它仍然是長格式資料中的一列,然后添加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()。
uj5u.com熱心網友回復:
不是對您問題的直接回答,而是對(可能)更引人注目的可視化的建議。您正在處理配對資料,因此將其帶入兩個維度。散點圖非常適合此目的。您的資料已經處于正確的形狀,您可以添加一行等式以使比較更容易。
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)

由reprex 包(v2.0.1)于 2021 年 12 月 20 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/388261.html
上一篇:試圖創建幾個箱線圖
