25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (2024)

25.1 plot_ly() tooltips

There are two main approaches to controlling the tooltip: hoverinfo and hovertemplate. I suggest starting with the former approach since it’s simpler, more mature, and enjoys universal support across trace types. On the other hand, hovertemplate does offer a convenient approach for flexible control over tooltip text, so it can be useful as well.

The hoverinfo attribute controls what other plot attributes are shown into the tooltip text. The default value of hoverinfo is x+y+text+name (you can verify this with schema()), meaning that plotly.js will use the relevant values of x, y, text, and name to populate the tooltip text. As in Figure 25.1 shows, you can supply custom text (without the other ‘calculated values’) by supplying a character string text and setting hoverinfo = "text". The character string can include Glyphs, unicode characters, a some (white-listed) HTML entities and tags.43 At least currently, plotly.js doesn’t support rendering of LaTeX or images in the tooltip, but as demonstrated in Figure 21.3, if you know some HTML/JavaScript, you can always build your own custom tooltip.

library(tibble)library(forcats)tooltip_data <- tibble( x = " ", y = 1, categories = as_factor(c( "Glyphs", "HTML tags", "Unicode",  "HTML entities", "A combination" )), text = c( "👋 glyphs ಠ_ಠ", "Hello <span style='color:red'><sup>1</sup>⁄<sub>2</sub></span>  fraction", "\U0001f44b unicode \U00AE \U00B6 \U00BF", "&mu; &plusmn; &amp; &lt; &gt; &nbsp; &times; &plusmn; &deg;", paste("<b>Wow</b> <i>much</i> options", emo::ji("dog2")))plot_ly(tooltip_data, hoverinfo = "text") %>% add_bars( x = ~x, y = ~y, color = ~fct_rev(categories),  text = ~text ) %>%  layout( barmode ="stack",  hovermode = "x" )

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (1)

FIGURE 25.1: Customizing the tooltip by supplying glyphs, Unicode, HTML markup to the text attributes and restricting displayed attributes with hoverinfo='text'.

Whenever a fill is relevant (e.g., add_sf(), add_polygons(), add_ribbons(), etc), you have the option of using the hoveron attribute to generate a tooltip for the supplied data points, the filled polygon that those points define, or both. As Figure 25.2 demonstrates, if you want a tooltip attached to a fill, you probably want text to be of length 1 for a given trace. On the other hand, if you want to each point along a fill to have a tooltip, you probably want text to have numerous strings.

p <- plot_ly( x = c(1, 2, 3), y = c(1, 2, 1), fill = "toself", mode = "markers+lines", hoverinfo = "text")subplot( add_trace(p, text = "triangle", hoveron = "fills"), add_trace(p, text = paste0("point", 1:3), hoveron = "points"))

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (2)

FIGURE 25.2: Using the hoveron attribute to control whether a tooltip is attached to fill or each point along that fill.

You can’t supply custom text in this way to a statistical aggregation, but there are ways to control the formatting of values computed and displayed by plotly.js (e.g.x, y, and z). If the value that you’d like to format corresponds to an axis, you can use *axis.hoverformat. The syntax behind hoverformat follows d3js’ format conventions. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format and for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format

set.seed(1000)plot_ly(x = rnorm(100), name = " ") %>%  add_boxplot(hoverinfo = "x") %>% layout(xaxis = list(hoverformat = ".2f"))

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (3)

FIGURE 25.3: Using xaxis.hoverformat to round aggregated values displayed in the tooltip to two decimal places.

Computed values that don’t have a corresponding axis likely have a *hoverformat trace attribute. Probably the most common example is the z attribute in a heatmap or histogram2d chart. Figure 25.4 shows how to format z values to have one decimal.

plot_ly(z = ~volcano) %>% add_heatmap(zhoverformat = ".1f") %>% layout(xaxis = list(hoverformat = ".2f"))

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (4)

FIGURE 25.4: Formatting the displayed z values in a heatmap using zhoverformat.

It’s admittedly difficult to remember where to specify these hoverformat attributes, so if you want a combination of custom text and formatting of computed values you can use hovertemplate, which overrides hoverinfo and allows you to fully specify the tooltip in a single attribute. It does this through special markup rules for inserting and formatting data values inside a string. Figure 25.5 provides an example of inserting x and y in the tooltip through the special %{variable:format} markup as well as customization of the secondary box through <extra> tag. For a full description of this attribute, including the formatting rules, see https://plot.ly/r/reference/#scatter-hovertemplate.

set.seed(10)plot_ly(x = rnorm(100, 0, 1e5)) %>% add_histogram( histnorm = "density", hovertemplate = "The height between <br> (%{x}) <br> is %{y:.1e}  <extra>That's small!</extra>" )

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (5)

FIGURE 25.5: Using the hovertemplate attribute to reference computed variables and their display format inside a custom string.

If you need really specific control over the tooltip, you might consider hiding the tooltip altogether (using hoverinfo='none') and defining your own tooltip. Defining your own tooltip, however, will require knowledge of HTML and JavaScript – see Figure 21.3 for an example of how to display an image on hover instead of a tooltip.

25.2 ggplotly() tooltips

Similar to how you can use the text attribute to supply a custom string in plot_ly() (see Section 25.1), you can supply a text aesthetic to your ggplot2 graph, as shown in 25.6:

p <- ggplot(mtcars, aes(wt, mpg, text = row.names(mtcars))) +  geom_point()ggplotly(p)

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (6)

FIGURE 25.6: Using the text ggplot2 aesthetic to supply custom tooltip text to a scatterplot.

By default, ggplotly() will display all relevant aesthetic mappings (or computed values), but you can restrict what aesthetics are used to populate the tooltip, as shown in Figure 25.7:

ggplotly(p, tooltip = "text")

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (7)

FIGURE 25.7: Using the tooltip argument in ggplotly() to only display the text aesthetic.

When constructing the text to display, ggplotly() runs format() on the computed values. Since some parameters of the format() function can be controlled through global options(), you can use these options() to control the displayed text. This includes the digits option for controlling the number of significant digits used for numerical values as well as scipen for setting a penalty for deciding whether scientific or fixed notation is used for displaying. Figure 25.8 shows how you can temporarily set these options (i.e., avoid altering of your global environment) using the withr package (Hester et al. 2018).

library(withr)p <- ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density))subplot( with_options(list(digits = 1), ggplotly(p)), with_options(list(digits = 6, scipen = 20), ggplotly(p)))

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (8)

FIGURE 25.8: Leveraging global R options for controlling the displayed values in a ggplotly() tooltip.

These global options are nice for specifying significant/scientific notation, but what about more sophisticated formatting? Sometimes a clever use of the text aesthetic provides a sufficient workaround. Specifically, as Figure 25.9 shows, if one wanted to control a displayed aesthetic value (e.g., y), one could generate a custom string from that variable and supply it to text, then essentially replace text for y in the tooltip:

library(scales)p <- ggplot(txhousing, aes(date, median)) +  geom_line(aes( group = city,  text = paste("median:", number_si(median)) ))ggplotly(p, tooltip = c("text", "x", "city"))

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (9)

FIGURE 25.9: Using the text aesthetic to replace an auto-generated aesthetic (y).

The approach depicted in Figure 25.9 works for computed values that pertain to raw data values, but what about sophisticated formatting of a summary statistics generated by ggplot2? In this case, you’ll have to use the return value of ggplotly() which, remember, is a plotly object that conforms to the plotly.js spec. That means you can identify trace attribute(s) that contain relevant info (note: the plotly_json() function is incredibly for helping to find that information), then use that info to populate a text attribute. Figure 25.10 applies this technique to customize the text that appears when hovering over a geom_smooth() line.

# Add a smooth to the previous figure and convert to plotlyw <- ggplotly(p + geom_smooth(se = FALSE))# This plotly object has two traces: one for# the raw time series and one for the smooth. # Try using `plotly_json(w)` to confirm the 2nd# trace is the smooth line.length(w$x$data)# use the `y` attribute of the smooth line # to generate a custom string (to appear in tooltip)text_y <- number_si( w$x$data[[2]]$y,  prefix = "Typical median house price: $")# suppress the tooltip on the raw time series # and supply custom text to the smooth linew %>% style(hoverinfo = "skip", traces = 1) %>% style(text = text_y, traces = 2)

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (10)

FIGURE 25.10: Using the return value of ggplotly() to populate a custom text attribute.

25.3 Styling

There is currently one main attribute for controlling the style of a tooltip: hoverlabel. With this attribute you can currently set the background color (bgcolor), border color (bordercolor), and font family/size/color. Figure 25.11 demonstrates how to use it with plot_ly() (basically any chart type you use should support it):

font <- list( family = "Roboto Condensed", size = 15, color = "white")label <- list( bgcolor = "#232F34", bordercolor = "transparent", font = font)plot_ly(x = iris$Petal.Length, hoverlabel = label)

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (11)

FIGURE 25.11: Using the hoverlabel attribute to customize the color and font of the tooltip.

On the other hand, when using ggplotly(), you have to modify the hoverlabel attribute via style() as shown in Figure 25.12

qplot(x = Petal.Length, data = iris) %>% ggplotly() %>% style(hoverlabel = label, marker.color = "#232F34") %>% layout(font = font)

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (12)

FIGURE 25.12: Using the hoverlabel attribute with ggplotly().

As shown in sections 25.1 and 25.2 the approach to customized the actual text of a tooltip is slightly different depending on whether you’re using ggplotly() or plot_ly(), but styling the appearance of the tooltip is more or less the same in either approach.

References

Hester, Jim, Kirill Müller, Kevin Ushey, Hadley Wickham, and Winston Chang. 2018. Withr: Run Code ’with’ Temporarily Modified Global State. https://CRAN.R-project.org/package=withr.

  1. If you find a tag or entity that you want isn’t supported, please request it to be added in the plotly.js repository https://github.com/plotly/plotly.js/issues/new↩︎

25 Controlling tooltips | Interactive web-based data visualization with R, plotly, and shiny (2024)

FAQs

Is R shiny a data visualization tool? ›

Shiny, an R package, is renowned for its ability to create interactive web applications directly from R. One of its core features is the seamless integration of powerful data visualization libraries such as ggplot2 and plotly, which enable users to construct sophisticated and dynamic visual representations of data.

What is tooltip in data visualization? ›

Tooltips are the little boxes that pop up when you hover over something. (Hovercards are more general, and can appear anywhere on the screen; tooltips are always attached to something, like a dot on a scatter chart, or a bar on a bar chart.)

What is R data visualization? ›

Data visualization is a technique used for the graphical representation of data. By using elements like scatter plots, charts, graphs, histograms, maps, etc., we make our data more understandable. Data visualization makes it easy to recognize patterns, trends, and exceptions in our data.

Which package in R is commonly used for data visualization? ›

Plotly. Plotly is a free open-source graphing library that can be used to form data visualizations. Plotly is an R package that is built on top of the Plotly JavaScript library (plotly.

Is R Shiny faster than Tableau? ›

However, as we saw, you can make a simple dashboard much faster with Tableau than with R Shiny. For this reason, we'll declare Tableau the winner for simple dashboards, but only for ease of use.

What is the use of R Shiny? ›

Shiny is an R package that enables building interactive web applications that can execute R code on the backend. With Shiny, you can host standalone applications on a webpage, embed interactive charts in R Markdown documents, or build dashboards.

What is a tooltip example? ›

Common Tooltip Examples and Use Cases

Indicating keyboard shortcuts: Tooltips can display keyboard shortcuts for specific actions or commands, helping users learn and utilize shortcuts to navigate the interface more efficiently–UXPin's design interface uses tooltips to educate users about shortcuts.

When should I use tooltips? ›

TL;DR
  1. A tooltip is a text box used to provide additional guidance and drive user action. ...
  2. Top use cases for tooltips in SaaS: new user onboarding, product tours, feature announcements, and contextual upsells.
  3. Tooltips should be placed near the active element they're describing.
Nov 30, 2022

What is tooltip in Python? ›

A tooltip is a box that appears next to an element when a user hovers over the element. To add a tooltip to a UI component, wrap the component in ui. tooltip() . Then pass ui. tooltip() one or more elements to display, such as a simple string that contains a message.

Is R or Python better for visualization? ›

R excels in statistical computing, data analysis, and visualization, making it a preferred choice for researchers and statisticians. On the other hand, Python offers versatility, ease of learning, and a broader range of applications beyond data science, making it popular among developers and analysts.

How to create a visualization using R? ›

When creating a visualization with ggplot, we first use the function ggplot and define the data that the visualization will use, then, we define the aesthetics which define the layout, i.e. the x- and y-axes. In a next step, we add the geom-layer which defines the type of visualization that we want to display.

Is R a data visualization tool? ›

R is a software environment and statistical programming language built for statistical computing and data visualization.

What is the alternative to Plotly in R? ›

9 Useful R Data Visualization Packages for Data Visualization
  • ggplot2.
  • Lattice.
  • highcharter.
  • Leaflet.
  • RColorBrewer.
  • Plotly.
  • sunburstR.
  • RGL.
Dec 1, 2021

What is the most widely used data visualization tool? ›

Top Data Visualization Tools
  • Qlik Sense.
  • Domo.
  • Microsoft Power BI.
  • Klipfolio.
  • SAP Analytics Cloud.
  • Yellowfin.
  • Whatagraph.
  • Dundas BI.
May 14, 2024

How to manipulate data in R? ›

Main data manipulation functions
  1. filter() : Pick rows (observations/samples) based on their values.
  2. distinct() : Remove duplicate rows.
  3. arrange() : Reorder the rows.
  4. select() : Select columns (variables) by their names.
  5. rename() : Rename columns.
  6. mutate() and transmutate() : Add/create new variables.

Is Ggplot a data visualization tool? ›

ggplot2 is a R package dedicated to data visualization.

What is the difference between looker and Shiny? ›

While Looker is more focused on data exploration and visualization, Shiny allows for more customization and flexibility through code-based application development.

Which tool is used for data visualization? ›

Some of the best data visualization tools include Google Charts, Tableau, Grafana, Chartist, FusionCharts, Datawrapper, Infogram, and ChartBlocks etc. These tools support a variety of visual styles, be simple and easy to use, and be capable of handling a large volume of data.

Top Articles
ME/cvs: Top tips. Een overzicht voor artsen | ME/cvs Vereniging
ME/CVS: het chronisch vermoeidheidssyndroom
Corgsky Puppies For Sale
Pga Scores Cbs
Burkes Outlet Credit Card Sign In
What to Do For Dog Upset Stomach
Greater Keene Men's Softball
The Canterville Ghost Showtimes Near Northwoods Cinema 10
eHerkenning | Leveranciersoverzicht
Www.1Tamilmv.con
nycsubway.org: The Independent Fleet (1932-1939)
Northamptonshire | England, Map, History, & Facts
Zulrah Strat Osrs
El Puerto Harrisonville Mo Menu
Do people over 65 pay federal income tax?
Japan’s Dagashi Treats: A Tasty Trip Down Memory Lane – Umami bites
Dupage County Fcrc
Tryhard Guide Wordle Solver
Point Click Care Cna Lo
15:30 Est
Metoprolol  (Kapspargo Sprinkle, Lopressor) | Davis’s Drug Guide
Ihub Fnma Message Board
H. P. Lovecraft - Deutsche Lovecraft Gesellschaft
Dead By Daylight Subreddit
Boys golf: Back-nine surge clinches Ottumwa Invite title for DC-G
Gopher Hockey Forum
Spring Tx Radar
Az511 Twitter
27 Sage Street Holmdel Nj
20 of the Best Restaurants in Moscow, Russia by a Local
Antique Wedding Favors
Xdm16Bt Manual
Rachel Campos-Duffy - Net Worth, Salary, Age, Height, Bio, Family, Career
Susan Dey Today: A Look At The Iconic Actress And Her Legacy
Landwatch Ms
Craigslist Labor Gigs Albuquerque
Sentara Reference Lab Solutions Bill Pay
Generation Zero beginner’s guide: six indispensable tips to help you survive the robot revolution
Fanart Tv
Ucla Course Schedule
Currently Confined Coles County
Sak Pase Rental Reviews
Dimensional Doors Mod (1.20.1, 1.19.4) - Pocket Dimensions
Left Periprosthetic Femur Fracture Icd 10
Veronika Sherstyuk Height
Kohl's Hixson Tennessee
Craigslist Old Forge
Walmart Makes Its Fashion Week Debut
Panguitch Lake Webcam
my Control Vitality Female Support Complex (10 ml)
Mri Prospect Connect
Xochavella Leak
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 5519

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.