我有以下脚本:
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(),但不起作用。
发布于 2016-07-14 00:41:38
如果您将dose保留为数字而不是将其设置为因子,则可以直接通过geom_smooth完成此操作。对于颜色和形状映射,您可以使用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变量的等级而不是实际值绘制一条平滑线,这在您的实际情况下可能有意义,也可能没有意义。
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)

发布于 2016-07-13 09:47:30
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)))

https://stackoverflow.com/questions/38341005
复制相似问题