我想在这个情节上给我的点上色:
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")
我想做成这样:
但是与长矛手的相关线。
我做错了什么?
问题是,当在
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'