![](/img/trans.png)
[英]How can I create a legend for confidence interval and line of best fit for a stat_smooth in a lm (ggplot2)
[英]How to extract stat_smooth exponential fit parameters ggplot2
我已經嘗試了這里找到的許多建議,但我根本無法弄清楚。
是否可以從擬合 stat_smooth 的線中提取方程 (y = a+exp(-b*x))?
這是一個數據示例:
df <-data_frame(Time = c(0.5,1,2,4,8,16,24), Concentration = c(1,0.5,0.2,0.05,0.02,0.01,0.001))
Plot <- ggplot(df, aes(x=Time, y=Concentration))+
geom_point(size=2) +
stat_smooth(method = nls, formula = y ~ a*exp(-b *x),
se = FALSE,
method.args = list(start = c(a=10, b=0.01)))+
theme_classic(base_size = 15) +
labs(x=expression(Time (h)),
y=expression(C[t]/C[0]))
我嘗試使用 "stat_regline_equation" ,但是當我添加指數函數時它不起作用。
要從 ggplot 中提取數據,您可以使用: ggplot_build()
來自stat_smooth()
值在ggplot_build(Plot)$data[[2]]
您可以將其分配給對象: build <- ggplot_build(Plot)$data[[2]]
下面的兩個代碼給出了相同的結果
Plot <- ggplot(df, aes(x=Time, y=Concentration)) + geom_point(size=2) +
stat_smooth(method = nls, formula = y ~ a*exp(-b *x), se = FALSE,
method.args = list(start = c(a=10, b=0.01)))
和
Plot <- ggplot(df, aes(x=Time, y=Concentration)) + geom_point(size=2) +
geom_line(data=build,aes(x=x,y=y),color="blue")
我不認為這是可能的。 (1) 我在ggplot_build(Plot)
生成的對象的內臟中ggplot_build(Plot)
尋找,但沒有找到任何可能的東西(這並不能證明它不存在,但是......)(2)如果你在ggpubr::stat_regline_equation()
函數的源代碼您可以看到,與其從平滑中查看存儲的信息,不如調用一個重新擬合線性模型的包函數,以便它可以提取系數並構造方程.
您可能只需要自己重新擬合模型:
nls_fit <- nls(formula = Concentration ~ a*exp(-b *Time),
start = c(a=10, b=0.01), data = df)
coef(nls_fit)
(您可能會發現broom::tidy(nls_fit)
返回的格式很方便。)
對於此特定模型,您還可以通過以下方式獲取系數
cc <- coef(glm(Concentration ~ Time, data = df, family = gaussian(link= "log")))
c(exp(cc[1]), -cc[2])
原則上,您可以編寫自己的stat_
函數鏡像stat_regline_equation
來封裝此功能,但是除非您經常執行此操作或想讓其他人輕松執行此操作,否則將需要做更多的工作/不值得...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.