In this challenge, I’ve learned how to make interactive visualizations using the plotly package in R. Interactive visualizations provide several advantages over static ones:
Working with ggplotly() has shown me how seamlessly R can transform static ggplot2 visualizations into interactive versions while maintaining the elegant grammar of graphics. The ability to customize tooltips makes the visualizations more informative and user-friendly.
Creating a dashboard with flexdashboard has also demonstrated how we can organize multiple visualizations into a cohesive report that’s both aesthetically pleasing and functionally rich.
library(tidyverse)
library(plotly)
if (!require(gapminder)) install.packages("gapminder")
library(gapminder)
# Load data
data(gapminder)
# 1. Make a basic scatter plot
p <- gapminder %>%
filter(year == 2007) %>%
ggplot(aes(x = gdpPercap, y = lifeExp,
color = continent,
size = pop,
text = paste("Country:", country,
"<br>Life Expectancy:", round(lifeExp, 1), "years",
"<br>GDP per capita:", round(gdpPercap, 2), "USD",
"<br>Population:", scales::comma(pop)))) +
geom_point(alpha = 0.7) +
scale_x_log10() +
labs(title = "Life Expectancy vs. GDP per Capita (2007)",
x = "GDP per Capita (log scale, USD)",
y = "Life Expectancy (years)",
color = "Continent",
size = "Population") +
theme_minimal()
# 2. Make the plot interactive with ggplotly
# 3. Make sure the hovering tooltip is more informative
ggplotly(p, tooltip = "text") %>%
layout(hoverlabel = list(bgcolor = "white"))
Install the {flexdashboard} package and create a new R Markdown file in your project by going to File > New File… > R Markdown… > From Template > Flexdashboard.
Using the documentation for {flexdashboard} online, create a basic dashboard that shows a plot (static or interactive) in at least three chart areas. Play with the layout if you’re feeling brave.