<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/a-quick-introduction-to-using-color-in-density-plots/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://sharpsightlabs.com/blog/quick-intro-color-density-plot/"> r-bloggers – SHARP SIGHT LABS</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Right now, many people are pursuing data science because they want to learn artificial intelligence and machine learning. And for good reason. <a href="https://www.r-bloggers.com/a-quick-introduction-to-using-color-in-density-plots/sharpsightlabs.com/blog/machine-learning-google-rethink/">Machine learning is white hot</a> right now, and it will probably <a href="http://sharpsightlabs.com/blog/second-machine-age-welcome/">reshape almost every sector of the world economy</a>.</p>
<p>Having said that, if you want to be a great machine learning expert, and a great data scientist in general, you need to master data visualization too. </p>
<p>This is because <a href="https://www.r-bloggers.com/a-quick-introduction-to-using-color-in-density-plots/sharpsightlabs.com/blog/machine-learning-prerequisite-isnt-math/">data visualization is a critical prerequisite</a> for advanced topics (like machine learning), and also because visualization is very useful for getting things done in its own right.</p>
<p>So let’s talk a little more about data visualization. As you begin learning data visualization in R, you should master the basics: the how to use ggplot2, <a href="http://sharpsightlabs.com/blog/r-package-think-about-visualization/">how to think about data visualization</a>, how to make basic plots (like the <a href="http://sharpsightlabs.com/blog/r-bar-chart-basic/">bar chart</a>, <a href="http://sharpsightlabs.com/blog/line-chart-ggplot2-amzn/">line chart</a>, <a href="http://sharpsightlabs.com/blog/histogram-in-r-basic/">histogram</a>, and <a href="http://sharpsightlabs.com/blog/how-to-create-a-scatterplot-in-r/">scatterplot</a>).</p>
<p>And I really mean that <a href="http://sharpsightlabs.com/blog/master-r-obsolete/">you need to master these basics</a>. To be a great data scientist, you need to be “fluent” in these basics. You should be able to write the code for basic charts and plots <a href="http://sharpsightlabs.com/blog/data-learning-vs-remembering/">without even thinking about it</a>. If you can’t, you should go back and practice them. <a href="http://sharpsightlabs.com/blog/stop-trying-jump-sexy-stuff/">Don’t get shiny object syndrome</a> and try to move on to advanced topics before you do. Show some discipline. Master the foundations.</p>
<p>After you <em>do</em> master the foundations though, you’ll need to learn some intermediate tools.</p>
<p>One such thing that you’ll need to learn is how to work with color. Specifically, you’ll need to learn how to manipulate the “fill” color of things like density plots (as well as <a href="http://sharpsightlabs.com/blog/heatmap-ggplot2-simple/">heatmaps</a>).</p>
<p>With that in mind, let’s take a look at using color in density plots. </p>
<p>As always, we’re going to use the meta-learning strategy of learning the tools with basic cases. Essentially, we’ll learn and practice how to modify the  aesthetic for very simple plots. Later, once you get the hang of it, you can move on to more advanced applications.</p>
<p>As always, first we will load the packages we will need.</p>
<pre class="wp-code-highlight">

#--------------
# LOAD PACKAGES
#--------------

library(tidyverse)
library(viridis)
library(RColorBrewer)

</pre>
<p>Next, we will set a “seed” that will make the dataset exactly reproducible when we create our data. Without this, running  and  would produce data that is similar, but not exactly the same as the data you see here. To be clear, it won’t make too much difference for the purposes of this blog post, but it’s a best practice when you want to show reproducible results, so we will do this anyway.</p>
<pre class="wp-code-highlight">
#---------
# SET SEED
#---------
set.seed(19031025)

</pre>
<p>Now, we will create our data frame.</p>
<p>We will use  to create 20,000 uniformly distributed values for our x variable, and  to create 20,000 random normal values for our y variables. We’re also using the  function to ultimately create a / out of these two new variables.</p>
<pre class="wp-code-highlight">
#------------------
# CREATE DATA FRAME
#------------------
df.data &lt;- tibble(x = runif(20000)
                  ,y = rnorm(20000)
             )

</pre>
<p>Now that we have a dataset created, let’s create a simple plot of the data. Ultimately, we will be working with density plots, but it will be useful to first <a href="http://sharpsightlabs.com/blog/how-to-create-a-scatterplot-in-r/">plot the data points as a simple scatter plot</a>.</p>
<p>Here, we’re using the typical  syntax: we’re specifying the data frame inside of  and specifying our variable mappings inside of .</p>
<pre class="wp-code-highlight">
#--------------------
# CREATE SCATTER PLOT
#--------------------

ggplot(df.data, aes(x = x, y = y)) +
  geom_point()

</pre>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i2.wp.com/sharpsightlabs.com/wp-content/uploads/2017/11/rnorm_scatterplot_OVERPLOTTED-600x502.png?w=450" alt="" class="wp-image-3181" data-recalc-dims="1"><br>
</a></p>
<p>Ok. We can at least see the data points and the general structure of the data (i.e., the horizontal band).</p>
<p>Having said that, these data are very heavily overplotted. There are a few ways to mitigate this overplotting (e.g., manipulating the alpha aesthetic), but a great way is to create a density plot.</p>
<p>To create the density plot, we’re using . I won’t explain this in detail here, but essentially in this application,  calculates the density of observations in each region of the plot, and then fills in that region with a color that corresponds to the density.</p>
<pre class="wp-code-highlight">
#------------------------------
# DENSITY PLOT, w/ DEFAULT FILL
#------------------------------

ggplot(df.data, aes(x = x, y = y)) +
  stat_density2d(aes(fill = ..density..), geom = 'tile', contour = F)

</pre>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i0.wp.com/sharpsightlabs.com/wp-content/uploads/2017/11/rnorm_band_default-600x503.png?w=450" alt="" class="wp-image-3182" data-recalc-dims="1"><br>
</a></p>
<p>This isn’t bad. It gives us a sense of the density of the data (you can see the thick band across the middle). However, there are two issues. </p>
<p>First, the differences in density are not completely obvious, because of the color scale. The default light blue/dark blue color scheme doesn’t illuminate the differences in data density.</p>
<p>Second, this is just not very aesthetically appealing. It just doesn’t look that good.</p>
<p>To fix these issues, let’s modify the color scheme. I’ll show you a few options. Some will work better than others, and after you see these, I’ll encourage you to experiment with other color palettes.</p>
<p>Let’s first take a look at the color palette options.</p>
<p>You can examine a large number of ready-made color palettes from the  package by using .</p>
<pre class="wp-code-highlight">
#-----------------------
# DISPLAY COLOR PALETTES
#-----------------------

display.brewer.all()

</pre>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i2.wp.com/sharpsightlabs.com/wp-content/uploads/2017/11/RColorBrewer_palettes-600x590.png?w=450" alt="" class="wp-image-3175" data-recalc-dims="1"><br>
</a></p>
<p>As you can see, there are quite a few palettes from . We’ll use a few of these to change the  color of our plot.</p>
<pre class="wp-code-highlight">
#--------------------------------
# FILL WITH COLOR PALETTE: Greens
#--------------------------------

ggplot(df.data, aes(x = x, y = y)) +
  stat_density2d(aes(fill = ..density..), geom = 'tile', contour = F) +
  scale_fill_distiller(palette = 'Greens')

</pre>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i0.wp.com/sharpsightlabs.com/wp-content/uploads/2017/11/rnorm_band_greens-600x480.png?w=450" alt="" class="wp-image-3176" data-recalc-dims="1"><br>
</a></p>
<p>Now let’s use a few more color palettes.</p>
<pre class="wp-code-highlight">
#------------------------------------------------------
# FILL WITH COLOR PALETTE: Reds, Greys, Red/Yellow/Blue
#------------------------------------------------------

ggplot(df.data, aes(x = x, y = y)) +
  stat_density2d(aes(fill = ..density..), geom = 'tile', contour = F) +
  scale_fill_distiller(palette = 'Reds')

</pre>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i0.wp.com/sharpsightlabs.com/wp-content/uploads/2017/11/rnorm_band_reds-600x479.png?w=450" alt="" class="wp-image-3177" data-recalc-dims="1"><br>
</a></p>
<p>… grey</p>
<pre class="wp-code-highlight">
ggplot(df.data, aes(x = x, y = y)) +
  stat_density2d(aes(fill = ..density..), geom = 'tile', contour = F) +
  scale_fill_distiller(palette = 'Greys')


</pre>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i0.wp.com/sharpsightlabs.com/wp-content/uploads/2017/11/rnorm_band_greys-600x478.png?w=450" alt="" class="wp-image-3178" data-recalc-dims="1"><br>
</a></p>
<p>… and a scale from red, to yellow, to blue.</p>
<pre class="wp-code-highlight">
ggplot(df.data, aes(x = x, y = y)) +
  stat_density2d(aes(fill = ..density..), geom = 'tile', contour = F) +
  scale_fill_distiller(palette = 'RdYlBu')

</pre>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i0.wp.com/sharpsightlabs.com/wp-content/uploads/2017/11/rnorm_band_RdYlBu-600x482.png?w=450" alt="" class="wp-image-3179" data-recalc-dims="1"><br>
</a></p>
<p>These aren’t bad. </p>
<p>I think they work a little better than the default color scheme, but I think we can do better, so let’s try one more.</p>
<p>The following plot uses a custom color palette from the  package. </p>
<pre class="wp-code-highlight">
#---------------------------------
# FILL WITH COLOR PALETTE: Viridis
#---------------------------------

ggplot(df.data, aes(x = x, y = y)) +
  stat_density2d(aes(fill = ..density..), geom = 'tile', contour = F) +
  scale_fill_viridis()

</pre>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i0.wp.com/sharpsightlabs.com/wp-content/uploads/2017/11/rnorm_band_viridis_v2-600x480.png?w=450" alt="" class="wp-image-3180" data-recalc-dims="1"><br>
</a></p>
<p>I should have called this blog post “ggplot for people who love Mark Rothko.”</p>
<p>Ok, the viridis color palette (and a related set of palettes in the  package) is probably my favorite option. Not only do I think this color palette is one of the most aesthetically attractive, it’s also more functional. As noted in the documentation for the package, the viridis color palette is “designed in such a way that it will analytically be perfectly perceptually-uniform … It is also designed to be perceived by readers with the most common form of color blindness.”</p>
<h2>Master these techniques with simple cases</h2>
<p>Admittedly, when you move on to more complex datasets later, it will take a bit of finesse to properly apply these color palettes.</p>
<p>But as I noted earlier, when you’re trying to master  (or any programming language), you should first master the syntax and techniques on basic cases, and then <a href="http://sharpsightlabs.com/blog/map-unemployment-nov-2016/">increase the complexity</a> as you attain basic competence.</p>
<p>With that in mind, if you want to master these color and fill techniques, learn and practice these tools with simple cases like the ones shown here, and you can attempt more advanced applications later.</p>
<h1>Sign up now, and discover how to rapidly master data science</h1>
<p>To master data visualization and data science, you need to master the essential tools.</p>
<p>Moreover, to make rapid progress, you need to know what to learn, what <em>not</em> to learn, and you need to know <em>how to practice</em> what you learn.</p>
<p>Sharp Sight is dedicated to teaching you how to master the tools of data science as quickly as possible.</p>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank">Sign up now for our email list</a>, and you’ll receive regular tutorials and lessons. </p>
<p>You’ll learn:</p>
<ul>
<li>How to do data visualization in R</li>
<li>How to practice data science</li>
<li>How to apply data visualization to more advanced topics (like machine learning)</li>
<li>… and more </li>
</ul>
<p>If you <a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank">sign up for our email list <em>right now</em></a>, you’ll also get access to our “Data Science Crash Course” <u>for free</u>.</p>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank">
<p><strong>SIGN UP NOW</strong></p>
<p></p></a>
<p>The post <a rel="nofollow" href="http://sharpsightlabs.com/blog/quick-intro-color-density-plot/" target="_blank">A quick introduction to using color in density plots</a> appeared first on <a rel="nofollow" href="http://sharpsightlabs.com/" target="_blank">SHARP SIGHT LABS</a>.</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="http://sharpsightlabs.com/blog/quick-intro-color-density-plot/"> r-bloggers – SHARP SIGHT LABS</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/aVgvDgkTnn4" height="1"></a></div>