
Image by Editor | Midjourney
Visualization is an important part of data analysis, helping us to communicate insights. In R, you can combine ggplot2 and Plotly to create interactive graphs. ggplot2 makes static plots, while Plotly adds interactivity. Together, they let you explore and share data dynamically.
This article will show you how to use both for interactive visualizations.
Installing the Required Libraries
First, install ggplot2 and plotly using the following commands:
# Install ggplot2 and plotly
install.packages("ggplot2")
install.packages("plotly")
# Load the libraries
library(ggplot2)
library(plotly)
Creating a Basic ggplot2 Plot
Let’s start by creating a ggplot2 plot. We’ll use the built-in mtcars dataset.
# Create a basic ggplot2 scatter plot p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(aes(color = factor(cyl)), size = 3) + labs(title = "Car Weight vs MPG", x = "Weight", y = "Miles per Gallon", color = "Cylinders") print(p)

The code creates a scatter plot using ggplot2 to visualize the relationship between car weight (wt) and miles per gallon (mpg) from the mtcars dataset. Points are plotted with different colors based on the number of cylinders (cyl).
Converting ggplot2 Plot to Plotly
We can make the ggplot2 plot interactive by using the ggplotly() function from Plotly.
# Convert ggplot2 plot to Plotly interactive_plot <- ggplotly(p) interactive_plot
When you run this code, the plot will become interactive. You can hover over points to see detailed information, zoom in, and pan around the plot.
Click here to view the output.
Customizing the Plotly Plot
After converting your ggplot2 plot to Plotly, you can improve interactivity and style. Plotly lets you change hover effects, colors, and the layout of the plot.
Customize Hover Information
You can modify the hover information using the tooltip argument. For example, you can display additional variables in the hover tooltip.
interactive_plot <- ggplotly(p, tooltip = c("x", "y", "color"))
interactive_plot
In this example, the tooltip will display the x-axis (weight), y-axis (mpg), and color (number of cylinders) values when you hover over a data point.
Click here to view the output.
Change the Layout
You can adjust various aspects of the layout of the plot, such as titles, axes, and the background color.
interactive_plot <- ggplotly(p) %>%
layout(
title = "Interactive Plot: Weight vs MPG",
xaxis = list(title = "Weight of Car (1000 lbs)"),
yaxis = list(title = "Miles per Gallon"),
plot_bgcolor = "#f5f5f5" # Changing the background color
)
interactive_plot
Click here to view the output.
Adding Shapes and Annotations
Plotly lets you add shapes and annotations to your plot. You can highlight important areas or add extra details.
interactive_plot <- ggplotly(p) %>%
layout(
annotations = list(
text = "Cluster of cars with high MPG",
x = 3, y = 25,
xref = "x", yref = "y",
showarrow = TRUE,
arrowhead = 2,
ax = 0, ay = -40
)
)
interactive_plot
This code will add a custom annotation with an arrow pointing to the region where cars with high MPG are clustered.
Click here to view the output.
Other Useful Plotly Features
Plotly has advanced features that make your ggplot2 plots more interactive.
Adding Dropdown Menus
You can create dropdown menus for users to select different visualizations or filters. For example, you could let users switch between different subsets of the data.
interactive_plot <- ggplotly(p) %>%
layout(
updatemenus = list(
list(
buttons = list(
list(method = "relayout", args = list("xaxis.range", c(2, 5)), label = "Zoom In"),
list(method = "relayout", args = list("xaxis.range", c(1, 6)), label = "Reset Zoom")
),
direction = "down",
showactive = TRUE,
active = 0,
x = 0.1,
y = 0.9
)
)
)
interactive_plot
Click here to view the output.
Adding Interactive Sliders
Plotly lets you add sliders to your plot. Sliders let users change parts of the plot. For example, they can filter data by time or range.
interactive_plot <- ggplotly(p) %>%
layout(
sliders = list(
list(
active = 0,
currentvalue = list(prefix = "Zoom: ", visible = TRUE),
steps = list(
list(label = "Full range", range = c(1, 6)),
list(label = "Zoom In", range = c(2, 5))
)
)
)
)
interactive_plot
Click here to view the output.
Conclusion
Combining ggplot2 and Plotly in R enhances your data visualizations. You can customize the plot, add annotations, and make it more engaging. With features like dropdown menus and sliders, you can create dynamic and interactive charts. This approach helps with better data exploration and insights sharing.
