Home > Net >  ggplot - reverse y axis when plotting geom_smooth with gamma error distribution
ggplot - reverse y axis when plotting geom_smooth with gamma error distribution

Time:07-05

I am trying to plot a geom_smooth using a gamma error distribution.

library(ggplot)

data <- data.frame(x = 1:100, y = (1:100   runif(1:100, min = 0, max = 50))^2)

p <- ggplot(data, aes(x, y))  
  geom_point()  
  geom_smooth(method = 'glm', method.args = list(family = Gamma(link = "log")))

geom smooth

I also want to reverse the y-axis however using scale_y_reverse, but this causes the Gamma distribution to fail as it can't be applied to negative values. How can I reverse the y-axis for this plot?

p   scale_y_reverse()
Warning message:
Computation failed in `stat_smooth()`:
non-positive values not allowed for the 'Gamma' family 

CodePudding user response:

I'm not sure if there are build-in methods to call out the predicted values of geom_smooth for scale_y_reverse to work.

Here's the more conventional method with visualizing of regression models, i.e. construct, predict and plot.

library(broom)
model <- glm(y ~ x, data, family = Gamma(link = "log"))
new <- augment(model, se=TRUE) 

ggplot(new, aes(x, y))   
  geom_point()   
  geom_line(aes(y=exp(1)^.fitted))   
  geom_line(aes(y=exp(1)^(.fitted   .se.fit)), linetype="dashed")   
  geom_line(aes(y=exp(1)^(.fitted - .se.fit)), linetype="dashed")   
  scale_y_reverse()

enter image description here

  • Related