我有以下脚本:
require(datasets)
data(ToothGrowth)
library(ggplot2)
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x=dose, y=len, color=dose, shape=dose)) +
geom_jitter(position=position_jitter(0.2))+
labs(title="Plot of length by dose",x="Dose (mg)", y = "Length") + stat_summary(fun.data=mean_sdl, size=0.6, geom="pointrange", color="black")
p + theme_classic() +
theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'))
这使得这个数字如下:
我的问题是如何为上面的黑色(平均)点添加smoothing line?
我尝试添加stat_smooth()
但不起作用。
答案 0 :(得分:3)
如果您将geom_smooth
作为数字而不是将其作为一个因素,则可以通过dose
直接执行此操作。对于颜色和形状映射,您可以使用factor(dose)
或使用不同的名称创建新的分类剂量变量。
data(ToothGrowth)
# New categorical dose for shapes and colors
ToothGrowth$Dose <- factor(ToothGrowth$dose)
ggplot(ToothGrowth, aes(x = dose, y = len, color = Dose, shape = Dose)) +
geom_jitter(position=position_jitter(0.2))+
labs(title="Plot of length by dose",x="Dose (mg)", y = "Length") +
stat_summary(fun.data=mean_sdl, size=0.6, geom="pointrange", color="black") +
theme_classic() +
theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
geom_smooth(aes(x = dose, y = len), inherit.aes = FALSE, se = FALSE)
如果你真的希望你的x轴是分类的,你需要通过在分类剂量变量上使用as.numeric
来表示每个因子水平代表的整数的平滑线。这是使用x变量的 rank 而不是实际值来绘制平滑线,这在实际情况下可能有意义,也可能没有意义。
ToothGrowth$Dose <- factor(ToothGrowth$dose)
ggplot(ToothGrowth, aes(x = Dose, y = len, color = Dose, shape = Dose)) +
geom_jitter(position=position_jitter(0.2))+
labs(title="Plot of length by dose",x="Dose (mg)", y = "Length") +
stat_summary(fun.data=mean_sdl, size=0.6, geom="pointrange", color="black") +
theme_classic() +
theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
geom_smooth(aes(x = as.numeric(Dose), y = len), inherit.aes = FALSE, se = FALSE)
答案 1 :(得分:2)
require(datasets)
data(ToothGrowth)
library(ggplot2)
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x=dose, y=len, color=dose, shape=dose)) +
geom_jitter(position=position_jitter(0.2))+
labs(title="Plot of length by dose",x="Dose (mg)", y = "Length") + stat_summary(fun.data=mean_sdl, size=0.6, geom="pointrange", color="black")
p + theme_classic() +
theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'))
lo <- loess(as.numeric(dose)~len,data=ToothGrowth)
p1 <- p+geom_line(aes(x=predict(lo)))