使用 ggscatter 分组着色

问题描述 投票:0回答:1

我想在这个情节上给我的点上色:

q <- ggscatter(ARAL_R, x = "Intl1", y = "Sul1", add = "reg.line", conf.int = TRUE, cor.coef = TRUE, cor.method = "spearman", xlab = "Intl1 (copies/g)", ylab = "Sul1 (copies/g)") + stat_cor(label.y = 1, label.x.npc = "center") + stat_regline_equation(label.y = 0.5, label.x.npc = "center")

但是每当我添加命令

color = "Core"
fill = "Core"
(其中 A 是 5 的分类变量)时,就会发生这种情况:

q <- ggscatter(ARAL_R, x = "Intl1", y = "Sul1", color = "Core", add = "reg.line", conf.int = TRUE, cor.coef = TRUE, cor.method = "spearman", xlab = "Intl1 (copies/g)", ylab = "Sul1 (copies/g)") + stat_cor(label.y = 1, label.x.npc = "center") + stat_regline_equation(label.y = 0.5, label.x.npc = "center")
ggpar(q, xscale = "log10", yscale = "log10")

我想做成这样:

但是与长矛手的相关线。

我做错了什么?

r ggplot2 scatter-plot
1个回答
0
投票

问题是,当在

color
上映射变量时,您的数据会被分成多个组,并且您会得到每个组或
Core
类别的回归线、相关系数和方程。要解决这个问题,您必须明确映射到
group
aes,即使用
aes(group = 1)
来处理所有obs。作为一组,为了简单起见或按照惯例,我们将其命名为
1
。不幸的是
ggscatter
不提供这个选项。这是使用“开箱即用”选项而不是使用 vanilla
ggplot2
时的缺点之一。但恐怕这是要走的路,即使用
geom_smooth
手动添加回归线,而不是依赖
ggscatter
:

使用基于

iris
的最小可重现示例:

library(ggpubr)
#> Loading required package: ggplot2

ARAL_R <- iris[3:5]
names(ARAL_R) <- c("Intl1", "Sul1", "Core")

q <- ggscatter(
  ARAL_R,
  x = "Intl1", y = "Sul1", color = "Core",
  xlab = "Intl1 (copies/g)", ylab = "Sul1 (copies/g)"
) +
  geom_smooth(aes(group = 1), method = "lm", color = "black") +
  stat_cor(aes(group = 1), label.y = 1, label.x.npc = "center") +
  stat_regline_equation(aes(group = 1), label.y = 0.5, label.x.npc = "center")

ggpar(q, xscale = "log10", yscale = "log10")
#> `geom_smooth()` using formula = 'y ~ x'

这里作为参考是香草

ggplot2
方式,我没有使用
group
aes,而是将
color
设为
geom_point
的本地aes,并且我只使用
ggpubr
来添加regline方程和相关系数:

library(ggplot2)
library(ggpubr)

ARAL_R <- iris[3:5]
names(ARAL_R) <- c("Intl1", "Sul1", "Core")

ggplot(
  ARAL_R,
  aes(Intl1, Sul1),
) +
  geom_smooth(method = "lm", color = "black") +
  geom_point(aes(color = Core)) +
  stat_cor(label.y = 1, label.x.npc = "center") +
  stat_regline_equation(label.y = 0.5, label.x.npc = "center") +
  labs(x = "Intl1 (copies/g)", y = "Sul1 (copies/g)") +
  scale_x_log10() +
  scale_y_log10()
#> `geom_smooth()` using formula = 'y ~ x'

© www.soinside.com 2019 - 2024. All rights reserved.