简体   繁体   中英

Print Regression Coefficients on Graph (ggplot)

I perform a regression with reg <- lm(...) and get some coefficents I can access with reg$coefficients .

It's of type Named num and contains all the coefficients with their values.

Named num [1:11] 505.085 -0.251 -0.286 -0.22 -0.801 ...
- attr(*, "names")= chr [1:11] "(Intercept)" "year" "monthDez" "monthFeb" ...

I want to show these on my graph created with ggplot. My current approach was to use the subtitle for this:

labs(subtitle=paste(toString(names(reg$coefficients)), "\n",
     paste(reg$coefficients, collapse = "           ")))

But it's not aligned correctly (name directly over the value etc.) Has someone an idea?

My current plot looks like this:

base <- ggplot(deliveries, aes(Date)) +
  geom_line(aes(y = SalesVolume, colour = "SalesVolume"))+
  ggtitle("Sales Volume By Time") +
  xlab("Time") +
  ylab("Sales Volume") +
  labs(subtitle=paste(toString(names(reg$coefficients)), "\n", paste(reg$coefficients, collapse = "           ")))

print(base + scale_x_date(labels = date_format("%b %y"), breaks =     date_breaks("2 months")))

In this graph a forecast is displayed, so I want to see the regression coefficients there as well.

Would it work to make two separate plots and arrange them onto a grid?

library(ggplot2)
library(broom)
library(dplyr)
library(tidyr)

data_plot <- 
  ggplot(data = mtcars,
         mapping = aes(x = qsec,
                       y = mpg,
                       colour = factor(gear))) + 
  geom_point()

fit <- lm(mpg ~ qsec + wt + factor(gear), 
          data = mtcars)

# Make a data frame with the contents of the model.
reg_data <- 
  tidy(fit) %>%
  mutate(y = nrow(.):1 - 1) %>%
  gather(estimate, value,
         estimate:p.value) %>%
  mutate(estimate = factor(estimate,
                           c("term", "estimate", "std.error", 
                             "statistic", "p.value")))

# Make a plot displaying the table.
reg_plot <- 
  ggplot(data = reg_data,
         mapping = aes(x = estimate,
                       y = y)) + 
  geom_text(mapping = aes(label = round(value, 2))) + 
  scale_y_continuous(breaks = unique(reg_data[["y"]]),
                     labels = unique(reg_data[["term"]])) + 
  scale_x_discrete(position = "top") + 
  xlab("") + 
  ylab("") + 
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_blank(), 
        axis.line = element_blank())

# Arrange the two plots
gridExtra::grid.arrange(data_plot + theme(plot.margin = grid::unit(c(1,1,0,.5), "lines")), 
                        reg_plot + theme(plot.margin = grid::unit(c(0,0,1,0), "lines")), 
                        clip = FALSE, 
                        nrow = 2,
                        ncol = 1, 
                        heights = grid::unit(c(.70, .5),
                                             c("null", "null"))) 

In my limited experience with ggplot2, annotate() could be used to add some annotations to a plot created with ggplot(), but I am not sure if the code below works for what you want

reg <- lm(data = mtcars, mpg ~ wt)

pred <- predict(reg)

newdata <- data.frame(mtcars, pred)

par <- summary(reg)$coefficients[,1]   # extract model parameters

par.f <- format(par, digits = 2)       # set the decimal digits of parameters

ggplot(mtcars, aes(x = wt, y = mpg)) + 

  geom_point() +

  geom_line(data = newdata, aes(x = wt, y = pred)) +

  annotate("text", x = c(2, 2.5), y = 18, label = names(reg$coefficients)) +

  annotate("text", x = c(2, 2.5), y = 16.5, label = par.f) # make them aligned by set x and y in annotate()

enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM