DEV Community

Dipti M
Dipti M

Posted on

From Static to Stunning: Interactive Charts in R using Plotly

Introduction

Data visualization is no longer about just creating good-looking charts — it’s about making your audience interact with the story behind the numbers. Traditional static plots can show trends and comparisons, but interactive visualizations go one step further: they invite exploration. With interactive charts, users can zoom in on specific regions, hover over points to get details, or filter by categories — all within a browser.
That’s where Plotly steps in. Known for its versatility, Plotly helps analysts, data scientists, and business users turn static visuals into dynamic, shareable dashboards without leaving the R environment. In this article, we’ll explore how to use Plotly in R — from basic plots to advanced, interactive dashboards — and understand how it can elevate your data storytelling game.

What is Plotly and Why Use It?

Plotly is an open-source library built for interactive, publication-quality visualizations. In R, it’s available as the plotly package, which seamlessly integrates with R’s base plotting system as well as ggplot2.
Unlike traditional charting libraries, Plotly generates web-based visualizations using JavaScript under the hood. The best part? You don’t need to write a single line of JavaScript — the R package handles it for you.
Here’s why many data professionals choose Plotly:
Interactivity out of the box: Zoom, pan, hover, and filter without extra code.
Compatibility: Works perfectly with ggplot2 through ggplotly().
Cross-platform sharing: Easily export visualizations as HTML for web or presentations.
Scalability: Handles large datasets efficiently with smooth rendering.
Getting Started: Installation and Setup
Before you begin, make sure you have Plotly installed in your R environment.

Install the package (only once)

install.packages("plotly")

Load the library

library(plotly)

Once installed, you’re ready to create your first interactive plot.
Creating Your First Interactive Chart
Let’s start simple — a scatter plot showing the relationship between two variables.

Sample data

data <- mtcars

Basic interactive scatter plot

fig <- plot_ly(data, x = ~mpg, y = ~hp, type = 'scatter', mode = 'markers',
marker = list(size = 10, color = 'blue'),
text = ~paste("Car:", rownames(data)))

Display the plot

fig

Explanation:

x and y define the axes (mpg vs. hp).
mode = 'markers' makes it a scatter plot.
text adds tooltips that display when you hover over a point.
The resulting plot is interactive — hover to see car details, zoom in on clusters, or reset the view with a click.
Adding Style: Titles, Axes, and Layouts
You can easily enhance your chart by customizing the layout and labels:
fig <- fig %>%
layout(title = "Horsepower vs. Miles per Gallon",
xaxis = list(title = "Miles per Gallon"),
yaxis = list(title = "Horsepower"),
hovermode = "closest")

fig

This small tweak adds polish and improves readability. With just a few lines, you’ve transformed a static scatter plot into a sleek, interactive graphic ready for presentation.
Interactive Line Chart Example
Line charts are ideal for showing trends over time. Let’s visualize monthly sales data:

Sample dataset

month <- month.abb
sales <- c(210, 240, 260, 290, 330, 370, 400, 390, 370, 340, 310, 280)

line_data <- data.frame(month, sales)

fig <- plot_ly(line_data, x = ~month, y = ~sales, type = 'scatter', mode = 'lines+markers',
line = list(color = 'orange', width = 3),
marker = list(size = 8),
text = ~paste("Sales:", sales))

fig <- fig %>%
layout(title = "Monthly Sales Trend",
xaxis = list(title = "Month"),
yaxis = list(title = "Sales (in USD)"))

fig

Hovering over each point shows exact sales figures — a quick, interactive way to explore seasonal patterns or dips in performance.
Combining Multiple Traces
Plotly shines when you want to overlay different datasets or categories in one visualization.

Simulated data for two products

month <- month.abb
productA <- c(210, 240, 260, 290, 330, 370, 400, 390, 370, 340, 310, 280)
productB <- c(180, 210, 240, 260, 310, 340, 370, 360, 340, 300, 280, 260)

fig <- plot_ly(x = ~month, y = ~productA, type = 'scatter', mode = 'lines+markers', name = 'Product A',
line = list(color = 'steelblue')) %>%
add_trace(y = ~productB, name = 'Product B',
line = list(color = 'tomato')) %>%
layout(title = "Sales Comparison: Product A vs Product B",
xaxis = list(title = "Month"),
yaxis = list(title = "Sales (in USD)"))

fig

With this, viewers can toggle categories directly from the legend and instantly compare performance across products.
Creating 3D Visualizations
Want to impress your audience with something more dynamic? Try 3D plots.
fig <- plot_ly(mtcars, x = ~mpg, y = ~disp, z = ~hp,
type = "scatter3d", mode = "markers",
color = ~cyl, colors = c("blue", "green", "red"),
marker = list(size = 5)) %>%
layout(title = "3D Visualization of Engine Metrics")

fig

Here, each car is represented as a point in 3D space, with color-coded cylinders. Users can rotate, zoom, and explore different perspectives effortlessly.
Integrating Plotly with ggplot2
If you’re already using ggplot2, you don’t have to start from scratch. Plotly allows you to make any ggplot interactive using ggplotly().
library(ggplot2)

Create a ggplot

p <- ggplot(mtcars, aes(x = mpg, y = hp, color = factor(cyl))) +
geom_point(size = 3) +
labs(title = "Horsepower vs. MPG by Cylinder")

Convert ggplot to interactive plot

ggplotly(p)

In a single line, your ggplot gains all the interactive features — hover, zoom, and filtering — with no extra configuration needed.
Practical Example: Sales Performance Dashboard
Let’s combine what we’ve learned into a business-relevant example. Suppose you’re analyzing sales performance across regions and product lines.
sales_data <- data.frame(
Region = rep(c("North", "South", "East", "West"), each = 4),
Quarter = rep(c("Q1", "Q2", "Q3", "Q4"), times = 4),
Sales = c(120, 150, 180, 200, 90, 110, 130, 160, 140, 170, 190, 220, 100, 130, 160, 190)
)

fig <- plot_ly(sales_data, x = ~Quarter, y = ~Sales, color = ~Region,
type = 'bar', text = ~paste("Region:", Region, "
Sales:", Sales),
hoverinfo = "text") %>%
layout(title = "Quarterly Sales by Region",
xaxis = list(title = "Quarter"),
yaxis = list(title = "Sales (in $ Thousands)"),
barmode = "group")

fig

This type of dashboard visualization helps leadership teams quickly compare performance across regions and time periods, making it easier to spot growth opportunities or underperforming segments.

Conclusion

Interactive visualizations have become essential for modern analytics — they don’t just present data; they invite exploration. With Plotly, R users can effortlessly move from static plots to dynamic, interactive dashboards that engage decision-makers and uncover insights faster.
Whether you’re building a quick exploratory graph or a business-ready visualization, Plotly’s simplicity, flexibility, and interactivity make it one of the best tools for data storytelling in R.
So go ahead — experiment with your datasets, try different plot types, and transform your analysis into an engaging experience.
Happy Visualizing

At Perceptive Analytics, our mission is “to enable businesses to unlock value in data.” For over 20 years, we’ve partnered with more than 100 clients—from Fortune 500 companies to mid-sized firms—to solve complex data analytics challenges. We deliver expert Tableau partner company in Charlotte and Tableau partner company in Houston services, helping enterprises design powerful dashboards and visual insights. Our experienced Excel consultants in Sacramento assist teams with automation, analysis, and business intelligence solutions that drive better decisions. We turn data into strategic insight and would love to talk to you. Do reach out to us.

Top comments (0)