Created
January 30, 2023 19:47
-
-
Save AlbertRapp/884e46472fd99fb17e64162ab0c80386 to your computer and use it in GitHub Desktop.
interactve_line_chart.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) | |
| # STEP 0: Compute Data and generate color palette | |
| mean_life_exps <- gapminder::gapminder |> | |
| janitor::clean_names() |> | |
| group_by(continent, year) |> | |
| summarise(mean_life_exp = mean(life_exp)) | |
| color_palette <- thematic::okabe_ito(5) | |
| names(color_palette) <- unique(dat$continent) | |
| # STEP 1: Use interactive geoms | |
| line_chart <- mean_life_exps |> | |
| ggplot( | |
| aes( | |
| x = year, | |
| y = mean_life_exp, | |
| col = continent, | |
| # STEP 2: Use data_id aesthetic to share | |
| # interactivity across continent line | |
| data_id = continent | |
| ) | |
| ) + | |
| geom_line_interactive(linewidth = 2.5) + | |
| geom_point_interactive(size = 4) + | |
| theme_minimal(base_size = 20) + | |
| labs( | |
| x = element_blank(), | |
| y = 'Life expectancy (in years)', | |
| title = 'Life expectancy over time' | |
| ) + | |
| theme( | |
| text = element_text(color = 'grey20'), | |
| legend.position = 'none', | |
| panel.grid.minor = element_blank(), | |
| plot.title.position = 'plot' | |
| ) + | |
| scale_color_manual(values = color_palette) | |
| # STEP 3: Render plot | |
| girafe( | |
| ggobj = line_chart, | |
| # Optional: add hover transparency | |
| options = list( | |
| opts_hover(css = ''), | |
| opts_hover_inv(css = "opacity:0.1;") | |
| ), | |
| height_svg = 6, # Optional: Set plot height | |
| width_svg = 9 # Optional: Set plot width | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment