【发布时间】:2021-12-28 11:25:33
【问题描述】:
我有一个数据框,我将其绘制为箱线图并添加了一条回归线。我想将此回归线与我使用 geom_abline 放入的另一条线(来自不同的实验)进行比较。但正如你所看到的,abline 不在正确的位置。我错过了什么吗?
eq <- function(x,y) {
m <- lm(log10Vol ~ log10hpf, Cell.Volume.Calculations)
as.character(
as.expression(
substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(coef(m)[1], digits = 4),
b = format(coef(m)[2], digits = 4),
r2 = format(summary(m)$r.squared, digits = 3)))
)
)
}
logEmb_hpff = ggplot(data = Cell.Volume.Calculations, aes(x=reorder(log10hpf,-Volume), y=log10Vol, fill=Stage)) +
geom_boxplot(width = 0.4) +
#scale_fill_viridis(discrete = TRUE, option = "J", alpha = 0.7)+
geom_jitter(aes(color = Stage), size=1, alpha=1) +
geom_smooth(method = "lm", formula = y ~ x, aes(group=1), se = TRUE, color = "gray60", alpha = 0.1)+
geom_text(x = 4.5, y = 7.5, label = eq(Cell.Volume.Calculations$log10hpf, Cell.Volume.Calculations$log10Vol), parse = TRUE, color = "grey40") +
#stat_regline_equation(label.y = 100, aes(label = ..eq.label..))+
scale_fill_brewer(palette = "Blues") +
theme_test() +
theme(
legend.position="none",
plot.title = element_text(size=14),
strip.text.x = element_text(
size = 12, color = "black", face = "bold"
))# +
#ggtitle("Cell Volumes for Early Embryo") +
# xlab("log10(hours post fertilisation)")+
#ylab("Single Cell Volume [log10(micron cubed)]")
logEmb_hpff + geom_abline(mapping = aes(intercept = 8.024, slope = -3, color = "red"))
【问题讨论】:
-
问题在于
reorder(log10hpf,-Volume)是一个因素。因此,您的 x 轴类别“0”(这是该因子的第二个类别)对应于数值 2。因此,为类别“0”显示的 abline 的 y 值是 8.024 - 3 * 2 = 2.024。一个简单的例子来说明这个问题:df <- data.frame(x = -1:1, y = 3:1); ggplot(df, aes(reorder(x, -y), y)) + geom_smooth(method = "lm", formula = y ~ x, aes(group = 1)) + geom_abline(intercept = 2, slope = -1, color = "red"). -
非常感谢,我删除了重新排序参数,只放了 log10hpf。现在可以使用了!