# Equation of a geom_smooth line

I think I have calculated the straight line of a geom_smooth line in a generated figure but would like to make it tidier. See example below:

Example data called data2:

Well_numbers Sample Dilution mIU.mL Type

``````1	Dilution 1:200	0.005	1.4450	Control
2	Dilution 1:200	0.005	1.2905	Control
3	Dilution 1:200	0.005	1.4425	Control
4	Dilution 1:500	0.002	1.1065	Control
5	Dilution 1:500	0.002	0.9475	Control
6	Dilution 1:500	0.002	0.9955	Control
``````
``````library(ggplot2)
library(Hmisc)
``````
``````lm_eqn = function(data2){
m = lm(mIU.mL ~ log10(Dilution), data2);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(coef(m), digits = 4),
b = format(coef(m), digits = 4),
r2 = format(summary(m)\$r.squared, digits = 3)))
as.character(as.expression(eq));
}
``````
``````ggplot(data2, aes(log10(Dilution), mIU.mL)) +
stat_summary(fun.y = mean, geom = "point") +
labs(title = "My Informative Title", x = "X axis label", y = "Y axis label") +
geom_smooth(method = "lm", se = TRUE, colour = 'green')+theme_light() + geom_text(x = -3, y = 1.2,label = lm_eqn(data2), parse = TRUE)
``````

My output is:

The equation of the line is y = c(3.53) + c(0.9301)x

I believe this is the same as y = 0.9301x + 3.53 (or y = 3.53 + 0.9301x). This makes sense when inputting the known data.

If this is true does anyone know how I remove the c values from the equation in the graph above? Or another way to calculate the equation of the straight line generated in the graph?

Well_numbers Sample Dilution mIU/mL Type
1 Dilution 1:200 0.005 1.445 Control
2 Dilution 1:200 0.005 1.2905 Control
3 Dilution 1:200 0.005 1.4425 Control
4 Dilution 1:500 0.002 1.1065 Control
5 Dilution 1:500 0.002 0.9475 Control
6 Dilution 1:500 0.002 0.9955 Control
7 Dilution 1:2000 0.0005 0.4295 Control
8 Dilution 1:2000 0.0005 0.4635 Control
9 Dilution 1:2000 0.0005 0.4925 Control

All data for above graph just realised I'd only given the head(data 2) data previously.

Hi @Schisto,

if you only want to format your equation differently you could start with a string. Maybe that helps a little...

I'm using different data but it should transfer easily to your problem, I hope.

``````library(tidyverse)

# a nonsense fit but never mind
fit <- lm(data = mtcars, formula = mpg ~ hp + cyl)
coeffs <- fit\$coefficients

# This is the equation string without italic etc. formatting
str_c(c(str_c(sprintf("%+ .2f", coeffs[-1]), names(coeffs)[-1], sep = "*"),
# add the intercept without a name
sprintf("%+ .2f", coeffs)),
collapse = " ")
#>  "-0.02*hp -2.26*cyl +36.91"
``````

Created on 2020-09-21 by the reprex package (v0.3.0)

You could also check the package `latex2exp` to use a TeX expression.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.