在 ggplot() 中为不同的 x 值范围绘制不同的模型
Plotting different models for different x value ranges in ggplot()
我正在尝试显示低 x 值的线性模型和高 x 值的非线性模型。为此,我将使用 DNase 作为示例:
library(ggplot2)
#Assinging DNase as a new dataframe:
data_1 <- DNase
#Creating a column that can distinguish low and high range values:
data_1$range <- ifelse(data_1$conc <5, "low", "high")
#Attempting to plot separate lines for low and high range values, and also facet_wrap by run:
ggplot(data_1, aes(x = conc, y = density, colour = range)) +
geom_point(size = 0.5) + stat_smooth(method = "nls",
method.args = list(formula = y ~ a*exp(b*x),
start = list(a = 0.8, b = 0.1)),
data = data_1,
se = FALSE) +
stat_smooth(method = 'lm', formula = 'y~0+x') +
facet_wrap(~Run)
但是,如您所见,它似乎同时绘制了线性模型和非线性模型,我不太清楚将告诉它只绘制一个的信息放在哪里每个。另外,如果可能的话,我可以将这些模型扩展到 x 轴上的整个值范围吗?
您可以为每个 geom
提供具体数据。在这种情况下,使用子集 data_1
使用 range
仅向每个 stat_smooth()
调用提供相关数据(以及整个帧 geom_point()
ggplot(NULL, aes(x = conc, y = density, colour = range)) +
geom_point(data = data_1, size = 0.5) +
stat_smooth(data = subset(data_1, range == "high"),
method = "nls",
method.args = list(formula = y ~ a*exp(b*x),
start = list(a = 0.8, b = 0.1)),
se = FALSE) +
stat_smooth(data = subset(data_1, range == "low"), method = 'lm', formula = 'y~0+x') +
facet_wrap(~Run)
如果您想在所有数据上都拟合两个模型,那么只需在 data_1
中手动计算并手动绘制。
我正在尝试显示低 x 值的线性模型和高 x 值的非线性模型。为此,我将使用 DNase 作为示例:
library(ggplot2)
#Assinging DNase as a new dataframe:
data_1 <- DNase
#Creating a column that can distinguish low and high range values:
data_1$range <- ifelse(data_1$conc <5, "low", "high")
#Attempting to plot separate lines for low and high range values, and also facet_wrap by run:
ggplot(data_1, aes(x = conc, y = density, colour = range)) +
geom_point(size = 0.5) + stat_smooth(method = "nls",
method.args = list(formula = y ~ a*exp(b*x),
start = list(a = 0.8, b = 0.1)),
data = data_1,
se = FALSE) +
stat_smooth(method = 'lm', formula = 'y~0+x') +
facet_wrap(~Run)
但是,如您所见,它似乎同时绘制了线性模型和非线性模型,我不太清楚将告诉它只绘制一个的信息放在哪里每个。另外,如果可能的话,我可以将这些模型扩展到 x 轴上的整个值范围吗?
您可以为每个 geom
提供具体数据。在这种情况下,使用子集 data_1
使用 range
仅向每个 stat_smooth()
调用提供相关数据(以及整个帧 geom_point()
ggplot(NULL, aes(x = conc, y = density, colour = range)) +
geom_point(data = data_1, size = 0.5) +
stat_smooth(data = subset(data_1, range == "high"),
method = "nls",
method.args = list(formula = y ~ a*exp(b*x),
start = list(a = 0.8, b = 0.1)),
se = FALSE) +
stat_smooth(data = subset(data_1, range == "low"), method = 'lm', formula = 'y~0+x') +
facet_wrap(~Run)
如果您想在所有数据上都拟合两个模型,那么只需在 data_1
中手动计算并手动绘制。