Reputation: 11
I have a data set with two columns and I want to fit to an exponential curve and show the equation on the chart. Could you please help me with the code?
x<-1:6
y<-c(86000,114597,165576,207467,328745,531531)
df<-as.data.frame(cbind(x,y))
ggplot(df,aes(x,y))+
geom_point()+
geom_line(colour=" dark blue")+
geom_smooth(method = "nls",se = F)+
scale_y_continuous(labels = scales::comma)+
theme_economist()+
xlab("Grade")+
ylab("Salary avg")
when I try to use nls I can not see the curve on ggplot.
Upvotes: 1
Views: 541
Reputation: 226182
Setup:
library(ggplot2)
df <- data.frame(x=1:6,
y=c(86000,114597,165576,207467,328745,531531))
gg0 <- ggplot(df,aes(x,y))+
geom_point()+
geom_line(colour=" dark blue")+
scale_y_continuous(labels = scales::comma)+
ggthemes::theme_economist()+
xlab("Grade")+
ylab("Salary avg")
One way to do it is to fit a GLM with Gaussian family and log link:
gg0 + geom_smooth(method="glm",
formula=y~x,
method.args=list(family=gaussian(link="log")))
You can use nls
, but it's a little tricky. I used a self-starting method here, but (1) had to install an archived package, (2) had to specify start
anyway (I think it's ignored but needs to be there)
## remotes::install_version("drLumi",version="0.1.2")
gg0 + geom_smooth(method="nls",
formula=y~drLumi::SSexp(x,b,y0),
se=FALSE,
method.args=list(start=list(b=1,y0=1)))
Incomplete attempt to extract regression equation:
g1 <- glm(y~x, data=df, family=gaussian(link="log"))
library(latex2exp)
library(equatiomatic)
s <- TeX(extract_eq(g1,ital_vars=TRUE))
Upvotes: 1