R starter
R starter

Reputation: 197

What is wrong with this code to add equation and r-squared to plot using ggplot2 in R

my df is:

df<- data.frame(logy, logx1, logx2)
dput(head(df, 20))

structure(list(logy = c(2.86483129264695, 2.71422609892467, 
6.0029648649718, 6.23407114218406, 3.10441832707604, 3.31883951518659, 
2.74899119270203, 3.33693389469922, 3.08234859652005, 2.86894009277142, 
3.14037873461243, 6.11999623623735, 5.62536278392782, 1.90161210220208, 
2.89764442725342, 2.29866776176114, 2.96609825952411, 3.81945083760566, 
6.0506839217917, 3.98692546692019), logx1 = c(2.40348089051437, 
2.40348089051437, 2.40348089051437, 2.40348089051437, 2.40348089051437, 
2.40348089051437, 2.40348089051437, 2.40348089051437, 2.40348089051437, 
2.40348089051437, 2.40348089051437, 2.40348089051437, 2.40348089051437, 
2.40348089051437, 2.40348089051437, 2.40348089051437, 2.40348089051437, 
2.40348089051437, 2.40348089051437, 2.40348089051437), logx2 = 
c(-1.57461309709751, -1.5307242691139, -0.464080611399306, 
-0.681847625665562, -1.14374686589473, -1.40571244572209, 
-1.43873659739373, -1.64132447315449, -1.68256017671134, 
-0.777132837116422, -0.658365673425322, -0.702903355642565, 
-1.11411689629791, -1.47169196167472, -2.70413799875517, 
-2.78595188490397, -2.484906653788, -1.65614025611831, -0.974314573029494, 
-1.05275482065124)), row.names = c(NA, 20L), class = "data.frame")

I want to add regression equation and Rsquared on a single plot as follow. This is logarithmic equation with 2 predictor variables. I am trying to use following code. But there is something wrong with it. Finally nothing is plotted. Can someone tell me What is wrong and how to fix it?

m <- lm(logy ~ logx1 +logx2, data = df)
p <- ggplot(data = df, aes(x = logx1 +logx2, y = logy)) +
   scale_x_continuous("logx1 + logx2") +
   scale_y_continuous("logy")+
   geom_smooth(method = "lm", formula = logy ~ logx1 + logx2) +
   geom_point()
 p

 eq <- substitute(italic(y) == a + b + c %.%     
 italic(x)*","~~italic(r)^2~"="~r2,
             list(a = format(coef(m)[1], digits = 4),
                  b = format(coef(m)[2], digits = 4),
                  c = format(coef(m)[3], digits = 4),
                  r2 = format(summary(m)$r.squared, digits = 3)))

 dftext <- data.frame(x1 = 3, x2= 3, y = 0.2, eq = 
 as.character(as.expression(eq)))

 p + geom_text(aes(label = eq), data = dftext, parse = TRUE)

Any help will be highly appreciated.

Upvotes: 1

Views: 192

Answers (1)

James Phillips
James Phillips

Reputation: 4657

According to this 3D scatterplot, no surface equation will fit this data well.

scatter

Upvotes: 1

Related Questions