【问题标题】:How to color-code ggplot boxplot dots by 2 variables?如何通过 2 个变量对 ggplot boxplot 点进行颜色编码?
【发布时间】:2019-11-01 10:40:26
【问题描述】:

我有一个箱线图,显示干预“之前”和“之后”的得分。我想把几个点换成不同的颜色,根据另一个分数。

换句话说,假设 10 个受试者在干预前得分为 (8,9,10,8,9,10,8,9,10,8),并且 (12,9,12,8,9, 10,10,9,10,10) 干预后。现在,使用标准 ggplot 箱线图,我将第 1 组和第 2 组显示为具有不同颜色的箱线图。我想用第三种颜色(在之前和之后的图中看到)为一些子喷气机着色,证明存在一个额外的二元变量(如年龄 > 50)。

PreopRespondersBoxPlotLDS <- ggboxplot(data=PreopResponders, 
x="Response",y="RespondersVsNonPreopLDS.preop", color = "Response", palette = 
"jco", add = "jitter") + labs(title = "Left Dorsal Striatum Connectivity to the Right Occipital Cortex", y = "Connectivity")
 + theme(axis.title.x = element_blank(), legend.position="none", legend.title = element_blank(), plot.title = element_text(hjust = 0.5))

我没有收到错误消息,我只是希望能够使用额外的颜色来为二进制变量编码。

【问题讨论】:

  • 使用反引号(`,在 ESC 键下的 1 旁边)而不是引号来获取问题中的代码格式。
  • 如果您想添加点,请将+ geom_point() 添加到您的图表中。给它你想要的数据子集geom_point(data = subset(PreopResponders, ::criteria::))。如果您想为这些点添加颜色,请为该层添加一个映射geom_point(data = subset(PreopResponders, ::criteria::), aes(color = binary_variable_name))。如果您需要更多帮助,请发布您的数据样本。 dput() 是共享数据的最佳方式,因为它可以复制/粘贴。

标签: r ggplot2 boxplot


【解决方案1】:

以下内容是问题所要求的。它使用geom_boxplot,而不是ggboxplot。并在对geom_jitter 的调用中通过二进制条件对数据进行子集化。这种情况很容易成为二进制数据帧变量。

另请注意,我在图表标题中包含了一个换行符 "\n"

library(ggplot2)

g <- ggplot(PreopResponders, aes(x = Response, y = RespondersVsNonPreopLDS.preop,
                                 color = Response)) + 
              geom_boxplot() +
              geom_jitter(data = subset(PreopResponders, Age > 50), 
                          color = "black",
                          width = 0.25, height = 0.25) +
              labs(title = "Left Dorsal Striatum Connectivity \nto the Right Occipital Cortex", y = "Connectivity") +
              theme(axis.title.x = element_blank(), 
                    legend.position = "none", 
                    legend.title = element_blank(), 
                    plot.title = element_text(hjust = 0.5))

g

数据创建代码。

PreopResponders <- data.frame(Response = factor(rep(c("Before", "After"), each = 10), labels = c("Before", "After")),
                              RespondersVsNonPreopLDS.preop = c(c(8,9,10,8,9,10,8,9,10,8),
                                                                c(12,9,12,8,9,10,10,9,10,10)))
set.seed(1234)
PreopResponders$Age <- sample(18:100, 20, TRUE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2012-07-04
    • 1970-01-01
    • 2014-02-12
    相关资源
    最近更新 更多