Created
February 4, 2023 14:04
-
-
Save AlbertRapp/ccbe85de5f9ff9877e96e38a78a50fd5 to your computer and use it in GitHub Desktop.
ggiraph_additional_infos.R
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
library(dplyr) | |
library(ggplot2) | |
library(ggiraph) | |
dat <- gapminder::gapminder |> | |
janitor::clean_names() |> | |
mutate( | |
# ID that is shared for boxplots (this one uses factors, i.e. numbers, as ID instead of continents) | |
id = as.numeric(continent), | |
continent = forcats::fct_reorder(continent, life_exp) | |
) | |
selected_year <- 2007 | |
color_palette <- thematic::okabe_ito(5) | |
names(color_palette) <- unique(dat$continent) | |
base_size <- 24 | |
box_stats <- dat |> | |
filter(year == selected_year) |> | |
group_by(continent) |> | |
summarise( | |
n = n(), | |
iqr = IQR(life_exp) |> round(2), | |
range = paste(range(life_exp) |> round(2), collapse = ' - '), | |
mean = mean(life_exp) |> round(2) | |
) | |
box_plot <- dat |> | |
filter(year == selected_year) |> | |
full_join(box_stats) |> | |
ggplot(aes(x = life_exp, y = continent, fill = continent, data_id = id)) + | |
geom_boxplot_interactive( | |
aes( | |
tooltip = glue::glue( | |
' | |
{levels(dat$continent)[continent]}\n | |
{n} Countries\n | |
Mean life expectancy: {mean}\n | |
Range: {range}\n | |
IQR: {iqr} | |
' | |
), | |
onclick = glue::glue('window.open("http://en.wikipedia.org/wiki/{levels(dat$continent)[continent]}")') | |
), | |
position = position_nudge(y = 0.25), | |
width = 0.5 | |
) + | |
geom_point_interactive( | |
aes(col = continent), | |
position = position_nudge(y = -0.2), | |
size = 11, | |
shape = '|', | |
alpha = 0.75 | |
) + | |
scale_fill_manual(values = color_palette) + | |
scale_color_manual(values = color_palette) + | |
labs( | |
x = 'Life expectancy (in years)', | |
y = element_blank(), | |
title = glue::glue('Distribution of Life Expectancy in {selected_year}') | |
) + | |
theme_minimal(base_size = base_size) + | |
theme( | |
text = element_text( | |
color = 'grey20' | |
), | |
legend.position = 'none', | |
panel.grid.minor = element_blank(), | |
plot.title.position = 'plot' | |
) | |
girafe( | |
ggobj = box_plot, | |
options = list( | |
opts_hover(css = ''), | |
opts_hover_inv(css = "opacity:0.1;"), | |
opts_tooltip(offx = 25, offy = 0, css = 'background:black;color:white;font-size:16pt;font-family:Open Sans;') | |
), | |
height_svg = 9, | |
width_svg = 16 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment