If you need to create very custom visualizations using R code in a Calculation, you should consider turning the code into an R function to create a template for the visualization to be used throughout your Document. This will keep the look and feel of your report consistent, and if future changes are needed, you will only need to change the R code in one place to modify all the relevant visualizations.
This example, shows you how to create a chart template that uses a table
To create the chart shown below, which is showing GDP by country:
Requirements
- The final chart was created with the Displayr/flipStandardCharts package on GitHub, but the principles can be applied to almost any charting package in R.
- A table with data for the visualization.
- Knowledge about R Functions in How to Use R in Displayr and How to Create Custom R Functions.
Method
- Create the R Function code that this and other Calculations can use to create the visualization. From the toolbar, go to Calculation > Custom Code and draw a box on the page.
- Paste the following into the R CODE:
#Name your function this one is called MyBarChartTemplate
#the function takes one input it will name x and use in the remaining code
MyBarChartTemplate = function(x) {
#load the charting package of functions
require(flipStandardCharts)
#use the Chart function from flipStandardCharts to create a custom visualization
Chart(x,
data.label.show = TRUE,
data.label.font.size = 8,
data.label.font.family = "Arial Narrow",
data.label.decimals = 0,
type = "Bar",
y.grid.width = 0,
x.tick.show = FALSE,
x.grid.width = 0,
x.bounds.minimum = 0,
x.bounds.maximum = 22000)
}
3. With the Calculation selected, click Hide so the code isn't exported when you export the document.
4. To use the template to create a visualization, go to Calculation > Custom Code and draw a box on the page.
5. Paste the following into the R CODE:
#create a chart using the gdp table above using MyBarChartTemplate
MyBarChartTemplate(gdp)
[OPTIONAL] To modify all the visualizations using the template, you will modify the template code from Step 2.
[OPTIONAL] You can also share this function across documents, see How to Share Custom R Functions in Displayr.
Next
How to Share Custom R Functions in Displayr