The rflot
package is an R interface to the Flot JavaScript charting library. It is a thin wrapper, giving the [R] user unfettered access to the parameters of the JS library. It boasts the ability to display point, line, and bar charts and features:
Let us begin with a simple chart of ozone (in parts per billion) versus temperature. The function flotChart
is used to specify the main data-source for the chart, as well as mannually adjust the height and width of the plot. It needs to be paired with the flotSeries
function, which adds a layer/series to the chart.
flotChart(airquality) %>%
flotSeries(x=Temp,y=Ozone, label= '', points=list(show=T))
Next, let us make use of the Month
column to group the data. The data is automatically colored by the group variable.
flotChart(airquality) %>%
flotSeries(x=Temp, y=Ozone, group = Month, label="Month: ", points=list(show=T))
We can add additional series to the chart by chaining additional calls to flotSeries
.
flotChart(airquality) %>%
flotSeries(x=Temp, y=Ozone, group = Month, label="Month: ", points=list(show=T)) %>%
flotSeries(x=seq(min(Temp), max(Temp), .1)
,y=predict(lm(Ozone ~ Temp + I(Temp^2) + I(Temp^3)), newdata = data.frame(Temp=seq(min(Temp), max(Temp), .1)))
,label="")
Let us leverage the interactive features of flot to display custom tooltips. We use the flotOptions
function to make this happen. Note, as you hover, we display tooltips that contain information beyond just the x,y coordinate (in particular, they also show the date), and change background according to the series color. We also add the ability to drag-and-zoom (double-click to reset).
flotChart(airquality) %>%
flotSeries(x=Temp, y=Ozone, group = Month, label="Month: ", extra.cols=list(Wind, Solar.R, Day), points=list(show=T), clickable=T, hoverable=T) %>%
flotSeries(x=seq(min(Temp), max(Temp), .1)
,y=predict(lm(Ozone ~ Temp + I(Temp^2) + I(Temp^3)), newdata = data.frame(Temp=seq(min(Temp), max(Temp), .1)))
,label="") %>%
flotOptions(selection=list(mode="xy") #Enable zoom along both the the x- and y-axes
,tooltipOpts = list( #Customize tool-tip options
id = "customTip"
,content = htmlwidgets::JS("
function(label, xval, yval, flotItem) {
return 'Day: ' + flotItem.series.extra_data[flotItem.dataIndex][2] +
'<br>Solar.R: ' + flotItem.series.extra_data[flotItem.dataIndex][1] +
'<br>Wind: ' + flotItem.series.extra_data[flotItem.dataIndex][0];
}
")
,onHover = htmlwidgets::JS("
function(flotItem, el){
el.css('background-color', flotItem.series.color);
}")
)
,onClick = htmlwidgets::JS("
function(event,pos,item) {
if(item) {
alert('You clicked on something');
}
}
")
)
In addition to point, and line charts, we can easily use this package to put together a bar chart. In the example below, we mark the x-axis data as cathegorical(can also be continuous)
library(data.table)
flotChart(data.table(mtcars)[,list(count=.N),by=list(cyl)]) %>%
flotSeries(x=cyl, y=count
,label= ''
,bars=list(show=T, barWidth= 0.6,align="center")) %>%
flotOptions(yaxis=list(axisLabel='Count')
,xaxis=list(axisLabel="Number of Cylinders"
,mode="categories"
,tickLength= 0
))
As a more involved example, below we show how you can use this package to produce a dodged-stacked chart. Note, when stacking data using flot, the data must be sorted by the stacking variable.
flotChart(data.table(mtcars)[,list(count=.N),by=list(cyl)]) %>%
flotSeries(x=cyl, y=count
,label= 'Total'
,hoverable = T
,bars=list(show=T, order = 1, barWidth= 0.3)) %>%
flotSeries(data=data.table(mtcars)[,list(count=.N),by=list(cyl, gear)][order(cyl),], x=cyl, y=count, group=gear
,label= 'Count w/ Number of gears: '
,hoverable = T
,stack='gear'
,bars=list(show=T, order=2, barWidth= 0.3)) %>%
flotOptions(yaxis=list(axisLabel='Count')
,xaxis=list(axisLabel="Number of Cylinders"
,mode="categories"
,tickLength= 0
)
,legend=list(position="nw"
,backgroundColor='grey'
,backgroundOpacity=.1))
Finally let us examine how you would go about charting a dual-axis time series. All dates must be passed in UTC * 1000 (milliseconds) format. We customize the axis labels, tick color and font color. In the chart below we consider the daily evolution of MSFT and AAPL stock prices starting in 2010.
flotChart(read.csv("msft_aapl_stock_data.csv")) %>%
flotSeries(x=as.numeric(as.POSIXct(date))*1000, y=msft, hoverable=T) %>%
flotSeries(x=as.numeric(as.POSIXct(date))*1000, y=aapl, yaxis=2, color='red') %>%
flotOptions(xaxis=list(axisLabel = 'Date', mode='time')
,yaxes=list(
list(axisLabel='MSFT')
,list(axisLabel='AAPL', axisLabelUseCanvas=T, axisLabelColour='red', position= "right", color='red',tickColor='red', font=list(color='red')))
,selection=list(mode="x"))
With rflot
we have bundled a useful set of plug-ins that extend the functionality of Flot. However there are many other plug-ins you may wish to include in your app. You can do this easily by sourcing appropriate JS script.
This package exposes shiny output bindings that follow the standard shiny usage pattern. In particular to display the very first chart we examined via a shiny application, we pair the flotOutput
function used in ui.R
, with the renderFlot
function in server.R
. Moreover we include the symbols plugin, and use the diamond
shape for the scatter plot.
library(shiny)
shinyApp(
ui = fluidPage(
tags$head(tags$script(type = 'text/javascript', src="http://cdn.rawgit.com/flot/flot/master/jquery.flot.symbol.js"))
,fluidRow(style = "padding-bottom: 20px;"
,column(12,
flotOutput("flotGraph1", height=300)
)
)
)
,server = function(input, output, session) {
output$flotGraph1 <- renderFlot({
flotChart(airquality) %>%
flotSeries(x=Temp,y=Ozone, label= '', points=list(show=T, symbol='diamond'))
})
},
options = list(height = 350)
)
Given that we have tried to keep the [R] code churn at a minimum, you may find yourself needing to inject snippets of JavaScript to achieve granular control over the various parameters of the Flot JS library (see examples above). Here are some useful references on underlying the options: