Skip to content

Instantly share code, notes, and snippets.

@meghall06
Last active October 15, 2022 16:08
Show Gist options
  • Save meghall06/678d7ef9bf469f4cfc26ca8321ab570e to your computer and use it in GitHub Desktop.
Save meghall06/678d7ef9bf469f4cfc26ca8321ab570e to your computer and use it in GitHub Desktop.
# to create the plots in this Twitter thread: https://twitter.com/MeghanMHall/status/1560411406935138305
library(tidyverse)
library(ggrepel)
library(scales)
df1 <- txhousing %>%
filter(city %in% c("Houston","Austin")) %>%
group_by(year, city) %>%
summarize(avg = mean(median, na.rm = TRUE)) %>%
mutate(label = ifelse(year %% 3 == 0, avg, NA),
nudge = ifelse(city == "Austin", 20000, -20000))
df1 %>%
ggplot(aes(x = year, y = avg, group = city, shape = city)) +
geom_line() +
geom_point(size = 3) +
scale_y_continuous(labels = scales::dollar,
expand = expansion(mult = c(0.15, 0.1))) +
ggrepel::geom_text_repel(aes(label = scales::dollar(label)),
size = 3, nudge_y = df1$nudge) +
labs(title = "Median home price per year") +
theme_linedraw() +
theme(legend.position = c(0.25, 0.75),
legend.title = element_blank(),
legend.background = element_rect(fill="transparent", color=NA),
legend.key = element_rect(fill="transparent", color=NA),
axis.ticks = element_blank(),
axis.title = element_blank())
df2 <- txhousing %>%
filter(city %in% c("Amarillo","Beaumont")) %>%
group_by(year, city) %>%
summarize(avg = mean(median, na.rm = TRUE)) %>%
group_by(year) %>%
mutate(bigger = max(avg),
label = ifelse(year %% 3 == 0, avg, NA),
nudge = ifelse(avg == bigger, 7500, -7500))
df2 %>%
ggplot(aes(x = year, y = avg, group = city, shape = city)) +
geom_line() +
geom_point(size = 3) +
scale_y_continuous(labels = scales::dollar,
expand = expansion(mult = c(0.15, 0.1))) +
ggrepel::geom_text_repel(aes(label = scales::dollar(label)),
size = 3, nudge_y = df2$nudge) +
labs(title = "Median home price per year") +
theme_linedraw() +
theme(legend.position = c(0.25, 0.75),
legend.title = element_blank(),
legend.background = element_rect(fill="transparent", color=NA),
legend.key = element_rect(fill="transparent", color=NA),
axis.ticks = element_blank(),
axis.title = element_blank())
@btadams
Copy link

btadams commented Aug 19, 2022

Meghan, thanks for this post! Can you post a link to the txhousing data source?

@meghall06
Copy link
Author

It’s a data set included with ggplot2 so it should be available if you have that package installed/loaded!

@alekrutkowski
Copy link

This gist file should be named ggrepel_nudge.R (i.e. include .R extension) so that we get a nice syntax highlighting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment