Introduction
This article describes how to go from a visualization with a standard hover text format...
...to one with own that uses a custom hover text template:
Requirements
Please note this requires the Data Stories module or a Displayr license.
- An Area, Bar, Column, Line, Radar, or Scatterplot chart (without tests) created via Visualization in the toolbar.
- In this example, we have a column chart with the below source table that includes the statistics we wish to include in our hover text:
Method
1. Select your visualization.
2. In the object inspector, go to General > R CODE.
3. Select Yes to allow you to modify the underlying R code.
4. Find the last row that references hovertext
and add the below code:
hovertext.template = matrix(paste0("%{x}:%{y}<br>n=",
pd$data[,,"Count"]), ncol=NCOL(pd$data)),
- The
hovertext.template
argument requires a matrix as an input so we wrap our code within thematrix
function to include the updated label and the number of columns. - Here,
pd$data
is the input table for the visualization. -
%{x}
is the X axis label while%{y}
is the Y axis value which, in this case, is separated by a colon. We have then added a line break using the HTML <br> character and will append the input table's Count value to go alongside the percentages. Note, this statistic must be showing in our source table. - We then use the
paste0
function to combine all the elements together to form the hover text.
5. Press Calculate.
Technical details
-
You can't use commas in your table rownames or hover text directly. A way around this is to use the comma html tag
<span>,</span>
to insert a comma. If there are commas in the rownames or other headers you'd like to use in the hover you can replace them as so:gsub(",", "<span>,</span>", rownames(pd$data))
- For scatterplots, you will not use
ncol=NCOL(pd$data)
in the code snippet above, instead you will usencol=1
because each row is a single point on the graph (vs bars which will need a hover for each row+column pair).
See Also
Creating Charts and Visualizations in Displayr