Last active
October 15, 2022 16:08
-
-
Save meghall06/678d7ef9bf469f4cfc26ca8321ab570e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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()) |
It’s a data set included with ggplot2 so it should be available if you have that package installed/loaded!
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
Meghan, thanks for this post! Can you post a link to the txhousing data source?