Introduction to Interactive Graphics in R with plotly (2024)

Posted on June 9, 2019 by Rstats on pi: predict/infer in R bloggers | 0 Comments

[This article was first published on Rstats on pi: predict/infer, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

R users adore the ggplot2 package for all things data visualization. Its consistent syntax, useful defaults, and flexibility make it a fantastic tool for creating high-quality figures. Although ggplot2 is great, there are other dataviz tools that deserve a place in a data scientist’s toolbox. Enter plotly.

plotly is a high-level interface to plotly.js, based on d3.js which provides an easy-to-use UI to generate slick D3 interactive graphics. These interactive graphs give the user the ability to zoom the plot in and out, hover over a point to get additional information, filter to groups of points, and much more. These interactive components contribute to an engaging user experience and allows information to be displayed in ways that are not possible with static figures.

The wonder of htmlwidgets

As you may have guessed, the “.js” in plotly.js is short for JavaScript. JavaScript is a programming language that runs a majority of the Internet’s interactive webpages. To make a webpage interactive, JavaScript code is embedded into HTML which is run by the user’s web browser. As the user interacts with the page, the JavaScript renders new HTML, providing the interactive experience that we are looking for. htmlwidgets is the framework that allows for the creation of R bindings to JavaScript libraries. These JavaScript visualizations can be embedded into R Markdown documents (html) or shiny apps.

Here are a few examples of JavaScript bindings in R:
plotly
highcharter
diagrammeR
leaflet

Usage

There are two main approaches to initialize a plotly object: transforming a ggplot2 object with ggplotly() or setting up aesthetics mappings with plot_ly() directly.

ggplotly

ggplotly() takes existing ggplot2 objects and converts them into interactive plotly graphics. This makes it easy to create interactive figures while using the ggplot2 syntax that we’re already used to. Additionally, ggplotly() allows us to use ggplot2 functionality that would not be as easily replicated with plotly and tap into the wide range of ggplot2 extension packages.

Let’s look at an example using the mpg dataset from ggplot2.

library(dplyr)library(ggplot2)library(plotly)(ggplot_object <- mpg %>% ggplot(aes(x = displ, y = hwy)) + geom_point(mapping = aes(color = class)) + geom_smooth())

Introduction to Interactive Graphics in R with plotly (1)

ggplotly(ggplot_object)

After saving a ggplot2 object, the only step to plotly-ize it is calling ggplotly() on that object.

The difference between the two is that the plotly figure is interactive. Try it out for yourself! Some of the interactive features to try out include hovering over a point to see the exact x and y values, zooming in by selecting (click+drag) a region, and subsetting to specific groups by clicking their names in the legend.

plot_ly

plot_ly() is the base plotly command to initialize a plot from a dataframe, similar to ggplot() from ggplot2.

mpg %>% plot_ly(x = ~displ, y = ~hwy, color = ~class)## No trace type specified:## Based on info supplied, a 'scatter' trace seems appropriate.## Read more about this trace type -> https://plot.ly/r/reference/#scatter## No scatter mode specifed:## Setting the mode to markers## Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

Although we did not specify the plot type, it defaulted to a scatter plot. The type of plot is specified by setting the trace type. The scatter trace type is the foundation for many low-level geometries (e.g., points, lines, and text), thus we must also specify a mode. To create a scatter plot with points the mode is set to markers, but additional scatter modes include lines, paths, segments, ribbons, polygons, and text.

plotly functions take a plotly object as an input and return a modified plotly object, making it work perfectly with the pipe (%>%).

mpg %>% plot_ly(x = ~displ, y = ~hwy, color = ~class) %>% add_trace(type = "scatter", mode = "markers")

add_markers

Rather than using add_trace() and specifying the type and mode, we can use the convenience function add_markers().

mpg %>% plot_ly(x = ~displ, y = ~hwy, color = ~class) %>% add_markers()

Making other plot types is similarly easy by using the corresponding add_*() function. See the documentation for a full list of traces: https://rdrr.io/cran/plotly/man/add_trace.html.

Conclusion

I was never taught about interactive graphics in school and never felt the need to learn it, but now I find uses for it all the time. Whether you are making a shiny app or just writing a statistical report I recommend trying out plotly. There is not much of a learning curve due to the intuitive syntax, and it makes high quality graphics that are sure to impress. This post only scratches the surface of plotly, but I hope this introduction gives you more confidence to try it out in your future work.

Related

To leave a comment for the author, please follow the link and comment on their blog: Rstats on pi: predict/infer.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Introduction to Interactive Graphics in R with plotly (2024)

FAQs

How to create an interactive graph in R? ›

The best way to build an interactive bubble chart from R is through the plotly library. If you know how to make a ggplot2 chart, you are 10 seconds away to rendering an interactive version= just call the ggplotly() function, and you're done. ← this chart is interactive: hover, drag, zoom, export and more.

Can Plotly be interactive? ›

Plotly figures are interactive when viewed in a web browser: you can hover over data points, pan and zoom axes, and show and hide traces by clicking or double-clicking on the legend.

Can you use Plotly in R? ›

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

What are the different types of graphing in Plotly R? ›

Plotly's R graphing library makes interactive, publication-quality graphs. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, and 3D (WebGL based) charts.

What is the difference between ggplot2 and plotly? ›

Plotly is the second most popular visualization package in R after ggplot2. Whereas ggplot2 is used for static plots, plotly is used for creating dynamic plots. Similarly, it offers a plethora of options in terms of chart type we can visualize our data with.

Can you make ggplot interactive? ›

However, ggplot cannot make interactive plots. To help ggplot create interactive plots, we can use a package called plotly. Plotly is an open-source package in R and is based on JavaScript by the same name, plotly.

What is better than Plotly? ›

For simple data visualisation, Matplotlib is the best. If you want to do more complex things, then Seaborn and Plotly become more useful.

Why use Plotly instead of Matplotlib? ›

Ease of Use: Plotly's syntax is user-friendly and intuitive, often requiring fewer lines of code to generate complex visualizations compared to Matplotlib. This makes it accessible for beginners and efficient for those who need to create plots quickly.

Is plotly for R free? ›

Plotly for R is free and open-source software, licensed under the MIT license. It costs nothing to install and use.

What is the difference between plotly and plotly Dash? ›

So Plotly is the library we use to plot, and Dash is the framework we use to generate cool, interactive dashboards from those plots. Here's the set of steps we'll follow to build today's dashboard: Setup and installation — to get us in the proper state. Some simple use cases — to show how Plotly works.

Can R be used for graphics? ›

Graphing in R is like painting and uses a canvas approach; you start out with an empty plot (called a device). You'll add your data points, axis titles, graph title, color customizations, and other functions individually. Each time a graphics function is used, R 'paints' the new customizations onto your plot device.

Can R make interactive graphs? ›

Through connections with JavaScript libraries, such as htmlwidgets for R (https://www.htmlwidgets.org), R can generate interactive graphs that can be explored in RStudio's viewer window or placed on external web pages.

What are the three plotting systems in R? ›

Watch a video of this chapter. There are three different plotting systems in R and they each have different characteristics and modes of operation. They three systems are the base plotting system, the lattice system, and the ggplot2 system. This chapter (and this book) will focus primarily on the base plotting system.

Is Dash by Plotly free? ›

Yes. Plotly's Dash analytics application framework is also free and open-source software, licensed under the MIT license.

How do I make an animated graph in R? ›

This article describes how to create animation in R using the gganimate R package. gganimate is an extension of the ggplot2 package for creating animated ggplots. It provides a range of new functionality that can be added to the plot object in order to customize how it should change with time.

How to create an interactive dashboard in R? ›

If you have this package installed, you can create a dashboard by opening your RStudio session and selecting “File” -> “New File” -> “RMarkdown”. In the box that pops up, go to the “From Template” tab and select “Flexdashboard”.

How to save an interactive plot in R? ›

In R, saving plots can be achieved through various techniques. These methods include using the ggsave() function from ggplot2 for saving ggplot2 plots and employing dev. copy() and dev. off() functions for base R graphics.

Top Articles
Nikki Catsouras: A Tragic Story Of Life, Death, And Infamy
Nikki Catsouras: The Tragic Accident And Its Impact On Digital Privacy
12 Beginner Tips for Raid: Shadow Legends
Spasa Parish
Houston Isd Applitrack
Is Jennifer Coffindaffer Married
Petco Clinic Hours
Seattle Clipper Vacations Ferry Terminal Amtrak
Tear Of The Kingdom Nsp
Minecraft Jenny Mod Dragon Staff
Terry Gebhardt Obituary
Bekijk hier het rouwregister van Uitvaartzorg FSK
Nsu Kpcom Student Handbook
Tyson Employee Paperless
Summoner Calamity
Craigslist Hutchinson Ks
Belle Fourche Landfill
Ff14 Cloth Softening Powder
Half Inning In Which The Home Team Bats Crossword
My Big Fat Greek Wedding 3 Showtimes Near Regal Ukiah
Craigslis Nc
Amsterdam, Netherlands to PST - Savvy Time
Chula Vista Tv Listings
My Sagu Blackboard
Contenidos del nivel A2
EVOLVE: Predicting User Evolution and Network Dynamics in Social Media Using Fine-Tuned GPT-like Model
The Blind Showtimes Near Showcase Cinemas Springdale
Holly Ranch Aussie Farm
Dash Ag Grid
Birkenstock Footprints Lawrence Ks
Chittenden County Family Court Schedule
Dayinew
Obsidian Guard's Skullsplitter
Deerc De22 Drone Manual Pdf
Orbison Roy: (1936 1988) American Singer. Signed 7 X 9
Royal Carting Holidays 2022
Small Party Hall Near Me
Oklahoma Scratch Off Remaining Prizes
Lincoln Access Rewards Redemption
William Sokol National Security Advisor Resigns
Fanart Tv
Fallen Avatar Mythic Solo
Sayuri Pilkey
Foolproof Module 6 Test Answers
Wbap Iheart
Gym Membership & Workout Classes in Lafayette IN | VASA Fitness
Goldthroat Goldie
Top-Filme und Serien mit Maggie Smith
Florida-Texas A&M: What You Need to Know - Florida Gators
The Crew 2 Cheats für PS4, Xbox One und PC ▷➡️
Bòlèt New York Soir
The Emperor's New Groove | Rotten Tomatoes
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 5521

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.