<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/creating-interactive-plots-with-r-and-highcharts/"></div></div><div><a data-url="https://www.r-bloggers.com/creating-interactive-plots-with-r-and-highcharts/" data-counturl="https://www.r-bloggers.com/creating-interactive-plots-with-r-and-highcharts/" data-count="horizontal" data-text="Creating Interactive Plots with R and Highcharts" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.rstudio.com/2016/10/19/creating-interactive-plots-with-r-and-highcharts/"> RStudio</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>By Mine Cetinkaya-Rundel</p>
<p>Sometimes great ideas come from trying to solve simple problems. This seems to be especially true for software developers who are willing to put in an unreasonable amount of effort to solve a simple problem to their satisfaction. So the <a target="_blank" rel="nofollow" href="http://www.highcharts.com/about">story</a> goes that Torstein Hønsi, the founder and Chief Product Officer of <a target="_blank" rel="nofollow" href="http://www.highcharts.com/">Highcharts</a>. was looking for a simple charting tool for updating his homepage with snow depth measurements from Vikjafjellet, the local mountain where his family keeps a cabin. Frustrated with the common flash plug-ins, and other proprietary solutions available at the time, he decided to build a standards-based solution of his own and then, of course, share it.</p>
<p>In this post, I’ll use <a target="_blank" rel="nofollow" href="https://github.com/jbkunst">Joshua Kunst’s</a> <a target="_blank" rel="nofollow" href="https://mran.revolutionanalytics.com/package/highcharter/">highcharter package</a>, a wrapper for the Highcharts javascript library, along with <a target="_blank" rel="nofollow" href="http://shiny.rstudio.com/">Shiny</a> to create some pretty slick plots.</p>
<p>Please note that all products in this library are free for non-commercial use. For use in commercial projects and websites, see <a target="_blank" rel="nofollow" href="https://shop.highsoft.com/">https://shop.highsoft.com/</a>.</p>
<p>The highcharter package enables the creation of Highcharts type plots within R.</p>
<p>There are two main functions in the package:</p>
<ul>
<li><code>highchart()</code>: Creates a Highchart chart object using <a target="_blank" rel="nofollow" href="http://www.htmlwidgets.org/">htmlwidgets</a>. The widget can be rendered on HTML pages generated from R Markdown, Shiny, or other applications.</li>
<li><code>hchart()</code>: Uses <code>highchart()</code> to draw a plot for different R object classes using a convenient single command. Specifically, it can plot data frames, numeric, histogram, character, density, factors, ts, mts, xts, stl, ohlc, acf, forecast, mforecast, ets, igraph, dist, dendrogram, phylo, and survfit classes.</li>
</ul>
<p>Plots are built in the spirit of ggplot2 by layering, although they use the pipe operator (<code>%>%</code>) instead of <code>+</code>.</p>
<p>Other attractive features of the package are:</p>
<ul>
<li>Theming: It is possible to configure your plots with pre-implemented themes like Economist, Financial Times, Google, and FiveThirtyEight among others.</li>
<li>Plugins: Motion, drag points, fontawesome, url-pattern, annotations.</li>
</ul>
<p>We will demonstrate the functionality of this package as well as of Highcharts in general through a series of visualisation examples.</p>
<div>
<h3 data-fontsize="18" data-lineheight="23">Example 1: US births on Friday the 13th</h3>
<p>The inspiration for this visualization is a FiveThirtyEight article titled <a target="_blank" rel="nofollow" href="http://fivethirtyeight.com/features/some-people-are-too-superstitious-to-have-a-baby-on-friday-the-13th/">Some People Are Too Superstitious To Have A Baby On Friday The 13th</a>. FiveThirtyEight generously makes the data used in (some of) their articles available on their <a target="_blank" rel="nofollow" href="https://github.com/fivethirtyeight/data">GitHub repository</a>. The data used in this particular analysis can be found <a target="_blank" rel="nofollow" href="https://github.com/mine-cetinkaya-rundel/highcharts-in-r/tree/master/data">here</a>.</p>
<p>Our goal is to recreate <a target="_blank" rel="nofollow" href="https://i2.wp.com/espnfivethirtyeight.files.wordpress.com/2016/05/bialik-fridaythe13th-2.png?quality=90&strip=all&w=1150&ssl=1">this particular visualization</a>. In order to do so, we need to calculate the differences between the number of births on the 13th and the average of 6th and 20th of each month, and aggregate these values for the days of the week. This is nothing a bit of dplyr and tidyr can’t handle.</p>
<p>Let’s load the necessary packages:</p>
<div>
<pre><code><span>library</span>(highcharter)
<span>library</span>(dplyr)
<span>library</span>(tidyr)</code></pre>
</div>
<p>and the data:</p>
<div>
<pre><code>births &lt;- <span>read.csv</span>(<span>&quot;data/births.csv&quot;</span>)</code></pre>
</div>
<p>Then we’ll calculate the differences in births as described in the article and store the results in a new data frame called <code>diff13</code>:</p>
<div>
<pre><code>diff13 &lt;- births %>%
  <span>filter</span>(date_of_month %in% <span>c</span>(<span>6</span>, <span>13</span>, <span>20</span>)) %>%
  <span>mutate</span>(<span>day =</span> <span>ifelse</span>(date_of_month == <span>13</span>, <span>&quot;thirteen&quot;</span>, <span>&quot;not_thirteen&quot;</span>)) %>%
  <span>group_by</span>(day_of_week, day) %>%
  <span>summarise</span>(<span>mean_births =</span> <span>mean</span>(births)) %>%
  <span>arrange</span>(day_of_week) %>%
  <span>spread</span>(day, mean_births) %>%
  <span>mutate</span>(<span>diff_ppt =</span> ((thirteen - not_thirteen) / not_thirteen) * <span>100</span>)</code></pre>
</div>
<p>which looks like:</p>
<pre><code>## Source: local data frame [7 x 4]
## Groups: day_of_week [7]
## 
##   day_of_week not_thirteen  thirteen   diff_ppt
##         &lt;int>        &lt;dbl>     &lt;dbl>      &lt;dbl>
## 1           1    11658.071 11431.429 -1.9440853
## 2           2    12900.417 12629.972 -2.0964008
## 3           3    12793.886 12424.886 -2.8841902
## 4           4    12735.145 12310.132 -3.3373249
## 5           5    12545.100 11744.400 -6.3825717
## 6           6     8650.625  8592.583 -0.6709534
## 7           7     7634.500  7557.676 -1.0062784</code></pre>
<p>Note that the calculated percentage point differences (<code>diff_ppt</code>) may not match the ones in the visualization in the FiveThirtyEight article. There are two reasons for this:</p>
<ol>
<li>Holidays are excluded in the FiveThirtyEight but not in this analysis.</li>
<li>Two data files are provided by FiveThirtyEight, one for years 1994 to 2003 and another for years 2000 to 2014. The numbers of births for the overlapping years (2000 – 2003) are not exactly the same. This app uses the SSA data for these years, however it is unclear which data source FiveThirtyEight used for these years.</li>
</ol>
<p>Let’s start by making a very simple highchart of these data using the <code>hchart()</code> function:</p>
<div>
<pre><code><span>hchart</span>(diff13, <span>&quot;scatter&quot;</span>, <span>x =</span> day_of_week, <span>y =</span> diff_ppt)</code></pre>
</div>
<div data-highcharts-chart="0">
<div>
<p><img sizes="(max-width: 456px) 100vw, 456px" alt="" class="wp-image-142527" src="https://i2.wp.com/www.r-bloggers.com/wp-content/uploads/2016/10/img_5807d88b621fa.png?w=456&ssl=1" data-recalc-dims="1"></p>
</div>
<div>This plot has some attractive features. For example, if you hover over the points you should be able to view the actual values of the plotted data. But, we need to do some customization to make the plot look like the one in the FiveThirtyEight article. We can achieve that using the <code>highchart()</code> function along with some customization functions. Note that we separate the layers with the pipe operator.</div>
</div>
<div>
<pre><code><span>highchart</span>() %>%
  <span>hc_add_series</span>(<span>data =</span> <span>round</span>(diff13$diff_ppt, <span>4</span>), <span>type =</span> <span>&quot;column&quot;</span>,
                <span>name =</span> <span>&quot;Difference, in ppt&quot;</span>,
                <span>color =</span> <span>&quot;#F0A1EA&quot;</span>, <span>showInLegend =</span> <span>FALSE</span>) %>%
  <span>hc_yAxis</span>(<span>title =</span> <span>list</span>(<span>text =</span> <span>&quot;Difference, in ppt&quot;</span>), <span>allowDecimals =</span> <span>FALSE</span>) %>%
  <span>hc_xAxis</span>(<span>categories =</span> <span>c</span>(<span>&quot;Monday&quot;</span>, <span>&quot;Tuesday&quot;</span>, <span>&quot;Wednesday&quot;</span>, <span>&quot;Thursday&quot;</span>, 
                          <span>&quot;Friday&quot;</span>, <span>&quot;Saturday&quot;</span>, <span>&quot;Sunday&quot;</span>),
           <span>tickmarkPlacement =</span> <span>&quot;on&quot;</span>,
           <span>opposite =</span> <span>TRUE</span>) %>%
  <span>hc_title</span>(<span>text =</span> <span>&quot;The Friday the 13th effect&quot;</span>,
           <span>style =</span> <span>list</span>(<span>fontWeight =</span> <span>&quot;bold&quot;</span>)) %>% 
  <span>hc_subtitle</span>(<span>text =</span> <span>&quot;Difference in the share of U.S. births on 13th of each month </span>
<span> from the average of births on the 6th and the 20th,</span>
<span> 1994 - 2004&quot;</span>) %>%
  <span>hc_tooltip</span>(<span>valueDecimals =</span> <span>4</span>,
             <span>pointFormat =</span> <span>&quot;Day: {point.x} &lt;br> Diff: {point.y}&quot;</span>) %>%
  <span>hc_credits</span>(<span>enabled =</span> <span>TRUE</span>, 
             <span>text =</span> <span>&quot;Sources: CDC/NCHS, SOCIAL SECURITY ADMINISTRATION&quot;</span>,
             <span>style =</span> <span>list</span>(<span>fontSize =</span> <span>&quot;10px&quot;</span>)) %>%
  <span>hc_add_theme</span>(<span>hc_theme_538</span>())</code></pre>
</div>
<div data-highcharts-chart="1">
<div>
<p><img sizes="(max-width: 456px) 100vw, 456px" alt="" class="wp-image-142526" src="https://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/10/img_5807d87502457.png?w=456&ssl=1" data-recalc-dims="1"></p>
</div>
</div>
<p>Once again, an attractive feature of this visualization is the hover tooltip. Themes also make it easy to change the look of the plot (in this case using <code>hc_theme_538()</code> gets us very close to the original visualization). Additionally, we are able to easily change labels (e.g., names of days) without having to make changes in the original data.</p>
</div>
<div>
<h3 data-fontsize="18" data-lineheight="23">Example 2: US births on Friday the 13th, an interactive look</h3>
<p>Since the highcharter package is powered by htmlwidlgets, it is also Shiny compatible! In order to build a highchart within a Shiny app, we use the <code>renderHighchart()</code> function.</p>
<p>We have built an app that extends the visualization we created earlier, allowing for custom selection of years plotted, type of plot, and theme. A screenshot of the app is shown below, and you can view the app and the source code <a target="_blank" rel="nofollow" href="https://gallery.shinyapps.io/highcharter-births/">here</a>.</p>
<p> </p>
</div>
<div>
<h3 data-fontsize="18" data-lineheight="23">Things to Look Out For</h3>
<p>Highcharts’ built-in and customizable hover/tooltip box and zooming functionality are among its most attractive features. However, whether or not these features would be useful for you depends on your use case.</p>
<p>For example, the tooltip is not as useful if you are plotting data with larger sample sizes. Take a look at this plot of arrival vs. departure delays of flights headed to Los Angeles (LAX) in October 2013 from the various New York airports. The overplotting on the lower left of the plot makes the hovering functionality not that useful.</p>
<div>
<pre><code><span>library</span>(nycflights13)
oct_lax_flights &lt;- flights %>%
  <span>filter</span>(month == <span>10</span>, dest ==<span> &quot;LAX&quot;</span>)
<span>hchart</span>(oct_lax_flights, <span>&quot;scatter&quot;</span>, <span>x =</span> dep_delay, <span>y =</span> arr_delay, <span>group =</span> origin)</code></pre>
</div>
<div data-highcharts-chart="2">
<div>
<p><img sizes="(max-width: 456px) 100vw, 456px" alt="" class="wp-image-142525" src="https://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/10/img_5807d833df3e2.png?w=456&ssl=1" data-recalc-dims="1"></p>
</div>
</div>
<p> </p>
<p>However, if we aggregated the data a bit to reduce the number of points plotted, this functionality could once again come in handy. For example, below we group the flights by 15-minute intervals in departure delays, and plot the median arrival delay for these intervals.</p>
<div>
<pre><code>oct_lax_flights_agg &lt;- oct_lax_flights %>%
  <span>mutate</span>(<span>dep_delay_cat =</span> <span>cut</span>(dep_delay, <span>breaks =</span> <span>seq</span>(-<span>15</span>, <span>255</span>, <span>15</span>))) %>%
  <span>group_by</span>(origin, dep_delay_cat) %>%
  <span>summarise</span>(<span>med_arr_delay =</span> <span>median</span>(arr_delay, <span>na.rm =</span> <span>TRUE</span>))
<span>hchart</span>(oct_lax_flights_agg, <span>&quot;line&quot;</span>, <span>x =</span> dep_delay_cat, <span>y =</span> med_arr_delay, <span>group =</span> origin)</code></pre>
</div>
<div data-highcharts-chart="3"></div>
</div>
<div>
<p><img sizes="(max-width: 456px) 100vw, 456px" alt="" class="wp-image-142524" src="https://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/10/img_5807d8059c737.png?w=456&ssl=1" data-recalc-dims="1"></p>
<h3 data-fontsize="18" data-lineheight="23">Summary</h3>
<p>Highcharts provides high quality web graphics with high customizability, and the highcharter package allows R users to take full advantage of them. If you’re interested in finding out more about the functionality of the package, I highly recommend browsing the highcharter package <a target="_blank" rel="nofollow" href="http://jkunst.com/highcharter/">homepage</a>which contains a variety of Highcharts, <a target="_blank" rel="nofollow" href="http://www.highcharts.com/products/highstock">Highstock</a> and <a target="_blank" rel="nofollow" href="http://www.highcharts.com/products/highmaps">Highmaps</a> plots along with sample code to reproduce them. Additionally, the <a target="_blank" rel="nofollow" href="http://api.highcharts.com/highcharts">Highcharts Options Reference page</a> is immensely useful for finding the specific syntax for customization options.</p>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/creating-interactive-plots-with-r-and-highcharts/"></div></div><div><a data-url="https://www.r-bloggers.com/creating-interactive-plots-with-r-and-highcharts/" data-counturl="https://www.r-bloggers.com/creating-interactive-plots-with-r-and-highcharts/" data-count="vertical" data-text="Creating Interactive Plots with R and Highcharts" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.rstudio.com/2016/10/19/creating-interactive-plots-with-r-and-highcharts/"> RStudio</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/IRHH7ilfFwM"></a></div>