33 Improving ggplotly() | Interactive web-based data visualization with R, plotly, and shiny (2024)

Since the ggplotly() function returns a plotly object, we can use that object in the same way you can use any other plotly object. Modifying this object is always going to be useful when you want more control over certain (interactive) behavior that ggplot2 doesn’t provide an API to describe46, for example:

  • layout() for modifying aspects of the layout, which can be used to do many things, for example:
  • style() for modifying data-level attributes, which can be used to:
    • Control the tooltip content and styling (see Chapter 25.2).
    • Turn hovering on/off (see Figure 33.4).
    • Add marker points to lines (e.g., style(p, mode = "markers+lines")).
  • config() for modifying the plot configuration, which can be used to:
    • Control the modebar (see Chapter 26).
    • Change the default language (see Chapter 30).
    • Enable LaTeX rendering (see Chapter 31).
    • Enable editable shapes (see Chapter 12).

In addition to using the functions above to modify ggplotly()’s return value, the ggplotly() function itself provides some arguments for controlling that return value. In this chapter, we’ll see a couple of them:

  • dynamicTicks: should plotly.js dynamically generate axis tick labels? Dynamic ticks are useful for updating ticks in response to zoom/pan interactions; however, they can not always reproduce labels as they would appear in the static ggplot2 image (see Figure 33.1).
  • layerData: return a reference to which ggplot2 layer’s data (see Figure 33.5)?

33.1 Modifying layout

Any aspect of a plotly objects layout can be modified47 via the layout() function. By default, since it doesn’t always make sense to compare values, ggplotly() will usually set layout.hovermode='closest'. As shown in Figure 33.1, when we have multiple y-values of interest at a specific x-value, it can be helpful to set layout.hovermode='x'. Moreover, for a long time series graph like this, zooming in on the x-axis can be useful – dynamicTicks allows plotly.js to handle the generation of axis ticks and the rangeslider() allows us to zoom on the x-axis without losing the global context.

library(babynames)nms <- filter(babynames, name %in% c("Sam", "Alex"))p <- ggplot(nms) +  geom_line(aes(year, prop, color = sex, linetype = name)) ggplotly(p, dynamicTicks = TRUE) %>% rangeslider() %>% layout(hovermode = "x")

FIGURE 33.1: Adding dynamicTicks, a rangeslider(), and a comparison hovermode to improve the interactive experience of a ggplotly() graph. For the interactive, see https://plotly-r.com/interactives/ggplotly-rangeslider.html

Since a single plotly object can only have one layout, modifying the layout of ggplotly() is fairly easy, but it’s trickier to modify the data underlying the graph.

33.2 Modifying data

As mentioned previously, ggplotly() translates each ggplot2 layer into one or more plotly.js traces. In this translation, it is forced to make a number of assumptions about trace attribute values that may or may not be appropriate for the use case. To demonstrate, consider Figure 33.2, which shows hover information for the points, the fitted line, and the confidence band. How could we make it so hover information is only displayed for the points and not for the fitted line and confidence band?

33 Improving ggplotly() | Interactive web-based data visualization with R, plotly, and shiny (1)

FIGURE 33.2: A scatterplot with a fitted line and confidence band.

The ggplot2 package doesn’t provide an API for interactive features, but by changing the hoverinfo attribute to "none", we can turn off hover for the relevant traces. This sort of task (i.e.modifying trace attribute values) is best achieved through the style() function. Before using it, you may want to study the underlying traces with plotly_json() which uses the listviewer package to display a convenient interactive view of the JSON object sent to plotly.js (de Jong and Russell 2016). By clicking on the arrow next to the data element, you can see the traces (data) behind the plot. As shown in Figure 33.3, we have three traces: one for the geom_point() layer and two for the geom_smooth() layer.

plotly_json(p)

33 Improving ggplotly() | Interactive web-based data visualization with R, plotly, and shiny (2)

FIGURE 33.3: Using listviewer to inspect the JSON representation of a plotly object.

This output indicates that the fitted line and confidence band are implemented in the 2nd and 3rd trace of the plotly object, so to turn off the hover of those traces:

style(p, hoverinfo = "none", traces = 2:3)

33 Improving ggplotly() | Interactive web-based data visualization with R, plotly, and shiny (3)

FIGURE 33.4: Using the style() function to modify hoverinfo attribute values of a plotly object created via ggplotly() (by default, ggplotly() displays hoverinfo for all traces). In this case, the hoverinfo for a fitted line and error bounds are hidden.

33.3 Leveraging statistical output

Since ggplotly() returns a plotly object, and plotly objects can have data attached to them, it attaches data from ggplot2 layer(s) (either before or after summary statistics have been applied). Furthermore, since each ggplot layer owns a data frame, it is useful to have some way to specify the particular layer of data of interest, which is done via the layerData argument in ggplotly(). Also, when a particular layer applies a summary statistic (e.g., geom_bin()), or applies a statistical model (e.g., geom_smooth()) to the data, it might be useful to access the output of that transformation, which is the point of the originalData argument in ggplotly().

p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + geom_smooth()p %>% ggplotly(layerData = 2, originalData = FALSE) %>% plotly_data()#> # A tibble: 80 x 14#> x y ymin ymax se flipped_aes PANEL group#> <dbl> <dbl> <dbl> <dbl> <dbl> <lgl> <fct> <int>#> 1 1.51 32.1 28.1 36.0 1.92 FALSE 1 -1#> 2 1.56 31.7 28.2 35.2 1.72 FALSE 1 -1#> 3 1.61 31.3 28.1 34.5 1.54 FALSE 1 -1#> 4 1.66 30.9 28.0 33.7 1.39 FALSE 1 -1#> 5 1.71 30.5 27.9 33.0 1.26 FALSE 1 -1#> 6 1.76 30.0 27.7 32.4 1.16 FALSE 1 -1#> # … with 74 more rows, and 6 more variables:#> # colour <chr>, fill <chr>, size <dbl>,#> # linetype <dbl>, weight <dbl>, alpha <dbl>

The data shown above is the data ggplot2 uses to actually draw the fitted values (as a line) and standard error bounds (as a ribbon). Figure 33.5 leverages this data to add additional information about the model fit; in particular, it adds a vertical lines and annotations at the x-values that are associated with the highest and lowest amount uncertainty in the fitted values. Producing a plot like this with ggplot2 would be impossible using geom_smooth() alone.48 Providing a simple visual clue like this can help combat visual misperceptions of uncertainty bands due to the sine illusion (VanderPlas and Hofmann 2015).

p %>% ggplotly(layerData = 2, originalData = FALSE) %>% add_fun(function(p) { p %>% slice(which.max(se)) %>% add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>% add_annotations("Maximum uncertainty", ax = 60) }) %>% add_fun(function(p) { p %>% slice(which.min(se)) %>% add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>% add_annotations("Minimum uncertainty") })

33 Improving ggplotly() | Interactive web-based data visualization with R, plotly, and shiny (4)

FIGURE 33.5: Leveraging data associated with a geom_smooth() layer to display additional information about the model fit.

In addition to leveraging output from StatSmooth, it is sometimes useful to leverage output of other statistics, especially for annotation purposes. Figure 33.6 leverages the output of StatBin to add annotations to a stacked bar chart. Annotation is primarily helpful for displaying the heights of bars in a stacked bar chart, since decoding the heights of bars is a fairly difficult perceptual task (Cleveland and McGill 1984). As result, it is much easier to compare bar heights representing the proportion of diamonds with a given clarity across various diamond cuts.

p <- ggplot(diamonds, aes(cut, fill = clarity)) + geom_bar(position = "fill")ggplotly(p, originalData = FALSE) %>% mutate(ydiff = ymax - ymin) %>%  add_text( x = ~x, y = ~(ymin + ymax) / 2, text = ~ifelse(ydiff > 0.02, round(ydiff, 2), ""), showlegend = FALSE, hoverinfo = "none", color = I("white"), size = I(9) )

33 Improving ggplotly() | Interactive web-based data visualization with R, plotly, and shiny (5)

FIGURE 33.6: Leveraging output from StatBin to add annotations to a stacked bar chart (created via geom_bar()) which makes it easier to compare bar heights.

Another useful application is labelling the levels of each piece/polygon output by StatDensity2d as shown in Figure 33.7. Note that, in this example, the add_text() layer takes advantage of ggplotly()’s ability to inherit aesthetics from the global mapping. Furthermore, since originalData is FALSE, it attaches the “built” aesthetics (i.e., the x/y positions after StatDensity2d has been applied to the raw data).

p <- ggplot(MASS::geyser, aes(x = waiting, y = duration)) + geom_density2d()ggplotly(p, originalData = FALSE) %>%  group_by(piece) %>% slice(which.min(y)) %>%  add_text( text = ~level, size = I(16), color = I("black"), hoverinfo="none" )

33 Improving ggplotly() | Interactive web-based data visualization with R, plotly, and shiny (6)

FIGURE 33.7: Leveraging output from StatDensity2d to add annotations to contour levels.

References

Cleveland, William S, and Robert McGill. 1984. “Graphical Perception: Theory, Experimentation, and Application to the Development of Graphical Methods.” Journal of the American Statistical Association 79 (September): 531–54.

de Jong, Jos, and Kenton Russell. 2016. Listviewer: ’Htmlwidget’ for Interactive Views of R Lists. https://github.com/timelyportfolio/listviewer.

VanderPlas, Susan, and Heike Hofmann. 2015. “Signs of the Sine Illusion—Why We Need to Care.” Journal of Computational and Graphical Statistics 24 (4): 1170–90. https://doi.org/10.1080/10618600.2014.951547.

  1. It can also be helpful for correcting translations that ggplotly() doesn’t get quite right.↩︎

  2. Or, in the case of cumulative attributes, like shapes, images, annotations, etc, these items will be added to the existing items↩︎

  3. It could be recreated by fitting the model via loess(), obtaining the fitted values and standard error with predict(), and feeding those results into geom_line()/geom_ribbon()/geom_text()/geom_segment(), but that process is much more onerous.↩︎

33 Improving ggplotly() | Interactive web-based data visualization with R, plotly, and shiny (2024)

FAQs

What is the difference between ggplot2 and plotly in R? ›

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.

What does ggplotly do? ›

Built on top of the Plotly JavaScript library (plotly.js), plotly enables Python users to create beautiful interactive web-based visualizations that can be displayed in Jupyter notebooks, saved to standalone HTML files, or served as part of pure Python-built web applications using Dash.

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 is the Plot_ly function in R? ›

The plot_ly() function has numerous arguments that are unique to the R package (e.g., color , stroke , span , symbol , linetype , etc) and make it easier to encode data variables (e.g., diamond clarity) as visual properties (e.g., color).

What is ggplot2 used for? ›

ggplot2 is an R package for producing statistical, or data, graphics. Unlike most other graphics packages, ggplot2 has an underlying grammar, based on the Grammar of Graphics (Wilkinson 2005), that allows you to compose graphs by combining independent components. This makes ggplot2 powerful.

Why is ggplot2 so popular? ›

The answer is that ggplot2 is declaratively and efficient in creating data visualization based on The Grammar of Graphics. The layered grammar makes developing charts structural and effusive. Generating ggplot2 feels like playing with LEGO blocks.

What are the benefits of ggplot? ›

So why do we need another plotting method, to make the same plot?
ggplot2 Pros:ggplot2 Cons:
consistent, concise syntaxdifferent syntax from the rest of R
intuitive (to many)does not handle a few types of output well
visually appealing by default
entirely customizable

Why should I use plotly? ›

Plotly is like a piece of paper, you can draw whatever you want on it. Compared to traditional visualization tools like Tableau, Plotly allows full control over what is being plotted. Since Plotly is plotted based on Pandas, you can easily perform complex transformations to your data before plotting it.

What is plotly in data visualization? ›

Plotly, an open-source Python module, supports data visualization with various graphs like line charts, scatter plots, bar charts, histograms, area plots, and more. Plotly's Python graphing library makes it easy to create interactive graphs.

Is plotly part of Ggplot? ›

Plotly is an R package for creating interactive web-based graphs via plotly's JavaScript graphing library, plotly. js . The plotly R package serializes ggplot2 figures into Plotly's universal graph JSON.

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 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.

Is Plotly better than GGplot? ›

In terms of speed, ggplot2 tends to run much slower than Plotly. With regard to integration, both Plotly and ggplot2 can integrate with a variety of tools, like Python, MATLAB, Jupyter, and React. Both Plotly and ggplot2 are good options for both large and small businesses.

What is R function used for? ›

A key feature of R is functions. Functions are “self contained” modules of code that accomplish a specific task. Functions usually take in some sort of data structure (value, vector, dataframe etc.), process it, and return a result.

What are functions in R plot? ›

There are three basic plotting functions in R: high-level plots, low-level plots, and the layout command par. Basically, a high-level plot function creates a complete plot and a low-level plot function adds to an existing plot, that is, one created by a high-level plot command.

Is Plotly part of ggplot? ›

Plotly is an R package for creating interactive web-based graphs via plotly's JavaScript graphing library, plotly. js . The plotly R package serializes ggplot2 figures into Plotly's universal graph JSON.

What is the difference between ggplot and R plot? ›

The graph made by ggplot is more clear. The default color is not grey and black and we can see the labels in x direction and we also have legends by default. However, the graph made by normal r packages doesn't have default legends and x labels.

What is the difference between ggplot and ggplot2 in R? ›

ggplot2 is the latest version of the popular open-source data visualization tool ggplot for R, used to create plots using the function ggplot(). It is part of the R tidyverse ecosystem, designed with common APIs, and is used in the statistical programming language.

Is Plotnine the same as ggplot2? ›

Except for the quotation of column names, plotnine has exactly the same syntax as ggplot2 - this is remarkable!

Top Articles
Feral Frenzy Shark
Deze 43 nieuwe films komen in de bioscoop in september 2024
Alvin Isd Ixl
Smsgt Promotion List
Gfr Soccer
All Obituaries | Sneath Strilchuk Funeral Services | Funeral Home Roblin Dauphin Ste Rose McCreary MB
Vons Credit Union Routing Number
Saccone Joly Gossip
Tmobile Ipad 10Th Gen
Charli D'Amelio: Wie die junge Amerikannerin TikTok-Sensation wurde
Jodie Sweetin Breast Reduction
6 Underground movie review & film summary (2019) | Roger Ebert
Tmobile Ipad 10Th Gen
Chesapeake Wv Topix
Dr. Nicole Arcy Dvm Married To Husband
Who has the best money market rate right now?
Savage Model 110 Serial Number Lookup
Giantesssave
Mobile Maher Terminal
Iapd Lookup
Amanda Balionis makes announcement as Erica Stoll strides fairways with Rory McIlroy
Carly Carrigan Family Feud Instagram - Carly Carrigan Home Facebook : The best gifs for carly family feud.
Equity Livestock Monroe Market Report
Dna Profiling Virtual Lab Answer Key
Teddy Torres Machoflix
SF bay area cars & trucks "chevrolet 50" - craigslist
Alexandria Van Starrenburg
Herdis Eriksson Obituary
Hawkview Retreat Pa Cost
18443168434
Best Hs Bball Players
Latest News Archives - Mon Valley Independent
Panama City News Herald Obituary
Sim7 Bus Time
Jackandjill Pregnant
Malibu Horror Story Showtimes Near Regal Atlantic Station
The Little Mermaid 2023 Showtimes Near Marcus South Pointe Cinema
The Safe Keeper Henderson
Chess Unblocked Games 66
Gowilkes For Rent
76 Games Unblocked Fnf
How Much Does Costco Gas Cost Today? Snapshot of Prices Across the U.S. | CostContessa
Uncg Directions
Craigslist Ft Meyers
168 Bus Schedule Pdf 2022
Ultimate Guide to Los Alamos, CA: A Small Town Big On Flavor
Stock Hill Restaurant Week Menu
3143656395
Keystyle.hensel Phelps.com/Account/Login
Cnas Breadth Requirements
Pfcu Chestnut Street
Sterling Primary Care Franklin
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 5517

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.