How to Create Interactive Visualizations in R



Image by Editor | Midjourney

 

Traditional static charts are useful, but interactive visuals offer more flexibility. They allow users to explore data, zoom in on details, and see changes over time. R has several packages that can be used to create interactive visualizations like tables, charts and maps.

 

Getting Started

 

To create interactive visualizations in R, you need to install some packages. These packages provide tools for data manipulation and visualization.

# Install required packages
install.packages("tidyverse")
install.packages("DT")
install.packages("ggplot2")
install.packages("dplyr")
install.packages("gapminder")
install.packages("plotly")
install.packages("leaflet")

# Load the packages
library(tidyverse)
library(DT)
library(ggplot2)
library(dplyr)
library(gapminder)
library(plotly)
library(leaflet)

 

Interactive Tables

 

The DT package in R helps you make interactive tables. You can sort, filter and search the data.

Here’s how to create an interactive table using the gapminder dataset:

# Load the necessary library
library(DT)

# Create an interactive data table
datatable(gapminder, 
          options = list(pageLength = 10, 
                         autoWidth = TRUE, 
                         dom = 'Bfrtip', 
                         buttons = c('copy', 'csv', 'excel', 'pdf', 'print'))) %>%
  formatCurrency('gdpPercap', currency = "$") %>%
  formatStyle('lifeExp', 
              backgroundColor = styleInterval(c(50, 70), c('red', 'green', 'blue')))

 

You can see the data and sort it by clicking on the column headers. The search box helps you find specific countries or values quickly.

 

Interactive Charts

 

Plotly is a great package for creating interactive plots. You can turn static ggplot2 charts into interactive ones. You can also create new interactive charts using Plotly’s functions.

Here’s how to create an interactive scatter plot using the gapminder dataset:

# Create an interactive scatter plot
plot_ly(data = gapminder, 
        x = ~gdpPercap, 
        y = ~lifeExp, 
        color = ~continent, 
        text = ~paste(country, "", "GDP per Capita:", gdpPercap), 
        type="scatter",    
        mode="markers") %>% layout(title = "GDP per Capita vs Life Expectancy",
        xaxis = list(title = "GDP per Capita (Log Scale)", type = "log"),  
        yaxis = list(title = "Life Expectancy"))

 

In this plot, you can hover over the points. This shows more information about each country. It helps you understand the data.

Similarly, you can also create a bar chart using the gapminder dataset:

# Calculate the average life expectancy for each continent
avg_lifeExp %
  group_by(continent) %>%
  summarise(avg_lifeExp = mean(lifeExp, na.rm = TRUE))

# Create an interactive bar chart
plot_ly(data = avg_lifeExp, 
        x = ~continent, 
        y = ~avg_lifeExp, 
        type="bar", 
        marker = list(color="orange")) %>%  
  layout(title = "Average Life Expectancy by Continent",
         xaxis = list(title = "Continent"),
         yaxis = list(title = "Average Life Expectancy"),
         showlegend = FALSE)

 

In this bar chart, you can hover over each bar to see the average life expectancy for that continent. This helps you compare the life expectancy across different regions.

 

Interactive Maps

 

You can create interactive geographical maps to display data by region using the leaflet. The map centers around a global view with zoom controls for easy exploration.

# Create a dataset with country coordinates 
country_coords %
    filter(year == 2007) %>%
    left_join(country_coords, by = "country")

# Create the leaflet map
leaflet(gapminder_data) %>%
    addTiles() %>%
    setView(lng = 0, lat = 20, zoom = 2) %>%  ]
    addCircleMarkers(
        lng = ~lon, 
        lat = ~lat, 
        radius = ~sqrt(pop / 1000000),  ]
        color = "blue", 
        stroke = FALSE, 
        fillOpacity = 0.5, 
        popup = ~paste("", country, "<br>Population: ", format(pop, big.mark = ","))
    ) %>%
    addLegend("bottomright", 
              pal = colorNumeric("Blues", NULL), 
              values = ~pop, 
              title = "Population",
              labFormat = labelFormat(big.mark = ","), 
              opacity = 1)

 

You can click on a marker to see a popup with the country’s name and population. You can zoom in and out to see different parts of the world.

 

Conclusion

 

In conclusion, making interactive visuals in R helps with data analysis. You can use packages like Plotly, DT, Leaflet, and gapminder. These tools let you create charts, tables and maps. They help you explore data and discover insights more easily. Try these techniques to improve your data presentations.
 
 

Jayita Gulati is a machine learning enthusiast and technical writer driven by her passion for building machine learning models. She holds a Master’s degree in Computer Science from the University of Liverpool.

Our Top 3 Course Recommendations

1. Google Cybersecurity Certificate – Get on the fast track to a career in cybersecurity.

2. Google Data Analytics Professional Certificate – Up your data analytics game

3. Google IT Support Professional Certificate – Support your organization in IT

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here