Interactive Power BI Custom Visuals with R
By: Freddie Tasker
Tags: Towards Data Science, Ggplot, Plotly, Power Bi, R

Interactive Power BI Custom Visuals with R

Sometimes the right Power BI visual just isn’t there. Trying to create an executive summary of project management data recently I hit just this wall.

The idea was a report page that would be a front page to users - a quick signpost before they got into the detail of the other report pages, and something that would easily translate to a slide in a presentation. Attempts at slimmed down Gantt charts were all messy and unwieldly.

A great example from the 2003 SARS outbreak of where causally linked information can be powerful, but often project management data can overload a computer screen. Molecular epidemiology of the novel coronavirus that causes severe acute respiratory syndrome (The Lancet)

The Power BI R Script Visual

After a bit of hard thought (playing) a basic horizontal timeline seemed to work well. It would focus on the project milestones, use colour to describe the project status and try its best to get the project related text as readable as possible.

The R script visual, quick to develop and (sometimes irritatingly) customisable

There didn’t seem to be a ready made visual in Microsoft’s AppSource that would do this, so turned to the R Script Visual. With a bit of R knowledge, these are quick to develop and allow the use of the endlessly customisable ggplot to get it looking exactly how you want it (n.b. other R plotting packages are available).

Here’s how it ended up. Project data has been replaced with the UK’s prime ministers and the project status colour now tells us what party they’re in. It might be handy in your next Zoom quiz. Code here. Thank you to Ben Alex Keen, who has a great article on the construction of this kind of timeline in R.

The R visual dropped into the report as expected. Moving from accessing the JSON data directly in R to dealing with the data from the Power BI R Script Visual needed some variable renaming and formatting .The Power BI friendly code for the visual is here.

The only thing these R plots are missing is a bit of interactivity. You can restrict the data going into them with Power BI’s slicers and filters but you can’t hover over and get a tooltip, or zoom in on an interesting bit.

Plotly

Thanks to the plotly package , we can turn our ggplot object into some html and add at least some of this interactivity.

g = ggplotly(p, tooltip = 'text') %>%

layout(legend = list(

orientation = 'h',

y = 1.1,

x = 0.1

));

Plotly will also host these charts, and you can push them up from within R.

Sys.setenv(plotly_username = 'xxx')

Sys.setenv(plotly_api_key = 'xxxxxxxxxxx') api_create(g)

The Tooltip

As well as a host of other plotly features, we now have a hover over tooltip. Really useful in providing some more information in this fairly compact graph. This was defined using a dummy aesthetic in the geom_text call, named ‘text’ (ggplot ignores this aesthetic).

#Tooltip for plotly

prime_ministers[,text:=paste0(

name, ', ', party, '<br>'

,format(start_date,'%d %b %Y'),' to ',format(end_date,'%d %b %Y')

)] # Show project text

p <- p + geom_text(aes(label = name,

text=text,x=decade

,y = text_position,colour=party),

size = 3, family = 'sans',show.legend = F, fontface='bold')

A custom tooltip is passed from ggplot to the plotly object using the dummy ‘text’ aesthetic in the final call to geom_text

ggplotly quirks

A quick side note on using ggplotly for this task.

geom_label: In our conversion to plotly from ggplot using ggplotly, geom_label isn’t supported, so the transparent rectangles behind each text label have been replaced with font coloring.

Legend naming: There was also some strange behaviour with the legend, ‘Whig’ became ‘(Whig,1)’ etc. This was caused by the ggplot object having both a colour scale (for text and points) and a fill scale (not used, since no geom_label). The manual fill scale was removed, but it would be annoying if a fill scale was needed. The only solution seemed to be manually adjusting the plotly object json.

Package R Code into Power BI Custom Visual

The final step is getting this plotly object into Power BI.

We can’t just paste our R code directly into the R Script Visual. The ggplotly function outputs an HTML object and Power BI is expecting an R plot object.

Well it turns out that with not too much work, we can create our own custom visual to import into Power BI. Here’s a quick step by step.

1 - Install node.js

2 - Install the powerbi-visuals-tools package with Powershell

npm install -g powerbi-visuals-tools

3 - Create an rhtml template

pbiviz new fredTimelineVis -t rhtml

4 - Find the folder and files that this command creates (this depends on the working directory of your Powershell). Then find the script.r file, and replace the ggplot code with your own

On my computer the rhtml files were output to C:/Users/FredTasker/fredTimelineVis. The script.R has an example ggplot chunk, and a ggplotly line, which I replaced with those above.

Packaging up the prime ministers. Replace the ggplot / ggplotly bits of the script.R file that powerbi-visuals-tools creates.

A couple of notes:

Make sure you have the right library declarations at the top of script.R and remember that R packages need to exist in Power BI online if that’s where you are going to use it

The data that’s coming from Power BI is referred to as the Values object in R.

Here’s the script.R file used in this example.

5 - Add author, description and support URL to the pbiviz.json

This is important, as package compiling will fail if you don’t. pbviz.json will be in the same directory as your scripts.R file.



"description":"Horizontal timeline visual build using ggplot and plotly in R",

"supportUrl":"https://medium.com/@fredtasker/interactive-power-bi-custom-visuals-with-r-a6a4ac998710",

"gitHubUrl":"https://github.com/fredwise/PM_timeline"},

...

"author":{"name":"Fred Tasker","email":"xxxx.com"}

... ..."description":"supportUrl":"gitHubUrl":},..."author":{"name":"email":...

6 -Go back to PowerShell, navigate to your script.r directory and package it all up, ready for Power BI to consume.

In my case:

cd C:\Users\FredTasker\fred_timeline_vis pbiviz package

Success!

If you run into issues,here’s the Microsoft help page for R HTML.

Import into Power BI

Now that the custom visual is packaged, we just need to import it into Power BI and drop our data fields into the visual.

Import the pbiz vis file from the dist directory of your compiled package

Well this was all very exciting. A really quick way to build interactive custom visuals in Power BI.

Have a look at the resulting dashboard on the Power BI service, you’ll see that Power BI’s Publish to Web doesn’t currently support the static R visual. To see the static graph in the PBIX file and all other scripts mentioned here head to GitHub.