Many times you may wish to add a horizontal or vertical line to a visualization. This can be to show a baseline threshold, mark off an area, and more. In Displayr, you can add a straight line to select visualizations by editing the underlying R code. This way you can go from a visualization that looks like this:
to one with a line that looks like this:
We cover a few things in this article:
Requirements
- An R-based visualization built off of the plotly package:
Bar: Bar, Stacked Bar, Small Multiples Bar, Funnel, Small Multiples Funnel
Column: Column, Stacked Column, Small Multiples Column, Sparkline Column
Radar: Radar, Small Multiples Radar
Line: Line, Small Multiples Line, Sparkline Line, Sparkline Line with End Labels, Sparkline Curve, Sparkline Curve with End Labels
Distributions: Histogram, Small Multiples Histogram, Bean, Small Multiples Bean, Density, Small Multiples Density, Violin, Small Multiples Violin, Box, Small Multiples Box, Sparkline Box
Geographic Map: Geographic Map, Small Multiples Geographic Map (only when plotly is selected as the map package)
Area: Area, Stacked Area, Stacked Area 100%, Small Multiples Area, Sparkline Area, Sparkline Area with End Labels
Exotic: Price Sensitivity Meter
Choice Modeling and MaxDiff Diagnostics: Utilities Plot
- Familiarity with R coding, see the primer document in Using R in Displayr Video Series and How to Learn R for a list of helpful articles for this.
Method 1 - Using a hard-coded value
The easiest way to add a line to a chart is to add it using a hardcoded value.
- Select your visualization and click into the object inspector > Data > Show Advanced Options > R Code > Edit Code.
- The Code Editor will appear at the top where you can edit the R code. Scroll to the bottom and add a few blank lines. This will trigger a prompt that will confirm you indeed want to edit the code and warn you that if you do, then we can't guarantee the code will work after future updates. Click Yes.
- Paste the following code on one of the newly inserted blank lines at the bottom. This code creates a function
addline()
that you can use to add lines on top of the visualization you just created and lists a couple examples:
###################### ADD LINES CODE ######################
#pull off underlying widget
newchart <- plotly::plotly_build(viz$htmlwidget)
#initialize the list of shapes
layout=list(shapes=list())
#make addline function
addline <- function(shapes, dir, val, color, width, style){
i = length(shapes)+1
if(dir == "vertical"){
shapes[[i]]=list(type="line",
layer="above",
x0=val,
x1=val,
xref="x",
y0=0,
y1=1,
yref="paper",
line=list(
color=color,
width=width,
dash=style
)
)
} else {
shapes[[i]]=list(type="line",
layer="above",
x0=0,
x1=1,
xref="paper",
y0=val,
y1=val,
yref="y",
line=list(
color=color,
width=width,
dash=style
)
)
}
return(shapes)
}
########## EDIT HERE to ADD CUSTOM LINES
## use the addline function to add lines to the visualization
## addline settings:
## dir = direction of the line -- values are: "vertical", "horizontal"
## val = value to put line -- values are: a value or category on the axis
## color = color of the line -- values are: HTML name or HEX value
## width = width of the line -- values are: numbers greater than 0
## style = style of the line -- values are: "solid", "dot", "dash", "longdash", "dashdot", or "longdashdot")
#add first line by modifying below
layout$shapes = addline(layout$shapes, dir="vertical", val= as.Date("2019-07-01"), color="red", width = 1, style="dotted")
## to add more lines copy and modify the settings in the line above
layout$shapes = addline(layout$shapes, dir="horizontal", val= 0, color="black", width = 1, style="solid")
# layout$shapes = addline(layout$shapes, dir="horizontal", val= 3.5, color="blue", width = 1, style="dash")
##########
##save list of lines to viz
newchart$x$layout$shapes <- layout$shapes
#return final viz
newchart
- Under the section ########## EDIT HERE to ADD CUSTOM LINES there's information on how to use the
addline()
function. You will use theaddline()
function to add individual lines to thelayout$shapes
list of lines to add on top of the plot. See the comments in the code for more details. - The
val
argument in theaddline()
function is the value of where to put the line. Depending on what type of data is on the axis this can be a dateas.Date("2019-11-06")
, a category"Coca-Cola"
, or a value3.5
.
Method 2 - Calculating a value for the line
You can also calculate your own custom value to use to place the line. This can update when data is updated or filtered in the input table. To do so:
- Follow steps 1-5 in Method 1 to insert the new code at the bottom of the code and edit the lines you want to add. For now, you can disregard the
val
argument in theaddline()
function as this is what we want to calculate. - Before the ########## EDIT HERE to ADD CUSTOM LINES section you can add in new lines to do the calculations. Then you can reference those calculations for the
val
argument in theaddline()
function. The data that is used for plotting is in a variable calledpd$data
but depending on significance testing you may need to convert that into a table differently. The code below turns the data from the plot into a data frame table calledthedata
:########## Calculations to place lines
#if there is significance on the chart, need to pull off the plot data differently
if(length(dim(pd$data)) > 2){
thedata = data.frame(pd$data[,,1], check.names=F)
} else {
thedata = data.frame(pd$data, check.names=F)
} - You can reference specific bits of the data using the row/column label or index (number) and use basic math functions. For example, below I will calculate the average across all the data to add a horizontal line for the average to the chart. You'd place these line below the
thedata
code from 2. above:
#calculate the average across all data
overallavg=Average(thedata) - Next you will follow the instructions in the ########## EDIT HERE to ADD CUSTOM LINES section to create the line using the new calculation
overallavg
as theval
argument:layout$shapes = addline(layout$shapes, dir="horizontal", val= overallavg, color="red", width = 3, style="dot")
- Another example, you can add a line for the average of a specific series. Below the
thedata
code from 2. above you'd add:
#calculate the average for coca-cola for the line
cokeavg=Average(thedata[,"Coca-Cola"]) - And create the line in the ########## EDIT HERE to ADD CUSTOM LINES section to create the line using the new calculation
cokeavg
as theval
argument:layout$shapes = addline(layout$shapes, dir="horizontal", val= cokeavg, color="red", width = 3, style="dot")
Technical Notes
- Most importantly, the straight lines cannot be exported to editable charts in PowerPoint, but can be exported if the visualization is exported as an image.
- You do not need to base your calculations off of the data used in the chart. You can base it off other variables and outputs, see How to Reference Different Items in Your Document in R.
- More examples of calculations you can include after
thedata
code:- The average of the most recent period:
#calculate the average for the most recent period (data is in bottom row)
curravg=Average(thedata[NROW(thedata),]) - The 80th percentile from the data:
#calculate the 80th percentile
eightypctl=quantile(thedata,.8,na.rm=T)
- The average of the most recent period:
Next
How to Show a Moving (Rolled) Average on a Line Chart Visualization
How to Create a Time Series - Column with Trend Tests Chart
How to Modify Significance Notation and Add Other Annotations to Visualizations