ggplot2: проблема с осью x при добавлении уравнения линии регрессии на каждом фасете - PullRequest
0 голосов
/ 10 января 2019

На основе примера здесь Добавляя уравнение линии регрессии и R2 на график , я изо всех сил стараюсь включить уравнение линии регрессии для моей модели в каждый аспект. Тем не менее, я не понимаю, почему меняется границы моей оси X.

library(ggplot2)
library(reshape2)

df <- data.frame(year = seq(1979,2010), M02 = runif(32,-4,6), 
M06 = runif(32, -2.4, 5.1), M07 = runif(32, -2, 7.1))
df <- melt(df, id = c("year"))


ggplot(data = df, mapping = aes(x = year, y = value)) +
geom_point() +
scale_x_continuous() + 
stat_smooth_func(geom = 'text', method = 'lm', hjust = 0, parse = T) +
geom_smooth(method = 'lm', se = T) +
facet_wrap(~ variable) # as you can see, the scale_x_axis goes back to 1800

Если я включу на x пределы,

scale_x_continuous(limits = c(1979,2010)) 

больше не показывает коэффициент регрессии. Что я тут не так делаю?

stat_smooth_func доступно здесь: https://gist.github.com/kdauria/524eade46135f6348140

Ответы [ 2 ]

0 голосов
/ 10 января 2019

Вы можете использовать функцию stat_poly_eq из пакета ggpmisc.

library(reshape2)
library(ggplot2)
library(ggpmisc)
#> For news about 'ggpmisc', please, see https://www.r4photobiology.info/
#> For on-line documentation see https://docs.r4photobiology.info/ggpmisc/

df <- data.frame(year = seq(1979,2010), M02 = runif(32,-4,6), 
                 M06 = runif(32, -2.4, 5.1), M07 = runif(32, -2, 7.1))
df <- melt(df, id = c("year"))

formula1 <- y ~ x

ggplot(data = df, mapping = aes(x = year, y = value)) +
  geom_point() +
  scale_x_continuous() + 
  geom_smooth(method = 'lm', se = TRUE) +
  stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")), 
               label.x = "left", label.y = "top",
               formula = formula1, parse = TRUE, size = 3) +
  facet_wrap(~ variable) 

ggplot(data = df, mapping = aes(x = year, y = value)) +
  geom_point() +
  scale_x_continuous() + 
  geom_smooth(method = 'lm', se = TRUE) +
  stat_poly_eq(aes(label = paste(..eq.label.., sep = "~~~")), 
               label.x = "left", label.y = 0.15,
               eq.with.lhs = "italic(hat(y))~`=`~",
               eq.x.rhs = "~italic(x)",
               formula = formula1, parse = TRUE, size = 4) +
  stat_poly_eq(aes(label = paste(..rr.label.., sep = "~~~")), 
               label.x = "left", label.y = "bottom",
               formula = formula1, parse = TRUE, size = 4) +
  facet_wrap(~ variable) 

Создано в 2019-01-10 пакетом Представление (v0.2.1.9000)

0 голосов
/ 10 января 2019

Возможно, кто-то предложит лучшее решение, но в качестве альтернативы вы можете изменить stat_smooth_func и сделать последнюю строку следующим образом

data.frame(x=1979, y=ypos, label=func_string)

вместо

data.frame(x=xpos, y=ypos, label=func_string)

Итак, сюжет будет как ниже enter image description here

...