1

I am trying to insert a text box in my ggplot to show regression equation and p-value but it is giving me a weird output. The graph only shows on one side. please look at the image.

I also tried to use:

scale_x_continuous(name = "Year", limits=c(1890, 2020)

but it does not work.

I adopted the following code and added the text in "geom_label" instead of in the title.

https://sejohnston.com/2012/08/09/a-quick-and-easy-function-to-plot-lm-results-in-r/

if anyone can find my error. i will be greatful.

Here is the function that I tried to use:

ggplotRegression3 <- function (fit) {
  require(ggplot2)

  ggplot(fit$model, 
         aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() + 
    geom_line() + 
    geom_label(aes(3, 40, hjust = 1, 
                   "Adj R2 = ",
                   signif(summary(fit)$adj.r.squared, 3),"\n",
                   "Intercept =",signif(fit$coef[[1]],3 ),"\n",
                   " Slope =",signif(fit$coef[[2]], 3),"\n",
                   " P-value =",signif(summary(fit)$coef[2,4], 3))) +
    stat_smooth(method = "lm", col = "red") +
    labs(title = "Average annual") + 
    scale_x_continuous(name = "Year", limits=c(1890, 2020)) 
}

enter image description here

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Samrat
  • 79
  • 1
  • 10
  • 1
    Why did you place the text geom at the year 3? – camille May 05 '19 at 01:47
  • @samrat, have you seen this [post](https://stackoverflow.com/questions/32506444/ggplot-function-to-add-text-just-below-legend?rq=1) Also look at [this post](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and learn how to create a minimum reproducible example – mnm May 05 '19 at 07:25
  • Welcome to Stack Overflow! Please, provide a [mcve] including your data in a reproducible way. Thank you. – Uwe May 05 '19 at 16:31

1 Answers1

1

Since you are specifying the geom_label to be placed at coordinates x=3, y=40, the x-axis is expanded from the 1890-to-2020 range that you asked for to include x=3. Instead of aes(3, 40, ... you should specify something like aes(1870, 43, ...

I am also wondering whether you have omitted square brackets around '1' in the ggplot line.

Jet
  • 650
  • 5
  • 17
Phil Smith
  • 430
  • 2
  • 12
  • Thank you so much for helping me with this. Finally it turned out the way i wanted. I was just recently introduced to R and have been just adding pieces of codes from here and there to make my own function and didnt really know what that 3 and 40 meant. I really appreciate this. – Samrat May 06 '19 at 02:07