Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Coefficient plot in R
# Libraries
library(dplyr)
library(broom)
library(ggplot2)
# Create data
fake.data <- data_frame(preg = rbinom(100, 1, prob=0.5),
trend = rnorm(100),
age = sample(15:55, 100, replace=TRUE),
parity = rbinom(100, 4, prob=0.5))
# Build model
model <- lm(preg ~ trend + age + parity, data=fake.data)
summary(model)
# Variables for the plot data
var.names <- c("Intercept", "Trend", "Age", "Parity")
multiplier <- qnorm(1 - 0.05 / 2)
# tidy() comes from the broom package and converts the model summary to a dataframe
plot.data <- tidy(model) %>%
mutate(ymin = estimate - (multiplier * std.error),
ymax = estimate + (multiplier * std.error),
# Change the variable names into an ordered factor.
# Reverse the order so that they display top->bottom when the plot is flipped.
term = factor(term, levels=rev(term),
labels=rev(var.names), ordered=TRUE))
# Get rid of the intercept if you want
plot.data <- plot.data %>% filter(term != "Intercept")
# Make a plot
p <- ggplot(plot.data, aes(x=term, y=estimate)) +
geom_hline(yintercept=0, colour="#8C2318", size=1) + # Line at 0
geom_pointrange(aes(ymin=ymin, ymax=ymax)) + # Ranges for each coefficient
labs(x="Coefficient", y="Estimate", title="Whatever") + # Labels
coord_flip() + # Rotate the plot
theme_bw() # Nicer theme
p
# Save plot
ggsave(p, filename="~/Desktop/cool_plot.pdf", width=5, height=5, units="in")
ggsave(p, filename="~/Desktop/cool_plot.png", width=5, height=5, units="in")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.