<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/using-heatmap-coloring-on-a-density-plot-using-r-to-visualize-distributions/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.displayr.com/using-heatmap-coloring-density-plot-using-r-visualize-distributions/?utm_medium=Feed&utm_source=Syndication"> R – Displayr</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><img sizes="(max-width: 780px) 100vw, 780px" src="https://i1.wp.com/www.displayr.com/wp-content/uploads/2017/11/r.output.13.png?w=450&ssl=1" alt="" class="wp-image-4074" data-recalc-dims="1"></p>
<p>Lots of different visualizations have been proposed for understanding distributions. In this post, I am going show how to create my current favorite, which is a density plot using <em>heatmap shading</em>. I find them particularly useful for showing duration data.</p>
<h2>Example: time to purchase</h2>
<p>The table below shows the number of days it took 200 people to purchase a product, after their first trial of the product. The average time taken is 131 days and the median is 54 days. The rest of the post looks at a number of different ways of visualizing this data, finishing with the <em>heated density plot</em>.</p>
<p><iframe src="https://embedded.azureedge.net/75668/244405/2c936008-db25-4bb2-9efa-9bab3d288cf1.html?v=29692-7c5e1a8cf9-505903879" width="354.942" height="436"></iframe></p>
<h2>Density plot</h2>
<p>One of the classic ways of plotting this type of data is as a <em>density plot. </em>The standard R version is shown below. I have set the default <span>from</span> argument to better display this data, as otherwise density plots tend to show negative values even when all the data contains no negative values.</p>
<pre> 
plot(density(days, from = 0),
             main = &quot;Density plot&quot;,
             xlab =  &quot;Number of days since trial started&quot;)
</pre>
<p><iframe width="450" src="https://embedded.azureedge.net/75668/244405/226d9e92-ffb1-438f-85a8-f89b751626fb.html?v=29692-7c5e1a8cf9-887532762"></iframe></p>
<p>This plot clearly shows that purchases occur at relatively close to 0 days since the trial started. But, unless you use a ruler, there is no way to work out precisely where the peak occurs. Is it at 20 days or 50 days? The values shown on the <em>y-</em>axis have no obvious meaning (unless you read the technical documentation, and even then they are not numbers that can be explained in a useful way to non-technical people).</p>
<p>We can make this easier to read by only plotting the data for the first 180 days (<span>to = 180</span>), and changing the bandwidth used in estimating the density (<span>adjust = 0.2</span>) to make the plot less smooth. We can now see that the peak is around 30. While the plot does a good job at describing the shape of the data, it does not allow us to draw conclusions regarding the cumulative proportion of people to purchase by a specific time. For example, what proportion of people buy in the first 100 days? We need a different plot.</p>
<pre> 
plot(density(days, from = 0, to = 180, adjust = 0.2),
             main = &quot;Density plot - Up to 180 days (86% of data)&quot;,
             xlab =  &quot;Number of days since trial started&quot;)
</pre>
<p><iframe width="450" src="https://embedded.azureedge.net/75668/244405/ec6c6b6f-c0b4-4f5f-b676-94591817a98f.html?v=29692-7c5e1a8cf9574516277"></iframe></p>
<h2>Survival curve</h2>
<p><em>Survival curves</em> have been invented for this type of data. An example is shown below. In this case, the survival curve shows the proportion of people who have yet to purchase at each point in time. The relatively sharp drop in the <em>survival function </em>at 30 is the same pattern that was revealed by the peak in the density plot. We can see also see that at about 100 days, around 26% or so of people have “survived” (i.e., not purchased). The plot also reveals that around 14% of customers have not purchased during the time interval shown (as this is where the line crosses the right-side of the plot). To my mind the survival plot is more informative than the density plot. But, it is also harder work. It is hard to see most non-technical audiences finding all the key patterns in this plot without guidance.</p>
<pre> 
library(survival)
surv.days = Surv(days)
surv.fit = survfit(surv.days~1)
plot(surv.fit, main = &quot;Kaplan-Meier estimate with 95% confidence bounds (86% of data)&quot;,
     xlab = &quot;Days since trial started&quot;,
     xlim = c(0, 180),
     ylab = &quot;Survival function&quot;)
grid(20, 10, lwd = 2) 
</pre>
<p><iframe width="450" src="https://embedded.azureedge.net/75668/244405/5a85927e-0947-4528-afa8-10d401b18ffb.html?v=29692-7c5e1a8cf9-72232684"></iframe></p>
<h2>Heated density plot</h2>
<p>I call the visualization below a <em>heated density plot. </em>No doubt somebody invented this before we did, so please tell me if there is a more appropriate name. It is identical to the density plot from earlier in this post, except that:</p>
<ul>
<li>The heatmap coloring shows the cumulative proportion to purchase, ranging from red (0%), to yellow (50%, the median), to blue (100%). Thus, we can now see that the median is at about 55, which could not be ascertained from the earlier density plots.</li>
<li>If you hover your mouse pointer (if you have one) over the plot, it will show you the cumulative percentage of people to purchase. We can readily see that the peak occurs near 30 days. Similarly, we can see that 93% of people purchased within 500 days.</li>
</ul>
<pre> 
HeatedDensityPlot(days, from = 0,
                  title = &quot;Heated density plot&quot;, 
                  x.title = &quot;Number of days since trial started&quot;,
                  legend.title = &quot;% of buyers&quot;)
</pre>
<p><iframe width="450" src="https://embedded.azureedge.net/75668/244405/f18fa8b4-5bd6-4230-841b-807d52491e6b.html?v=29692-7c5e1a8cf9303726089"></iframe></p>
<p>Below I show the plot limited to the first 180 days with the bandwidth adjusted as in the earlier density plot. The use of the legend on the right allows the viewer to readily see that only a little over 85% of people have purchased.</p>
<pre> 
HeatedDensityPlot(days, from = 0, to = 180, adjust = 0.2,
                  title = &quot;Heated density plot - Up to 180 days (86% of data)&quot;, 
                  x.title = &quot;Number of days since trial started&quot;,
                  legend.title = &quot;% of buyers&quot;)
</pre>
<p><iframe width="450" src="https://embedded.azureedge.net/75668/244405/6e89d483-a884-4cd0-bc80-5731688ef00b.html?v=29692-7c5e1a8cf9-140122620"></iframe></p>
<h2>Bonus: they are awesome for discrete data</h2>
<p>The visualization below shows randomly-generated data where I have generated whole numbers in the range of 0 through 12 (i.e., one 0; six 1s, seven 2s, etc). In all the previous heated density plots the color transition was relatively smooth. In the visualization below, the discrete nature of the data has been emphasized by the clear vertical lines between each color. This is not a feature that can be seen on either a traditional density plot or histogram with small sample sizes.</p>
<pre> 
set.seed(12230)
x = rpois(100, 5)
HeatedDensityPlot(x, from = 0, 
                  title = &quot;Poisson(5), n = 100&quot;, 
                  x.title = &quot;x&quot;)
</pre>
<p><iframe width="450" src="https://embedded.azureedge.net/75668/244405/c27f8b69-5b4a-4309-a922-a67e003ac666.html?v=29692-7c5e1a8cf9-1566922027"></iframe></p>
<h2>Conclusion</h2>
<p>The <em>heated density plot </em>is, to my mind, a straightforward improvement on traditional density plots. It shows additional information about the cumulative values of the distribution and reveals when the data is discrete. However, the function we have written is still a bit rough around the edges. For example, sometimes a faint line appears at the top of the plot, and a whole host of warnings appear in R when the plot is created. If you can improve on this, please tell us how!</p>
<h2>The code</h2>
<p>The R function used to create the plot is shown below. If you run this code you will get a plot of a normal distribution. If you want to reproduce my exact examples, please <a rel="nofollow" href="https://app.displayr.com/Try/Heated%20Density" target="_blank">click here</a> to sign into Displayr and access the document that contains all my code and charts. This document contains further additional examples of the use of this plot. To see the code, just click on one of the charts in the document, and the code should be shown on the right in <strong><span>Properties</span> > R CODE</strong>.</p>
<pre> 
HeatedDensityPlot &lt;- function(x,
                              title = &quot;&quot;,
                              x.title = &quot;x&quot;,
                              colors = c('#d7191c','#fdae61','#ffffbf','#abdda4','#2b83ba'),
                              show.legend = TRUE, 
                              legend.title = &quot;Cumulative %&quot;, 
                              n = 512, # Number of unique values of x in the heatmap/density estimation
                              n.breaks = 5, # Number of values of x to show on the x-axis. Final number may differ.
                              ...)
{
    # Checking inputs.
    n.obs &lt;- length(x)
    if (any(nas &lt;- is.na(x))) {
        warning(sum(nas), &quot; observations with missing values have been removed.&quot;)
        x &lt;- x[!nas]
        n.obs &lt;- length(x)
    }
    if (n.obs &lt; 4)
        stop(n.obs, &quot; is too few observations for a valid density plot. See Silverman (1986) Density Estimation for Statistics and Data Analysis.&quot;)
    # Computing densities
    dens &lt;- density(x, ...)
    y.max &lt;- max(dens$y) * 1.1 # To ensure top of plot isn't too close to title
    x.to.plot.true &lt;- x.to.plot &lt;- dens$x
    y.seq &lt;- c(0, y.max/2, y.max)
    y.to.plot &lt;- dens$y
    range.x = range(x)
    cum.dens &lt;- ecdf(x)(x.to.plot)# * 100
    #Due to plotly blug that misaligns heatmap with ensuing white line,
    #putting blanks at beginnig of data.
    n.blanks &lt;- 10
    cum.dens &lt;- c(rep(NA, n.blanks), cum.dens)
    diff &lt;- x.to.plot[1] - x.to.plot[2]
    blanks &lt;- diff * (n.blanks:1) + x.to.plot[1]
    x.to.plot &lt;- c(blanks, x.to.plot)
    y.to.plot &lt;- c(rep(0, n.blanks), y.to.plot)
    # Creating the matrix of heatmap values
    cum.perc &lt;- cum.dens * 100
    z.mat &lt;- matrix(cum.perc, byrow = TRUE, nrow = 3, ncol = n + n.blanks,
                    dimnames = list(y = y.seq, x = x.to.plot))
    # Specifying the colors
    col.fun &lt;- scales::col_numeric(colors, domain = 0:1, na.color = &quot;white&quot;)#range.x)
    x.as.colors &lt;- col.fun(cum.dens)
    z.to.plot.scaled &lt;- scales::rescale(cum.perc)
    color.lookup &lt;- setNames(data.frame(z.to.plot.scaled, x.as.colors), NULL)
    # Creating the base heatmap.
    require(plotly)
    p &lt;- plot_ly(z = z.mat,
                 xsrc = x.to.plot,
                 ysrc = y.seq,
                 type = &quot;heatmap&quot;,
                 colorscale = color.lookup,
                 cauto = FALSE,
                 hoverinfo = &quot;none&quot;,
                  colorbar = list(title = legend.title),
                 showscale = show.legend)
    # Placing white on top of the bits of the heatmap to hide
    p &lt;- add_trace(p,
                   x = c(1:(n + n.blanks), (n + n.blanks):1),
                   y = c(y.to.plot, rep(y.max * 1.10, n + n.blanks)),
                   fill = &quot;tonexty&quot;,
                   hoverinfo = &quot;none&quot;,
                   showlegend = FALSE,
                   type = &quot;scatter&quot;,
                   mode = &quot;line&quot;,
                   showscale = FALSE, 
                   line = list(color = &quot;white&quot;, width = 0),
                   fillcolor = &quot;white&quot;)
    # Adding the tooltips
    p &lt;- add_trace(p,
                   x = 1:(n + n.blanks),
                   y = y.to.plot,
                   name = &quot;&quot;,
                   hoverinfo = &quot;text&quot;,
                   text = sprintf(paste0(x.title,&quot;: %.0f %% &lt; %.1f&quot;), cum.perc, x.to.plot),
                   type = &quot;scatter&quot;,
                   mode = &quot;lines&quot;,
                   line = list(color = &quot;white&quot;, width = 0),
                   showlegend=FALSE, 
                   showscale=FALSE)
    p &lt;- plotly::config(p, displayModeBar = FALSE)
    # Formatting the x axis
    x.text &lt;- pretty(x.to.plot, n = n.breaks)
    x.tick &lt;- 1 + (x.text - x.to.plot[1]) / (x.to.plot[n + n.blanks] - x.to.plot[1]) * (n + n.blanks - 1)
    p &lt;- layout(p, title = title,
                xaxis = list(title = x.title, tickmode = &quot;array&quot;, tickvals = x.tick, ticktext = x.text),
                yaxis = list(title = &quot;&quot;, showline = FALSE, ticks = &quot;&quot;, showticklabels = FALSE, range= c(0, y.max)),
                margin = list(t = 30, l = 5, b = 50, r = 5))
    p
}
</pre>
<h2>Acknowledgements</h2>
<p>My colleague Carmen wrote most of the code. It is written using the wonderful <span>plotly</span> package.</p>
	<p>
<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.displayr.com/using-heatmap-coloring-density-plot-using-r-visualize-distributions/?utm_medium=Feed&utm_source=Syndication"> R – Displayr</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 rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/nZjz6h0l3bo" height="1"></a></div>