<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Rsquared Academy Blog</title>
<link>https://blog.rsquaredacademy.com/data-visualization/</link>
<atom:link href="https://blog.rsquaredacademy.com/data-visualization/index.xml" rel="self" type="application/rss+xml"/>
<description>ggplot2 end to end — geoms, aesthetics, themes, and the 20-part series.</description>
<generator>quarto-1.10.18</generator>
<lastBuildDate>Mon, 07 May 2018 00:00:00 GMT</lastBuildDate>
<item>
  <title>ggplot2: Themes</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/themes/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-05-07-ggplot2-themes.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<hr>
<p>
This is the last post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt to combine multiple plots. In this post, we will learn to modify the appearance of all non data components of the plot such as:
</p>
<ul>
<li>
axis
</li>
<li>
legend
</li>
<li>
panel
</li>
<li>
plot area
</li>
<li>
background
</li>
<li>
margin
</li>
<li>
facets
</li>
</ul>
<p>
<br>
</p>
</section> ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/themes/</guid>
  <pubDate>Mon, 07 May 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_themes.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Faceting</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/faceting/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-04-25-ggplot2-facets-combine-multiple-plots.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<hr>
<p>
This is the 19th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt to modify the title, label and bar of a legend. In this post, we will learn about faceting i.e.&nbsp;combining plots.
</p>
<p>
<br>
</p>
</section> ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/faceting/</guid>
  <pubDate>Wed, 25 Apr 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_facet.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Legend - Part 6</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/legend-part-6/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-04-13-legend-part-6.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<hr>
<p>
This is the 18th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt how to modify the legend of plot when <code>alpha</code> is mapped to a categorical variable. In this post, we will learn to modify legend
</p>
<ul>
<li>
title
</li>
<li>
label
</li>
<li>
and bar
</li>
</ul>
<p>
So far, we have learnt to modify the components of a legend using <code>scale_*</code> family of functions. Now, we will use the <code>guide</code> argument and supply it values using the <code>guide_legend()</code> function.
</p>
<p>
<br>
</p>
<p>
<br>
</p>
</section> ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/legend-part-6/</guid>
  <pubDate>Fri, 13 Apr 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_leg_part_1.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Legend - Part 5</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/legend-part-5/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-04-01-legend-part-5.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<hr>
<p>
This is the 17th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt how to modify the legend of plot when <code>size</code> is mapped to continuous variable. In this post, we will learn to modify the following using <code>scale_alpha_continuous()</code> when <code>alpha</code> or transparency is mapped to variables:
</p>
<ul>
<li>
title
</li>
<li>
breaks
</li>
<li>
limits
</li>
<li>
range
</li>
<li>
labels
</li>
<li>
values
</li>
</ul>
<p>
<br>
</p>
</section> ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/legend-part-5/</guid>
  <pubDate>Sun, 01 Apr 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_leg_part_1.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Legend - Part 4</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/legend-part-4/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-03-20-legend-part-4.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<hr>
<p>
This is the 16th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt how to modify the legend of plot when <code>shape</code> is mapped to categorical variables. In this post, we will learn to modify the following using <code>scale_size_continuous</code> when <code>size</code> aesthetic is mapped to variables:
</p>
<ul>
<li>
title
</li>
<li>
breaks
</li>
<li>
limits
</li>
<li>
range
</li>
<li>
labels
</li>
<li>
values
</li>
</ul>
<p>
<br>
</p>
</section> ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/legend-part-4/</guid>
  <pubDate>Tue, 20 Mar 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_leg_part_1.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Legend - Part 3</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/legend-part-3/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-03-08-legend-part-3.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the 15th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt how to modify the legend of plots when aesthetics are mapped to variables..In this post, we will learn to modify the following using <code>scale_shape_manual</code> when <code>shape</code> is mapped to categorical variables:
</p>
<ul>
<li>
title
</li>
<li>
breaks
</li>
<li>
limits
</li>
<li>
labels
</li>
<li>
values
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<hr>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/446c78bd5cb4a6cb546bd440bc357140">here</a>.
</p>
<p>
<br>
</p>
</section> ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/legend-part-3/</guid>
  <pubDate>Thu, 08 Mar 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_leg_part_1.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Legend - Part 2</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/legend-part-2/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-02-24-guides-legends-part-2.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<hr>
<p>
This is the 14th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt how to modify the legend of plots when aesthetics are mapped to variables. In this post, we will continue to explore different ways to modify/customize the legend of plots.
</p>
<p>
Specifically, we will learn to modify the following using <code>scale_fill_manual()</code> when <code>fill</code> is mapped to categorical variables:
</p>
<ul>
<li>
title
</li>
<li>
breaks
</li>
<li>
limits
</li>
<li>
labels
</li>
<li>
values
</li>
</ul>
<p>
<br>
</p>
</section> ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/legend-part-2/</guid>
  <pubDate>Sat, 24 Feb 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_leg_part_2.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Legend - Part 1</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/legend-part-1/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-02-12-ggplot2-guides-legends.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the 13th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previos post, we learnt how to modify the axis of plots. In this post, we will focus on modifying the appearance of legend of plots when the aesthetics are mapped to variables. Specifically, we will learn to modify the following when <code>color</code> is mapped to categorical variables:
</p>
<ul>
<li>
title
</li>
<li>
breaks
</li>
<li>
limits
</li>
<li>
labels
</li>
<li>
values
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="https://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="https://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/f099b954fa8f5a84cd8e5a2a031f91db">here</a>.
</p>
<p>
<br>
</p>
</section>
<section id="basic-plot" class="level3">
<h3 class="anchored" data-anchor-id="basic-plot">
Basic Plot
</h3>
<p>
Let us start with a scatter plot examining the relationship between displacement and miles per gallon from the mtcars data set. We will map the color of the points to the <code>cyl</code> variable.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = factor(cyl)))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/legend-part-1/2018-02-12-ggplot2-guides-legends_files/figure-html/leg15-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
As you can see, the legend acts as a guide for the <code>color</code> aesthetic. Now, let us learn to modify the different aspects of the legend.
</p>
<p>
<br>
</p>
</section>
<section id="values" class="level3">
<h3 class="anchored" data-anchor-id="values">
Values
</h3>
<p>
To change the default colors in the legend, use the <code>values</code> argument and supply a character vector of color names. The number of colors specified must be equal to the number of levels in the categorical variable mapped. In the below example, <code>cyl</code> has 3 levels (4, 6, 8) and hence we have specified 3 colors.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = factor(cyl))) +
  scale_color_manual(values = c("red", "blue", "green"))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/legend-part-1/2018-02-12-ggplot2-guides-legends_files/figure-html/leg17-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="title" class="level3">
<h3 class="anchored" data-anchor-id="title">
Title
</h3>
<p>
In the previous example, the title of the legend (<code>factor(cyl)</code>) is not very intuitive. If the user does not know the underlying data, they will not be able to make any sense out of it. Let us change it to <code>Cylinders</code> using the <code>name</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = factor(cyl))) +
  scale_color_manual(name = "Cylinders", 
    values = c("red", "blue", "green"))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/legend-part-1/2018-02-12-ggplot2-guides-legends_files/figure-html/leg16-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
Now, the user will know that the different colors represent number of cylinders in the car.
</p>
<p>
<br>
</p>
</section>
<section id="limits" class="level3">
<h3 class="anchored" data-anchor-id="limits">
Limits
</h3>
<p>
Let us assume that we want to modify the data to be displayed i.e.&nbsp;instead of examining the relationship between mileage and displacement for all cars, we desire to look at only cars with at least 6 cylinders. One way to approach this would be to filter the data using <code>filter</code> from dplyr and then visualize it. Instead, we will use the <code>limits</code> argument and filter the data for visualization.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = factor(cyl))) +
  scale_color_manual(values = c("red", "blue", "green"), limits = c(6, 8))</code></pre>
<pre><code>## Warning: Removed 11 rows containing missing values (geom_point).</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/legend-part-1/2018-02-12-ggplot2-guides-legends_files/figure-html/leg18-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
As you can see above, <code>ggplot2</code> returns a warning message indicating data related to 4 cylinders has been dropped. If you observe the legend, it now represents only 4 and 6 cylinders.
</p>
<p>
<br>
</p>
</section>
<section id="labels" class="level3">
<h3 class="anchored" data-anchor-id="labels">
Labels
</h3>
<p>
The labels in the legend can be modified using the <code>labels</code> argument. Let us change the labels to <code>Four</code>, <code>Six</code> and <code>Eight</code> in the next example. Ensure that the labels are intuitive and easy to interpret for the end user of the plot.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = factor(cyl))) +
  scale_color_manual(values = c("red", "blue", "green"),
    labels = c('Four', 'Six', 'Eight'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/legend-part-1/2018-02-12-ggplot2-guides-legends_files/figure-html/leg19-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="breaks" class="level3">
<h3 class="anchored" data-anchor-id="breaks">
Breaks
</h3>
<p>
When there are large number of levels in the mapped variable, you may not want the labels in the legend to represent all of them. In such cases, we can use the breaks argument and specify the labels to be used. In the below case, we use the <code>breaks</code> argument to ensure that the labels in legend represent two levels (4, 8) of the mapped variable.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = factor(cyl))) +
  scale_color_manual(values = c("red", "blue", "green"),
    breaks = c(4, 8))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/legend-part-1/2018-02-12-ggplot2-guides-legends_files/figure-html/leg20-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="putting-it-all-together" class="level3">
<h3 class="anchored" data-anchor-id="putting-it-all-together">
Putting it all together…
</h3>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = factor(cyl))) +
  scale_color_manual(name = "Cylinders", values = c("red", "blue", "green"),
    labels = c('Four', 'Six', 'Eight'), limits = c(4, 6, 8), breaks = c(4, 6, 8))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/legend-part-1/2018-02-12-ggplot2-guides-legends_files/figure-html/leg21-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to modify the following aspects of legends:
</p>
<ul>
<li>
title
</li>
<li>
breaks
</li>
<li>
limits
</li>
<li>
labels
</li>
<li>
values
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn how to modify legend when <code>fill</code> is mapped to variables.
</p>
<p>
<br>
</p>
</section>



 ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/legend-part-1/</guid>
  <pubDate>Mon, 12 Feb 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_leg_part_1.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Guides - Axes</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/guides-axes/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-01-31-ggplot2-guides-axes.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the twelfth post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt to build histograms. Now that we have learnt to build different plots, let us look at different ways to modify the axis. Along the way, we will also explore the <code>scale_*()</code> family of functions.
</p>
<p>
Modify X and Y axis
</p>
<ul>
<li>
title
</li>
<li>
labels
</li>
<li>
limits
</li>
<li>
breaks
</li>
<li>
position
</li>
</ul>
<p>
In this module, we will learn how to modify the X and Y axis using the following functions:
</p>
<ul>
<li>
Continuous Axis
<ul>
<li>
<code>scale_x_continuous()</code>
</li>
<li>
<code>scale_y_continuous()</code>
</li>
</ul>
</li>
<li>
Discrete Axis
<ul>
<li>
<code>scale_x_discrete()</code>
</li>
<li>
<code>scale_y_discrete()</code>
</li>
</ul>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/096bc745c18a9ba47b99260978189920">here</a>.
</p>
<p>
<br>
</p>
</section>
<section id="continuous-axis" class="level3">
<h3 class="anchored" data-anchor-id="continuous-axis">
Continuous Axis
</h3>
<p>
If the X and Y axis represent continuous data, we can use <code>scale_x_continuous()</code> and <code>scale_y_continuous()</code> to modify the axis. They take the following arguments:
</p>
<ul>
<li>
name
</li>
<li>
limits
</li>
<li>
breaks
</li>
<li>
labels
</li>
<li>
position
</li>
</ul>
<p>
<br>
</p>
<p>
Let us continue with the scatter plot we have used in previous posts.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The <code>name</code> argument is used to modify the X axis label. In the below example, we change the X axis label to <code>‘Displacement’</code>. In previous posts, we have used <code>xlab()</code> to work with the X axis label.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  scale_x_continuous(name = "Displacement")</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
To modify the range, use the <code>limits</code> argument. It takes a vector of length 2 i.e.&nbsp;2 values, the lower and upper limit of the range. It is an alternative for <code>xlim()</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  scale_x_continuous(limits = c(0, 600))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
In the above plot, the ticks on the X axis appear at <code>0</code>, <code>200</code>, <code>400</code> and <code>600</code>. Let us say we want the ticks to appear more closer i.e.&nbsp;the difference between the tick should be reduced by <code>50</code>. The <code>breaks</code> argument will allow us to specify where the ticks appear. It takes a numeric vector equal to the length of the number of ticks.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  scale_x_continuous(breaks = c(150, 300, 450))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide5-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
We can change the tick labels using the <code>labels</code> argument. In the below example, we use words instead of numbers. When adding labels, we need to ensure that the length of the <code>breaks</code> and <code>labels</code> are same.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  scale_x_continuous(breaks = c(150, 300, 450),
    labels = c('One Hundred Fifty', 'Three Hundred', 'Four Hundred Fifity'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The position of the axes can be changed using the <code>position</code> argument. In the below example, we can move the axes to the top of the plot by supplying the value <code>‘top’</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  scale_x_continuous(position = 'top')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="putting-it-all-together.." class="level3">
<h3 class="anchored" data-anchor-id="putting-it-all-together..">
Putting it all together..
</h3>
<pre class="r"><code>ggplot(mtcars) + geom_point(aes(disp, mpg)) +
  scale_x_continuous(name = "Displacement", limits = c(0, 600),
                     breaks = c(0, 150, 300, 450, 600), position = 'top',
                     labels = c('0', '150', '300', '450', '600'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide8-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="y-axis---continuous" class="level3">
<h3 class="anchored" data-anchor-id="y-axis---continuous">
Y Axis - Continuous
</h3>
<pre class="r"><code>ggplot(mtcars) + geom_point(aes(disp, mpg)) +
  scale_y_continuous(name = "Miles Per Gallon", limits = c(0, 45),
                     breaks = c(0, 15, 30, 45), position = 'right',
                     labels = c('0', '15', '30', '45'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide9-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="discrete-axis" class="level3">
<h3 class="anchored" data-anchor-id="discrete-axis">
Discrete Axis
</h3>
<p>
If the X and Y axis represent discrete or categorical data, <code>scale_x_discrete()</code> and <code>scale_y_discrete()</code> can be used to modify them. They take the following arguments:
</p>
<ul>
<li>
name
</li>
<li>
labels
</li>
<li>
breaks
</li>
<li>
position
</li>
</ul>
<p>
The above options serve the same purpose as in the case of continuous scales.
</p>
<p>
<br>
</p>
<section id="axis-label" class="level4">
<h4 class="anchored" data-anchor-id="axis-label">
Axis Label
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_bar(aes(factor(cyl))) +
  scale_x_discrete(name = "Number of Cylinders")</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide11-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="axis-tick-labels" class="level4">
<h4 class="anchored" data-anchor-id="axis-tick-labels">
Axis Tick Labels
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_bar(aes(factor(cyl))) +
  scale_x_discrete(labels = c("4" = "Four", "6" = "Six", "8" = "Eight"))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide12-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="axis-breaks" class="level4">
<h4 class="anchored" data-anchor-id="axis-breaks">
Axis Breaks
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_bar(aes(factor(cyl))) +
  scale_x_discrete(breaks = c("4", "6", "8"))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide13-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="axis-position" class="level4">
<h4 class="anchored" data-anchor-id="axis-position">
Axis Position
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_bar(aes(factor(cyl))) +
  scale_x_discrete(position = 'bottom')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide14-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="putting-it-all-together" class="level4">
<h4 class="anchored" data-anchor-id="putting-it-all-together">
Putting it all together…
</h4>
<pre class="r"><code>ggplot(mtcars) + geom_bar(aes(factor(cyl))) +
  scale_x_discrete(name = "Number of Cylinders",
    labels = c("4" = "Four", "6" = "Six", "8" = "Eight"),
    breaks = c("4", "6", "8"), position = "bottom")</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/guides-axes/2018-01-31-ggplot2-guides-axes_files/figure-html/guide15-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to modify
</p>
<ul>
<li>
title
</li>
<li>
labels
</li>
<li>
limits
</li>
<li>
breaks
</li>
<li>
position
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn to modify the legend when <code>color</code> is mapped to a variable.
</p>
</section>



 ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/guides-axes/</guid>
  <pubDate>Wed, 31 Jan 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_axes_guide.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Histogram</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-histogram/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-01-19-ggplot2-histogram.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the eleventh post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt to build box plots. In this post, we will learn to
</p>
<ul>
<li>
build histogram
</li>
<li>
specify bins
</li>
<li>
modify
<ul>
<li>
color
</li>
<li>
fill
</li>
<li>
alpha
</li>
<li>
bin width
</li>
<li>
line type
</li>
<li>
line size
</li>
</ul>
</li>
<li>
map aesthetics to variables
</li>
</ul>
<p>
A histogram is a plot that can be used to examine the shape and spread of continuous data. It looks very similar to a bar graph and can be used to detect outliers and skewness in data. The histogram graphically shows the following:
</p>
<ul>
<li>
center (location) of the data
</li>
<li>
spread (dispersion) of the data
</li>
<li>
skewness
</li>
<li>
outliers
</li>
<li>
presence of multiple modes
</li>
</ul>
<p>
To construct a histogram, the data is split into intervals called bins. The intervals may or may not be equal sized. For each bin, the number of data points that fall into it are counted (frequency). The Y axis of the histogram represents the frequency and the X axis represents the variable.
</p>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/674bc30cc1539d735bdc4e6210982d1d">here</a>.
</p>
<p>
<br>
</p>
</section>
<section id="data" class="level3">
<h3 class="anchored" data-anchor-id="data">
Data
</h3>
<pre class="r"><code>ecom &lt;- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/web.csv')
ecom</code></pre>
<pre><code>## # A tibble: 1,000 x 11
##       id referrer device bouncers n_visit n_pages duration country purchase
##    &lt;dbl&gt; &lt;chr&gt;    &lt;chr&gt;  &lt;lgl&gt;      &lt;dbl&gt;   &lt;dbl&gt;    &lt;dbl&gt; &lt;chr&gt;   &lt;lgl&gt;   
##  1     1 google   laptop TRUE          10       1      693 Czech ~ FALSE   
##  2     2 yahoo    tablet TRUE           9       1      459 Yemen   FALSE   
##  3     3 direct   laptop TRUE           0       1      996 Brazil  FALSE   
##  4     4 bing     tablet FALSE          3      18      468 China   TRUE    
##  5     5 yahoo    mobile TRUE           9       1      955 Poland  FALSE   
##  6     6 yahoo    laptop FALSE          5       5      135 South ~ FALSE   
##  7     7 yahoo    mobile TRUE          10       1       75 Bangla~ FALSE   
##  8     8 direct   mobile TRUE          10       1      908 Indone~ FALSE   
##  9     9 bing     mobile FALSE          3      19      209 Nether~ FALSE   
## 10    10 google   mobile TRUE           6       1      208 Czech ~ FALSE   
## # ... with 990 more rows, and 2 more variables: order_items &lt;dbl&gt;,
## #   order_value &lt;dbl&gt;</code></pre>
<p>
<br>
</p>
</section>
<section id="data-dictionary" class="level3">
<h3 class="anchored" data-anchor-id="data-dictionary">
Data Dictionary
</h3>
<ul>
<li>
id: row id
</li>
<li>
referrer: referrer website/search engine
</li>
<li>
os: operating system
</li>
<li>
browser: browser
</li>
<li>
device: device used to visit the website
</li>
<li>
n_pages: number of pages visited
</li>
<li>
duration: time spent on the website (in seconds)
</li>
<li>
repeat: frequency of visits
</li>
<li>
country: country of origin
</li>
<li>
purchase: whether visitor purchased
</li>
<li>
order_value: order value of visitor (in dollars)
</li>
</ul>
<p>
<br>
</p>
<section id="histogram" class="level4">
<h4 class="anchored" data-anchor-id="histogram">
Histogram
</h4>
<p>
To create a histogram, we will use <code>geom_histogram()</code> and specify the variable name within <code>aes()</code>. In the below example, we create histogram of the variable <code>n_visit</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit))</code></pre>
<pre><code>## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="specify-bins" class="level4">
<h4 class="anchored" data-anchor-id="specify-bins">
Specify Bins
</h4>
<p>
The default number of bins in ggplot2 is <code>30</code>. You can modify the number of bins using the <code>bins</code> argument. In the below example, we create a histogram with 7 bins.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit), bins = 7)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="aesthetics" class="level4">
<h4 class="anchored" data-anchor-id="aesthetics">
Aesthetics
</h4>
<p>
Now that we know how to create a histogram, let us learn to modify its appearance. We will begin with the background color. Use the <code>fill</code> argument to modify the background color of the histogram. In the below case, we change the color of the histogram to ‘blue’.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit), bins = 7, fill = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
As we have learnt before, the transparency of the background color can be modified using the <code>alpha</code> argument. It can take any value between <code>0</code> and <code>1</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit), bins = 7, fill = 'blue', alpha = 0.3)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist11-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The color of the histogram border can be modified using the <code>color</code> argument. The color can be specified either using its name or the associated hex code.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit), bins = 7, fill = 'white', color = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist8-1.png" width="672" style="display: block; margin: auto;"> <br>
</p>
</section>
<section id="putting-it-all-together" class="level4">
<h4 class="anchored" data-anchor-id="putting-it-all-together">
Putting it all together…
</h4>
<p>
Let us modify the bins, the background and border color of the histogram in the below example.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit), bins = 7, fill = 'blue', color = 'white')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist9-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="bin-width" class="level4">
<h4 class="anchored" data-anchor-id="bin-width">
Bin Width
</h4>
<p>
Another way to control the number of bins in a histogram is by using the <code>binwidth</code> argument. In this case, we specify the width of the bins instead of the number of bins. As you can see, in the below example, we do not use the <code>bins</code> argument when using the <code>binwidth</code> argument. You can use either of them but not both.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit), binwidth = 2, fill = 'blue', color = 'black')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist5-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="line-type" class="level4">
<h4 class="anchored" data-anchor-id="line-type">
Line Type
</h4>
<p>
The line type of the histogram border can be modified using the <code>linetype</code> argument. It can take any integer value between <code>0</code> and <code>6</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit), bins = 5, fill = 'white', 
    color = 'blue', linetype = 3)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="line-size" class="level4">
<h4 class="anchored" data-anchor-id="line-size">
Line Size
</h4>
<p>
Use the <code>size</code> argument to modify the width of the border of the histogram bins. It can take any value greater than <code>0</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit), bins = 5, fill = 'white', 
    color = 'blue', size = 1.25)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist10-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="map-variables" class="level4">
<h4 class="anchored" data-anchor-id="map-variables">
Map Variables
</h4>
<p>
You can map the aesthetics to variables as well. In the below example, we map <code>fill</code> to the device variable. You can try mapping color, linetype and size to variables as well.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(n_visit, fill = device), bins = 7)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-histogram/2018-01-19-ggplot2-histogram_files/figure-html/hist7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to:
</p>
<ul>
<li>
build histogram
</li>
<li>
specify bins
</li>
<li>
modify
<ul>
<li>
color
</li>
<li>
fill
</li>
<li>
alpha
</li>
<li>
bin width
</li>
<li>
line type
</li>
<li>
line size
</li>
</ul>
</li>
<li>
map aesthetics to variables
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn to modify the axes of a plot.
</p>
<p>
<br>
</p>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-histogram/</guid>
  <pubDate>Fri, 19 Jan 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_hist.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Box Plots</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2018-01-07-ggplot2-box-plots.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the 9th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt how to build bar charts. In this post, we will learn to:
</p>
<ul>
<li>
build box plots
</li>
<li>
modify box
<ul>
<li>
color
</li>
<li>
fill
</li>
<li>
alpha
</li>
<li>
line size
</li>
<li>
line type
</li>
</ul>
</li>
<li>
modify outlier
<ul>
<li>
color
</li>
<li>
shape
</li>
<li>
size
</li>
<li>
alpha
</li>
</ul>
</li>
</ul>
<p>
The box plot is a standardized way of displaying the distribution of data. It is useful for detecting outliers and for comparing distributions and shows the shape, central tendancy and variability of the data.
</p>
<p>
<br>
</p>
</section>
<section id="structure" class="level2">
<h2 class="anchored" data-anchor-id="structure">
Structure
</h2>
<ul>
<li>
the body of the boxplot consists of a “box” (hence, the name), which goes from the first quartile (Q1) to the third quartile (Q3)
</li>
<li>
within the box, a vertical line is drawn at the Q2, the median of the data set
</li>
<li>
two horizontal lines, called whiskers, extend from the front and back of the box
</li>
<li>
the front whisker goes from Q1 to the smallest non-outlier in the data set, and the back whisker goes from Q3 to the largest non-outlier
</li>
<li>
if the data set includes one or more outliers, they are plotted separately as points on the chart
</li>
</ul>
<p>
<br>
</p>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/246091b512a6c006e68374e2d24caf7c">here</a>.
</p>
<p>
<br>
</p>
</section>
</section>
<section id="data" class="level2">
<h2 class="anchored" data-anchor-id="data">
Data
</h2>
<p>
We are going to use two different data sets in this post. Both the data sets have the same data but are in different formats.
</p>
<pre class="r"><code>daily_returns &lt;- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/tickers.csv')
daily_returns</code></pre>
<pre><code>## # A tibble: 250 x 5
##       AAPL   AMZN      FB    GOOG    MSFT
##      &lt;dbl&gt;  &lt;dbl&gt;   &lt;dbl&gt;   &lt;dbl&gt;   &lt;dbl&gt;
##  1  1.38    24.2   2.12    22.4    1.12  
##  2  2.83     3.25 -0.860    5.99   0.767 
##  3 -0.0394   9.91  1.45     6.75   0.973 
##  4  0.108    3.76 -0.770  -10.7   -0.285 
##  5  1.64    19.8   4.75     8.66   0.501 
##  6  0.0689   5.33 -0.300   -0.930  0.256 
##  7 -0.561   -5.21 -0.630   -7.28  -0.708 
##  8  0.551    0.25 -0.460    0.690  0.128 
##  9 -0.217  -13.6   0.0300   6.56   0.0786
## 10 -0.108   -4.25  0.460    2.60   0.472 
## # ... with 240 more rows</code></pre>
<p>
<br>
</p>
</section>
<section id="univariate-box-plot" class="level2">
<h2 class="anchored" data-anchor-id="univariate-box-plot">
Univariate Box Plot
</h2>
<p>
If you are not comparing the distribution of continuous data, you can create box plot for a single variable. Unlike <code>plot()</code>, where we could just use 1 input, in ggplot2, we must specify a value for the X axis and it must be categorical data. Since we are not comparing distributions, we will use <code>1</code> as the value for the X axis and wrap it inside <code>factor()</code> to treat it as a categorical variable. In the below example, we examine the distribution of stock returns of Apple.
</p>
<pre class="r"><code>ggplot(daily_returns) +
  geom_boxplot(aes(x = factor(1), y = AAPL))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="data-1" class="level2">
<h2 class="anchored" data-anchor-id="data-1">
Data
</h2>
<p>
For the rest of the post, we will use the below data set. Instead of 5 columns, we have two columns. One for the stock names and another for returns.
</p>
<pre class="r"><code>tidy_returns &lt;- 
  read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/tidy_tickers.csv',
  col_types = list(col_factor(levels = c('AAPL', 'AMZN', 'FB', 'GOOG', 'MSFT')), col_double()))
tidy_returns</code></pre>
<pre><code>## # A tibble: 1,254 x 2
##    stock returns
##    &lt;fct&gt;   &lt;dbl&gt;
##  1 AAPL   1.38  
##  2 AAPL   2.83  
##  3 AAPL  -0.0394
##  4 AAPL   0.108 
##  5 AAPL   1.64  
##  6 AAPL   0.0689
##  7 AAPL  -0.561 
##  8 AAPL   0.551 
##  9 AAPL  -0.217 
## 10 AAPL  -0.108 
## # ... with 1,244 more rows</code></pre>
<p>
<br>
</p>
</section>
<section id="box-plot" class="level2">
<h2 class="anchored" data-anchor-id="box-plot">
Box Plot
</h2>
<p>
With the above data, let us create a box plot where we compate the distribution of stock returns of different companies. We map X axis to the column with stock names and Y axis to the column with stock returns. Note that, the column names are wrapped inside <code>aes()</code>.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
To create a horizontal bar plot, we can use <code>coord_flip()</code> which will flip the coordinate axes.
</p>
</section>
<section id="horizontal-box-plot" class="level2">
<h2 class="anchored" data-anchor-id="horizontal-box-plot">
Horizontal Box Plot
</h2>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns)) +
  coord_flip()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="notch" class="level2">
<h2 class="anchored" data-anchor-id="notch">
Notch
</h2>
<p>
Notches are used to compare medians. You can use the <code>notch</code> argument and set it to <code>TRUE</code>.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns),
    notch = TRUE) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box5-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="jitter" class="level2">
<h2 class="anchored" data-anchor-id="jitter">
Jitter
</h2>
<p>
Just for comparison, let us plot the returns as points on top of the box plot using <code>geom_jitter()</code>. We modify the color of the points using the <code>color</code> argument and the spread using the <code>width</code> argument.
</p>
<pre class="r"><code>ggplot(tidy_returns, aes(x = stock, y = returns)) +
  geom_boxplot() +
  geom_jitter(width = 0.2, color = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="outliers" class="level2">
<h2 class="anchored" data-anchor-id="outliers">
Outliers
</h2>
<p>
To highlight extreme observations, we can modify the appearance of outliers using the following:
</p>
<ul>
<li>
color
</li>
<li>
shape
</li>
<li>
size
</li>
<li>
alpha
</li>
</ul>
<p>
<br>
</p>
<p>
To modify the color of the outliers, use the <code>outlier.color</code> argument. The color can be specified either using its name or the associated hex code.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), outlier.color = 'red')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The shape of the outlier can be modified using the <code>outlier.shape</code> argument. It can take values between <code>0</code> and <code>25</code>.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), outlier.shape = 23) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box9-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The size of the outlier can be modified using the <code>outlier.size</code> argument. It can take any value greater than <code>0</code>.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), outlier.size = 3) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box10-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
You can play around with the transparency of the outlier using the <code>outlier.alpha</code> argument. It can take values between <code>0</code> and <code>1</code>.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), outlier.color = 'blue', outlier.alpha = 0.3) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box11-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="box-aesthetics" class="level2">
<h2 class="anchored" data-anchor-id="box-aesthetics">
Box Aesthetics
</h2>
<p>
The appearance of the box can be controlled using the following:
</p>
<ul>
<li>
color
</li>
<li>
fill
</li>
<li>
alpha
</li>
<li>
line type
</li>
<li>
line width
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="specify-values" class="level2">
<h2 class="anchored" data-anchor-id="specify-values">
Specify Values
</h2>
<p>
The background color of the box can be modified using the <code>fill</code> argument. The color can be specified either using its name or the associated hex code.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), fill = c('blue', 'red', 'green', 'yellow', 'brown')) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box12-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
To modify the transparency of the background color, use the <code>alpha</code> argument. It can take any value between <code>0</code> and <code>1</code>.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), fill = 'blue', alpha = 0.3) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box14-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The color of the border can be modified using the <code>color</code> argument. The color can be specified either using its name or the associated hex code.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), color = c('blue', 'red', 'green', 'yellow', 'brown')) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box15-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The width of the border can be changed using the <code>size</code> argument. It can take any value greater than <code>0</code>.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), size = 1.5) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box17-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
To change the line type of the border, use the <code>linetype</code> argument. It can take any value between <code>0</code> and <code>6</code>.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns), linetype = 2) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box18-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="map-variables" class="level2">
<h2 class="anchored" data-anchor-id="map-variables">
Map Variables
</h2>
<p>
Instead of specifying values, we can map <code>fill</code> and <code>color</code> to variables as well. In the below example, we map <code>fill</code> to the variable stock. It assigns different colors to the different stocks.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns, fill = stock)) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box13-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Let us map <code>color</code> to the variable stock. It will assign different colors to the box borders.
</p>
<pre class="r"><code>ggplot(tidy_returns) +
  geom_boxplot(aes(x = stock, y = returns, color = stock)) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/2018-01-07-ggplot2-box-plots_files/figure-html/box16-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to:
</p>
<ul>
<li>
build box plots
</li>
<li>
modify outlier color, shape, size etc.
</li>
<li>
modify box color
</li>
<li>
modify box line color, size and line type
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn to build histograms.
</p>
<p>
<br>
</p>
</section>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-box-plots/</guid>
  <pubDate>Sun, 07 Jan 2018 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_box.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Bar Plots</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-12-26-ggplot2-bar-plots.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the ninth post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt to build line charts. In this post, we will learn to:
</p>
<ul>
<li>
build
<ul>
<li>
simple bar plot
</li>
<li>
stacked bar plot
</li>
<li>
grouped bar plot
</li>
<li>
proportional bar plot
</li>
</ul>
</li>
<li>
map aesthetics to variables
</li>
<li>
specify values for
<ul>
<li>
bar color
</li>
<li>
bar line color
</li>
<li>
bar line type
</li>
<li>
bar line size
</li>
</ul>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="https://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="https://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/096329693fa1f9313771d4e259cce1ec">here</a>.
</p>
<p>
<br>
</p>
</section>
<section id="data" class="level3">
<h3 class="anchored" data-anchor-id="data">
Data
</h3>
<pre class="r"><code>ecom &lt;- read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/ecom.csv',
  col_types = list(col_factor(levels = c('Desktop', 'Mobile', 'Tablet')), 
  col_factor(levels = c(TRUE, FALSE)), col_factor(levels = c(TRUE, FALSE)), 
  col_factor(levels = c('Affiliates', 'Direct', 'Display', 'Organic', 'Paid', 'Referral', 'Social'))))
ecom</code></pre>
<pre><code>## # A tibble: 5,000 x 4
##    device  bouncers purchase referrer  
##    &lt;fct&gt;   &lt;fct&gt;    &lt;fct&gt;    &lt;fct&gt;     
##  1 Desktop FALSE    FALSE    Affiliates
##  2 Mobile  FALSE    FALSE    Affiliates
##  3 Desktop TRUE     FALSE    Organic   
##  4 Desktop FALSE    FALSE    Organic   
##  5 Mobile  TRUE     FALSE    Direct    
##  6 Desktop TRUE     FALSE    Direct    
##  7 Desktop FALSE    FALSE    Referral  
##  8 Tablet  TRUE     FALSE    Organic   
##  9 Mobile  TRUE     FALSE    Social    
## 10 Desktop TRUE     FALSE    Organic   
## # ... with 4,990 more rows</code></pre>
<p>
<br>
</p>
</section>
<section id="data-dictionary" class="level3">
<h3 class="anchored" data-anchor-id="data-dictionary">
Data Dictionary
</h3>
<ul>
<li>
device: device used to visit the website
</li>
<li>
bouncers: whether visit was a bouncer (exit website from landing page)
</li>
<li>
purchase: whether visitor purchased
</li>
<li>
referrer: referrer website/search engine
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="aesthetics" class="level3">
<h3 class="anchored" data-anchor-id="aesthetics">
Aesthetics
</h3>
<ul>
<li>
<code>fill</code>
</li>
<li>
<code>color</code>
</li>
<li>
<code>linetype</code>
</li>
<li>
<code>size</code>
</li>
<li>
<code>position</code>
</li>
</ul>
<p>
<br>
</p>
<section id="simple-bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="simple-bar-plot">
Simple Bar Plot
</h4>
<p>
We can create a bar plot using <code>geom_bar()</code>. It takes a single input, a categorical variable. In the below example, we plot the number of visits for each device type.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="bar-color" class="level4">
<h4 class="anchored" data-anchor-id="bar-color">
Bar Color
</h4>
<p>
The color of the bars can be modified using the <code>fill</code> argument. In the below example, we assign different colors to the 3 bars in the plot. If you use the <code>color</code> argument, it will modify the color of the bar line and not the background color of the bars. We will look at that later in the post.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device), fill = c('red', 'blue', 'green'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="stacked-bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="stacked-bar-plot">
Stacked Bar Plot
</h4>
<p>
If you want to look at distribution of one categorical variable across the levels of another categorical variable, you can create a stacked bar plot. In ggplot2, a stacked bar plot is created by mapping the <code>fill</code> argument to the second categorical variable. In the below example, we have mapped <code>fill</code> to <code>referrer</code> variable.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device, fill = referrer))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="grouped-bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="grouped-bar-plot">
Grouped Bar Plot
</h4>
<p>
Grouped bar plots are a variation of stacked bar plots. Instead of being stacked on top of one another, the bars are placed next to one another and grouped by levels. In the below example, we create a grouped bar plot and you can observe that the bars are placed next to one another instead of being stacked as was shown in the previous example. To create a grouped bar plot, use the <code>position</code> argument and set it to <code>‘dodge’</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device, fill = referrer), position = 'dodge')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar8-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="proportional-bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="proportional-bar-plot">
Proportional Bar Plot
</h4>
<p>
In a proportional bar plot, the height of all the bars is proportional or same. To create a proportional bar plot, use the <code>position</code> argument and set it to <code>‘fill’</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device, fill = referrer), position = 'fill')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar10-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="horizontal-bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="horizontal-bar-plot">
Horizontal Bar Plot
</h4>
<p>
A horizontal bar plot can be created by flipping the coordinate axes of a regular plot. To flip the axes, use <code>coord_flip()</code> as shown below.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device, fill = referrer)) +
  coord_flip()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar9-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="bar-line" class="level4">
<h4 class="anchored" data-anchor-id="bar-line">
Bar Line
</h4>
<p>
The color of the bar line can be modified using the <code>color</code> argument. The color can be specified either using its name or hex code.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device), fill = 'white', color = c('red', 'blue', 'green'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
To modify the line type of the bar line, use the <code>linetype</code> argument. It can take values between <code>0</code> and <code>6</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device), fill = 'white',  color = 'black', linetype = 2)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar5-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The width of the bar line can be modified using the <code>size</code> argument. It can take any value greater than <code>0</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_bar(aes(device), fill = 'white', color = 'black', size = 2)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/2017-12-26-ggplot2-bar-plots_files/figure-html/bar6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to:
</p>
<ul>
<li>
build
<ul>
<li>
simple bar plot
</li>
<li>
stacked bar plot
</li>
<li>
grouped bar plot
</li>
<li>
proportional bar plot
</li>
</ul>
</li>
<li>
map aesthetics to variables
</li>
<li>
specify values for
<ul>
<li>
bar color
</li>
<li>
bar line color
</li>
<li>
bar line type
</li>
<li>
bar line size
</li>
</ul>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn to build box plots.
</p>
<p>
<br>
</p>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-bar-plots/</guid>
  <pubDate>Tue, 26 Dec 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_bar.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Line Graphs</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-12-14-ggplot2-line-graphs.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the 8th post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt to build scatter plots. In this post, we will learn to:
</p>
<ul>
<li>
build
<ul>
<li>
simple line chart
</li>
<li>
grouped line chart
</li>
</ul>
</li>
<li>
map aesthetics to variables
</li>
<li>
modify line
<ul>
<li>
color
</li>
<li>
type
</li>
<li>
size
</li>
</ul>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/84b3204eee81d6e804f10a73900809b5">here</a>.
</p>
<p>
<br>
</p>
<section id="case-study" class="level4">
<h4 class="anchored" data-anchor-id="case-study">
Case Study
</h4>
<p>
We will use a data set related to GDP growth rate. You can download it from <a href="https://github.com/rsquaredacademy/datasets/blob/master/gdp.csv">here</a>. It contains GDP (Gross Domestic Product) growth data for the BRICS (Brazil, Russia, India, China, South Africa) for the years 2000 to 2005.
</p>
<p>
<br>
</p>
</section>
<section id="data" class="level4">
<h4 class="anchored" data-anchor-id="data">
Data
</h4>
<pre class="r"><code>gdp &lt;- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/gdp.csv')</code></pre>
<pre><code>## Warning: Missing column names filled in: 'X1' [1]</code></pre>
<pre class="r"><code>gdp</code></pre>
<pre><code>## # A tibble: 6 x 6
##      X1     X year       growth india china
##   &lt;dbl&gt; &lt;dbl&gt; &lt;date&gt;      &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
## 1     1     1 2000-01-01      6     5     8
## 2     2     2 2001-01-01      9     9     5
## 3     3     3 2002-01-01      8     8     6
## 4     4     4 2003-01-01      9     8     8
## 5     5     5 2004-01-01      9     5     9
## 6     6     6 2005-01-01      8     7     8</code></pre>
<p>
<br>
</p>
</section>
<section id="line-chart" class="level4">
<h4 class="anchored" data-anchor-id="line-chart">
Line Chart
</h4>
<p>
To create a line chart, use <code>geom_line()</code>. In the below example, we examine the GDP growth rate trend of India for the years 2000 to 2005.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line100-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="line-color" class="level4">
<h4 class="anchored" data-anchor-id="line-color">
Line Color
</h4>
<p>
To modify the color of the line, use the <code>color</code> argument and supply it a valid color name. In the below example, we modify the color of the line to <code>‘blue’</code>. Remember that the <code>color</code> argument should be outside <code>aes()</code>.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(color = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line1-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="line-type" class="level4">
<h4 class="anchored" data-anchor-id="line-type">
Line Type
</h4>
<p>
The line type can be modified using the <code>linetype</code> argument. It can take 7 different values. You can specify the line type either using numbers or words as shown below:
</p>
<ul>
<li>
0 : blank
</li>
<li>
1 : solid
</li>
<li>
2 : dashed
</li>
<li>
3 : dotted
</li>
<li>
4 : dotdash
</li>
<li>
5 : longdash
</li>
<li>
6 : twodash
</li>
</ul>
<p>
<br>
</p>
<p>
Let us modify the line type to dashed style by supplying the value <code>2</code> to the <code>linetype</code> argument.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(linetype = 2)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The above example can be recreated by supplying the value <code>‘dashed’</code> instead of <code>2</code>.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(linetype = 'dashed')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="line-size" class="level4">
<h4 class="anchored" data-anchor-id="line-size">
Line Size
</h4>
<p>
The width of the line can be modified using the <code>size</code> argument. It can take any value above 0 as input.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(size = 2)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="modify-data" class="level4">
<h4 class="anchored" data-anchor-id="modify-data">
Modify Data
</h4>
<p>
Now let us map the aesthetics to the variables. The data used in the above example cannot be used as we need a variable with country names. We will use <code>gather()</code> function from the <code>tidyr</code> package to reshape the data.
</p>
<pre class="r"><code>gdp2 &lt;- gdp %&gt;% 
  select(year, growth, india, china) %&gt;% 
  gather(key = country, value = gdp, -year)

gdp2</code></pre>
<pre><code>## # A tibble: 18 x 3
##    year       country   gdp
##    &lt;date&gt;     &lt;chr&gt;   &lt;dbl&gt;
##  1 2000-01-01 growth      6
##  2 2001-01-01 growth      9
##  3 2002-01-01 growth      8
##  4 2003-01-01 growth      9
##  5 2004-01-01 growth      9
##  6 2005-01-01 growth      8
##  7 2000-01-01 india       5
##  8 2001-01-01 india       9
##  9 2002-01-01 india       8
## 10 2003-01-01 india       8
## 11 2004-01-01 india       5
## 12 2005-01-01 india       7
## 13 2000-01-01 china       8
## 14 2001-01-01 china       5
## 15 2002-01-01 china       6
## 16 2003-01-01 china       8
## 17 2004-01-01 china       9
## 18 2005-01-01 china       8</code></pre>
<p>
<br>
</p>
</section>
<section id="grouped-line-chart" class="level4">
<h4 class="anchored" data-anchor-id="grouped-line-chart">
Grouped Line Chart
</h4>
<p>
In the original data, to plot GDP trend of multiple countries we will have to use <code>geom_line()</code> multiple times. But in the reshaped data, we have the country names as one of the variables and this can be used along with the <code>group</code> argument to plot data of multiple countries with a single line of code as shown below. By mapping country to the <code>group</code> argument, we have plotted data of all countries.
</p>
<pre class="r"><code>ggplot(gdp2, aes(year, gdp, group = country)) +
  geom_line()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
In the above plot, we cannot distinguish between the lines and there is no way to identify which line represents which country. To make it easier to identify the trend of different countries, let us map the <code>color</code> argument to the variable country as shown below. Now, each country will be represented by line of different color.
</p>
<pre class="r"><code>ggplot(gdp2, aes(year, gdp, group = country)) +
  geom_line(aes(color = country))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
We can map <code>linetype</code> argument to country as well. In this case, each country will be represented by a different line type.
</p>
<pre class="r"><code>ggplot(gdp2, aes(year, gdp, group = country)) +
  geom_line(aes(linetype = country))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line8-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
We can map the width of the line to the variable country as well. But in this case, the plot does not look either elegant or intuitive.
</p>
<pre class="r"><code>ggplot(gdp2, aes(year, gdp, group = country)) +
  geom_line(aes(size = country))</code></pre>
<pre><code>## Warning: Using size for a discrete variable is not advised.</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/2017-12-14-ggplot2-line-graphs_files/figure-html/line9-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
Remember that in all the above cases, we mapped the arguments to a variable inside <code>aes()</code>.
</p>
<p>
<br>
</p>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to:
</p>
<ul>
<li>
build
<ul>
<li>
simple line chart
</li>
<li>
grouped line chart
</li>
</ul>
</li>
<li>
map aesthetics to variables
</li>
<li>
modify line
<ul>
<li>
color
</li>
<li>
type
</li>
<li>
size
</li>
</ul>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn to build bar plots.
</p>
<p>
<br>
</p>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-line-graphs/</guid>
  <pubDate>Thu, 14 Dec 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_line.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Scatter Plots</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-12-02-ggplot2-scatter-plots.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the fifth post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt about text annotations. In this post, we will:
</p>
<ul>
<li>
build scatter plots
</li>
<li>
modify point
<ul>
<li>
color
</li>
<li>
fill
</li>
<li>
alpha
</li>
<li>
shape
</li>
<li>
size
</li>
</ul>
</li>
<li>
fit regression line
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="">here</a>.
</p>
<p>
<br>
</p>
<section id="basic-plot" class="level4">
<h4 class="anchored" data-anchor-id="basic-plot">
Basic Plot
</h4>
<p>
As we did in the previous post, let us begin by creating a scatter plot using<br> <code>geom_point()</code> to examine the relationship between displacement and miles per gallon using the mtcars data.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="jitter" class="level4">
<h4 class="anchored" data-anchor-id="jitter">
Jitter
</h4>
<p>
If you want to avoid over plotting, use the <code>position</code> argument and supply it the value <code>‘jitter’</code>. It adds random noise to a plot and makes it easier to read.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg), position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat22-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Another way to avoid over plotting is to use <code>geom_jitter()</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_jitter(aes(disp, mpg))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="aesthetics" class="level4">
<h4 class="anchored" data-anchor-id="aesthetics">
Aesthetics
</h4>
<p>
Now let us modify the appearance of the points. There are two ways:
</p>
<ul>
<li>
specify values
</li>
<li>
map them to variables using <code>aes()</code>
</li>
</ul>
</section>
<section id="specify-values" class="level4">
<h4 class="anchored" data-anchor-id="specify-values">
Specify Values
</h4>
<section id="color" class="level5">
<h5 class="anchored" data-anchor-id="color">
Color
</h5>
<p>
To modify the color of the points, you can use the <code>color</code> argument and supply it a valid color name. In the below example, we change the color of the points to <code>‘blue’</code>. Keep in mind that the <code>color</code> argument should be outside <code>aes()</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg), color = 'blue', position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="alpha" class="level5">
<h5 class="anchored" data-anchor-id="alpha">
Alpha
</h5>
<p>
The transparency of the color can be modified using the <code>alpha</code> argument. It takes values between <code>0</code> and <code>1</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg), color = 'blue', alpha = 0.4, position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="shape" class="level5">
<h5 class="anchored" data-anchor-id="shape">
Shape
</h5>
<p>
The shape of the points can be modified using the <code>shape</code> argument. It takes values between <code>0</code> and <code>25</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg), shape = 3, position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat9-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="size" class="level5">
<h5 class="anchored" data-anchor-id="size">
Size
</h5>
<p>
The size of the points can be modified using the <code>size</code> argument. It can take any value greater than <code>0</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg), size = 3, position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat11-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="map-variables" class="level4">
<h4 class="anchored" data-anchor-id="map-variables">
Map Variables
</h4>
<p>
So far, we have specified values for color, shape, size etc. Now, let us map them to variables using <code>aes()</code>.
</p>
<section id="color-1" class="level5">
<h5 class="anchored" data-anchor-id="color-1">
Color
</h5>
<p>
You can modify the color of the points by mapping them to a variable using <code>aes()</code>. It allows you to examine the relationship between two continuous variables at different levels of a categorical variable.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = factor(cyl)), 
             position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The color can be mapped to a conitnuous variable as well and in this case you will be able to examine the relationship betweem two continuous variable for a range of value of a third variable.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, color = hp), 
             position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat5-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="shape-1" class="level5">
<h5 class="anchored" data-anchor-id="shape-1">
Shape
</h5>
<p>
Shape can be mapped to categorical variables. In the below example, we use <code>factor()</code> to convert <code>cyl</code> to categorical data before mapping shape to it. ggplot2 will throw an error if you map shape to a continuous variable.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, shape = factor(cyl)), position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat8-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="size-1" class="level5">
<h5 class="anchored" data-anchor-id="size-1">
Size
</h5>
<p>
Size must be always mapped to continuous variables. In the below example, we have mapped size to <code>hp</code> variable.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, size = hp), color = 'blue', position = 'jitter')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat10-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
If you map size to categorical data as shown in the below example, ggplot2 will throw a warning.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg, size = factor(cyl)), color = 'blue', position = 'jitter')</code></pre>
<pre><code>## Warning: Using size for a discrete variable is not advised.</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/scat10a-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="regression-line" class="level4">
<h4 class="anchored" data-anchor-id="regression-line">
Regression Line
</h4>
<p>
<code>geom_smooth()</code> allows us to fit a regression line to the plot. By default it will use least squares method to fit the line but you can also use the loess method. In the below example, we fit a regression line using the least squares technique by supplying the value <code>‘lm’</code> to the <code>method</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars, aes(disp, mpg)) +
  geom_point(position = 'jitter') +
  geom_smooth(method = 'lm', se = FALSE)</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/aes12-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="intercept-slope" class="level4">
<h4 class="anchored" data-anchor-id="intercept-slope">
Intercept &amp; Slope
</h4>
<p>
If you know the intercept and the slope of the line, you can use <code>geom_abline()</code>. Let us regress <code>mpg</code> over <code>disp</code> and then use the result to add the line.
</p>
<section id="regression" class="level6">
<h6 class="anchored" data-anchor-id="regression">
Regression
</h6>
<pre class="r"><code>lm(mpg ~ disp, data = mtcars)</code></pre>
<pre><code>## 
## Call:
## lm(formula = mpg ~ disp, data = mtcars)
## 
## Coefficients:
## (Intercept)         disp  
##    29.59985     -0.04122</code></pre>
</section>
<section id="add-line" class="level6">
<h6 class="anchored" data-anchor-id="add-line">
Add Line
</h6>
<pre class="r"><code>ggplot(mtcars, aes(disp, mpg)) +
  geom_point(position = 'jitter') +
  geom_abline(slope = -0.04122, intercept = 29.59985)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/aes17-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The <code>se</code> argument will add a confidence interval around the regression line, if set to <code>TRUE</code>.
</p>
</section>
<section id="conf.-interval" class="level5">
<h5 class="anchored" data-anchor-id="conf.-interval">
Conf. Interval
</h5>
<pre class="r"><code>ggplot(mtcars, aes(disp, mpg)) +
  geom_point(position = 'jitter') +
  geom_smooth(method = 'lm', se = TRUE)</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/aes13-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="loess-method" class="level5">
<h5 class="anchored" data-anchor-id="loess-method">
Loess Method
</h5>
<p>
In the below example, we use the loess method instead of the default least squares method to fit the regression line.
</p>
<pre class="r"><code>ggplot(mtcars, aes(disp, mpg)) +
  geom_point(position = 'jitter') +
  geom_smooth(method = 'loess', se = FALSE)</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/2017-12-02-ggplot2-scatter-plots_files/figure-html/aes14-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to:
</p>
<ul>
<li>
build scatter plots
</li>
<li>
map aesthetics to variables
</li>
<li>
fit regression line
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn to build line charts.
</p>
<p>
<br>
</p>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-scatter-plots/</guid>
  <pubDate>Sat, 02 Dec 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_scatter.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Text Annotations</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-text-annotations/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-11-20-ggplot2-text-annotations.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the sixth post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt to modify the axis and plot labels. In this post, we will learn to add text to the plots.
</p>
<ul>
<li>
add custom text
</li>
<li>
modify color
</li>
<li>
modify size
</li>
<li>
modify fontface
</li>
<li>
modify angle
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/567094325b5e134b5b4459677206f363">here</a>.
</p>
<p>
<br>
</p>
<section id="annotate" class="level4">
<h4 class="anchored" data-anchor-id="annotate">
Annotate
</h4>
<p>
We will use the <code>annotate()</code> function to add custom text to the plots. You can use the <code>annotate()</code> function to add rectangles/segments/pointrange as well but our focus will be on adding text. Let us start with a simple scatter plot.
</p>
<p>
<code>annotate()</code> takes the following arguments:
</p>
<ul>
<li>
<code>geom</code> : specify text
</li>
<li>
<code>x</code> : x axis location
</li>
<li>
<code>y</code> : y axis location
</li>
<li>
<code>label</code> : custom text
</li>
<li>
<code>color</code> : color of text
</li>
<li>
<code>size</code> : size of text
</li>
<li>
<code>fontface</code> : fontface of text
</li>
<li>
<code>angle</code> : angle of text
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="add-text" class="level4">
<h4 class="anchored" data-anchor-id="add-text">
Add Text
</h4>
<p>
Let us begin by adding text to a scatter plot. We will use the mtcars data set and continue to examine the relationship between displacement and miles per gallon. To add the text, we have to indicate that we are using <code>annotate()</code> for adding text, and we do this by ensuring that the first input is the word <code>‘text’</code>. Now, ggplot2 knows that it should add a text to the plot but it still needs other information such as:
</p>
<ul>
<li>
where should the text appear on the plot i.e.&nbsp;location of the text
</li>
<li>
and the text itself
</li>
</ul>
<p>
We will provide the location by specifying points on the X and Y axis which are also the second and third inputs to <code>annotate()</code> and the final input is the text itself, which in our example is <code>‘Sample Text’</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  annotate('text', x = 200, y = 30, label = 'Sample Text')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-text-annotations/2017-11-20-ggplot2-text-annotations_files/figure-html/ann2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="color" class="level4">
<h4 class="anchored" data-anchor-id="color">
Color
</h4>
<p>
Now that we know how to add text, let us look at modifying the appearance of the text. To change the color, use the <code>color</code> argument. In the below example, we modify the color to <code>‘red’</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  annotate('text', x = 200, y = 30, label = 'Sample Text', color = 'red')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-text-annotations/2017-11-20-ggplot2-text-annotations_files/figure-html/ann4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="size" class="level4">
<h4 class="anchored" data-anchor-id="size">
Size
</h4>
<p>
The <code>size</code> argument can be used to modify the size of the text.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  annotate('text', x = 200, y = 30, label = 'Sample Text', size = 6)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-text-annotations/2017-11-20-ggplot2-text-annotations_files/figure-html/ann5-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="font" class="level4">
<h4 class="anchored" data-anchor-id="font">
Font
</h4>
<p>
To choose a font of your liking, use the <code>font</code> argument and supply it a valid value.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  annotate('text', x = 200, y = 30, label = 'Sample Text', fontface = 'bold')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-text-annotations/2017-11-20-ggplot2-text-annotations_files/figure-html/ann6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="angle" class="level4">
<h4 class="anchored" data-anchor-id="angle">
Angle
</h4>
<p>
The angle of the text can also be modified using the <code>angle</code> argument. In the below example, we modify the angle of the text to <code>25</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  annotate('text', x = 200, y = 30, label = 'Sample Text', angle = 25)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-text-annotations/2017-11-20-ggplot2-text-annotations_files/figure-html/ann7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="putting-it-all-together.." class="level4">
<h4 class="anchored" data-anchor-id="putting-it-all-together..">
Putting it all together..
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  annotate('text', x = 200, y = 30, label = 'Sample Text',
           color = 'red', size = 6, fontface = 'bold', angle = 25)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-text-annotations/2017-11-20-ggplot2-text-annotations_files/figure-html/ann3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="summary" class="level4">
<h4 class="anchored" data-anchor-id="summary">
Summary
</h4>
<p>
In this post, we learnt to:
</p>
<ul>
<li>
add custom text
</li>
<li>
modify color
</li>
<li>
modify size
</li>
<li>
modify fontface
</li>
<li>
modify angle
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level4">
<h4 class="anchored" data-anchor-id="up-next..">
Up Next..
</h4>
<p>
In the next post, we will learn to build scatter plots.
</p>
</section>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-text-annotations/</guid>
  <pubDate>Mon, 20 Nov 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_text_ann.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2 - Axis and Plot Labels</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/axis-plot-labels/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-11-08-ggplot2-axis-plot-labels.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the fifth post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt about aesthetics. In this post, we will learn to:
</p>
<ul>
<li>
add title and subtitle to the plot
</li>
<li>
modify axis labels
</li>
<li>
modify axis range
</li>
<li>
remove axis
</li>
<li>
format axis
</li>
</ul>
<p>
<br>
</p>
<section id="basic-plot" class="level4">
<h4 class="anchored" data-anchor-id="basic-plot">
Basic Plot
</h4>
<p>
Let us start with a simple scatter plot. We will continue to use the mtcars data set and examine the relationship between displacement and miles per gallon using <code>geom_point()</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="title-subtitle" class="level4">
<h4 class="anchored" data-anchor-id="title-subtitle">
Title &amp; Subtitle
</h4>
<p>
There are two ways to add title to a plot:
</p>
<ul>
<li>
<code>ggtitle()</code>
</li>
<li>
<code>labs()</code>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="ggtitle" class="level4">
<h4 class="anchored" data-anchor-id="ggtitle">
ggtitle()
</h4>
<p>
Let us explore the <code>ggtitle()</code> function first. It takes two arguments:
</p>
<ul>
<li>
label: title of the plot
</li>
<li>
subtitle: subtitle of the plot
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="title-subtitle-1" class="level4">
<h4 class="anchored" data-anchor-id="title-subtitle-1">
Title &amp; Subtitle
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  ggtitle(label = 'Displacement vs Mileage', subtitle = 'disp vs mpg')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="axis-labels" class="level4">
<h4 class="anchored" data-anchor-id="axis-labels">
Axis Labels
</h4>
<p>
You can add labels to the axis using:
</p>
<ul>
<li>
<code>xlab()</code>
</li>
<li>
<code>ylab()</code>
</li>
<li>
<code>labs()</code>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="axis-labels-1" class="level4">
<h4 class="anchored" data-anchor-id="axis-labels-1">
Axis Labels
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  xlab('Displacement') + ylab('Miles Per Gallon')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="labs" class="level4">
<h4 class="anchored" data-anchor-id="labs">
Labs
</h4>
<p>
The <code>labs()</code> function can be used to add the following to a plot:
</p>
<ul>
<li>
title
</li>
<li>
subtitle
</li>
<li>
X axis label
</li>
<li>
Y axis label
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="labs-1" class="level4">
<h4 class="anchored" data-anchor-id="labs-1">
Labs
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  labs(title = 'Displacement vs Mileage', subtitle = 'disp vs mpg', 
    x = 'Displacement', y = 'Miles Per Gallon')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis5-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="axis-range" class="level4">
<h4 class="anchored" data-anchor-id="axis-range">
Axis Range
</h4>
<p>
In certain scenarios, you may want to modify the range of the axis. In ggplot2, we can achieve this using:
</p>
<ul>
<li>
<code>xlim()</code>
</li>
<li>
<code>ylim()</code>
</li>
<li>
<code>expand_limits()</code>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="axis-range-1" class="level4">
<h4 class="anchored" data-anchor-id="axis-range-1">
Axis Range
</h4>
<ul>
<li>
<code>xlim()</code> and <code>ylim()</code> take a numeric vector of length 2 as input
</li>
<li>
<code>expand_limits()</code> takes two numeric vectors (each of length 2), one for each axis
</li>
<li>
in all of the above functions, the first element represents the lower limit and the second element represents the upper limit
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="x-axis" class="level4">
<h4 class="anchored" data-anchor-id="x-axis">
X Axis
</h4>
<p>
In the below example, we limit the range of the X axis between <code>0</code> and <code>600</code> using <code>xlim</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  xlim(c(0, 600))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="y-axis" class="level4">
<h4 class="anchored" data-anchor-id="y-axis">
Y Axis
</h4>
<p>
Let us limit the range of the Y axis between <code>0</code> and <code>40</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  ylim(c(0, 40))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="expand-limits" class="level4">
<h4 class="anchored" data-anchor-id="expand-limits">
Expand Limits
</h4>
<p>
Let us use <code>expand_limits()</code> to limit the range of both the X and Y axis. The first input is the range for the X axis and the second input for the Y axis. In both the cases, we use a numeric vector of length 2 to specify the lower and upper limit.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  expand_limits(x = c(0, 600), y = c(0, 40))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis8-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="remove-axis-labels" class="level4">
<h4 class="anchored" data-anchor-id="remove-axis-labels">
Remove Axis Labels
</h4>
<p>
If you want to remove the axis labels all together, use the <code>theme()</code> function. It allows us to modify every aspect of the theme of the plot. Within <code>theme()</code>, set the following to <code>element_blank()</code>.
</p>
<ul>
<li>
<code>axis.title.x</code>
</li>
<li>
<code>axis.title.y</code>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="remove-axis-labels-using-theme" class="level4">
<h4 class="anchored" data-anchor-id="remove-axis-labels-using-theme">
Remove Axis Labels using theme()
</h4>
<p>
<code>element_blank()</code> will remove the title of the X and Y axis.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) +
  theme(axis.title.x = element_blank(), axis.title.y = element_blank())</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis9-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="format-title-axis-labels" class="level4">
<h4 class="anchored" data-anchor-id="format-title-axis-labels">
Format Title &amp; Axis Labels
</h4>
<p>
To format the title or the axis labels, we have to modify the theme of the plot using the <code>theme()</code> function. We can modify:
</p>
<ul>
<li>
color
</li>
<li>
font family
</li>
<li>
font face
</li>
<li>
font size
</li>
<li>
horizontal alignment
</li>
<li>
and angle
</li>
</ul>
<p>
In addition to <code>theme()</code>, we will also use <code>element_text()</code>. It should be used whenever you want to modify the appearance of any text element of your plot.
</p>
<p>
<br>
</p>
</section>
<section id="color" class="level4">
<h4 class="anchored" data-anchor-id="color">
Color
</h4>
<p>
In the below example, we use the <code>color</code> argument within <code>element_text()</code> to modify the color of the title of the plot to <code>‘blue’</code>.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) + ggtitle('Diaplacement vs Mileage') +
  theme(plot.title = element_text(color = 'blue'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis10-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="font-family" class="level4">
<h4 class="anchored" data-anchor-id="font-family">
Font Family
</h4>
<p>
Let us change the font family of the plot title to <code>‘Arial’</code> by using the <code>family</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) + ggtitle('Diaplacement vs Mileage') +
  theme(plot.title = element_text(family = 'Arial'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis11-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="font-face" class="level4">
<h4 class="anchored" data-anchor-id="font-face">
Font Face
</h4>
<p>
The font face can be any of the following:
</p>
<ul>
<li>
<code>plain</code>
</li>
<li>
<code>bold</code>
</li>
<li>
<code>italic</code>
</li>
<li>
<code>bold.italic</code>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="font-face-1" class="level4">
<h4 class="anchored" data-anchor-id="font-face-1">
Font Face
</h4>
<p>
The <code>face</code> argument can be used to modify the font face of the title of the plot.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) + ggtitle('Diaplacement vs Mileage') +
  theme(plot.title = element_text(face = 'bold'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis12-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="font-size" class="level4">
<h4 class="anchored" data-anchor-id="font-size">
Font Size
</h4>
<p>
The size of the title of the plot can be modified using the <code>size</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) + ggtitle('Diaplacement vs Mileage') +
  theme(plot.title = element_text(size = 8))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis13-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="horizontal-alignment" class="level4">
<h4 class="anchored" data-anchor-id="horizontal-alignment">
Horizontal Alignment
</h4>
<p>
To modify the horizontal alignment of the title, use the <code>hjust</code> argument. It can take values between <code>0</code> and <code>1</code>. If the value is closer to <code>0</code>, the text will be left-aligned and viceversa.
</p>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) + ggtitle('Diaplacement vs Mileage') +
  theme(plot.title = element_text(hjust = 0.3))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis14-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="putting-it-all-together" class="level3">
<h3 class="anchored" data-anchor-id="putting-it-all-together">
Putting it all together…
</h3>
<section id="title" class="level4">
<h4 class="anchored" data-anchor-id="title">
Title
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) + ggtitle('Diaplacement vs Mileage') +
  theme(plot.title = element_text(color = 'blue', family = 'Arial',
    face = 'bold', size = 12, hjust = 0.5))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis15-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="x-axis-label" class="level4">
<h4 class="anchored" data-anchor-id="x-axis-label">
X axis label
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) + xlab('Diaplacement') +
  theme(axis.title.x = element_text(color = 'blue', family = 'Arial',
    face = 'bold', size = 8, hjust = 0.5, angle = 15))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis16-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="y-axis-label" class="level4">
<h4 class="anchored" data-anchor-id="y-axis-label">
Y axis label
</h4>
<pre class="r"><code>ggplot(mtcars) +
  geom_point(aes(disp, mpg)) + ylab('Miles Per Gallon') +
  theme(axis.title.y = element_text(color = 'blue', family = 'Arial',
    face = 'italic', size = 8, vjust = 0.3, angle = 90))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/axis-plot-labels/2017-11-08-ggplot2-axis-plot-labels_files/figure-html/axis17-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to:
</p>
<ul>
<li>
add title and subtitle to the plot
</li>
<li>
modify axis labels
</li>
<li>
modify axis range
</li>
<li>
remove axis
</li>
<li>
format axis
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn to add text annotations to plots.
</p>
</section>



 ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/axis-plot-labels/</guid>
  <pubDate>Wed, 08 Nov 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_axis_labels.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2 - Introduction to Aesthetics</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-10-27-ggplot2-introduction-to-aesthetics.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the fourth post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt about geoms and how we can use them to build different plots. In this post, we will focus on the aesthetics i.e.&nbsp; color, shape, size, alpha, line type, line width etc. We can map these to variables or specify values for them. If we want to map the above to variables, we have to specify them within the <code>aes()</code> function. We will look at both methods in the following sections.
</p>
<p>
Explore aesthetics such as
</p>
<ul>
<li>
color
</li>
<li>
shape
</li>
<li>
size
</li>
<li>
fill
</li>
<li>
alpha
</li>
<li>
width
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
<li>
<a href="http://dplyr.tidyverse.org/">dplyr</a>
</li>
<li>
<a href="http://tidyr.tidyverse.org/">tidyr</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/a596a4604b2ebda163313caa272f05cd">here</a>.
</p>
<p>
<br>
</p>
</section>
<section id="data" class="level3">
<h3 class="anchored" data-anchor-id="data">
Data
</h3>
<section id="introduction-1" class="level4">
<h4 class="anchored" data-anchor-id="introduction-1">
Introduction
</h4>
<pre class="r"><code>ecom &lt;- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/web.csv')
ecom</code></pre>
<pre><code>## # A tibble: 1,000 x 11
##       id referrer device bouncers n_visit n_pages duration country purchase
##    &lt;dbl&gt; &lt;chr&gt;    &lt;chr&gt;  &lt;lgl&gt;      &lt;dbl&gt;   &lt;dbl&gt;    &lt;dbl&gt; &lt;chr&gt;   &lt;lgl&gt;   
##  1     1 google   laptop TRUE          10       1      693 Czech ~ FALSE   
##  2     2 yahoo    tablet TRUE           9       1      459 Yemen   FALSE   
##  3     3 direct   laptop TRUE           0       1      996 Brazil  FALSE   
##  4     4 bing     tablet FALSE          3      18      468 China   TRUE    
##  5     5 yahoo    mobile TRUE           9       1      955 Poland  FALSE   
##  6     6 yahoo    laptop FALSE          5       5      135 South ~ FALSE   
##  7     7 yahoo    mobile TRUE          10       1       75 Bangla~ FALSE   
##  8     8 direct   mobile TRUE          10       1      908 Indone~ FALSE   
##  9     9 bing     mobile FALSE          3      19      209 Nether~ FALSE   
## 10    10 google   mobile TRUE           6       1      208 Czech ~ FALSE   
## # ... with 990 more rows, and 2 more variables: order_items &lt;dbl&gt;,
## #   order_value &lt;dbl&gt;</code></pre>
<p>
<br>
</p>
</section>
<section id="data-dictionary" class="level4">
<h4 class="anchored" data-anchor-id="data-dictionary">
Data Dictionary
</h4>
<ul>
<li>
id: row id
</li>
<li>
referrer: referrer website/search engine
</li>
<li>
os: operating system
</li>
<li>
browser: browser
</li>
<li>
device: device used to visit the website
</li>
<li>
n_pages: number of pages visited
</li>
<li>
duration: time spent on the website (in seconds)
</li>
<li>
repeat: frequency of visits
</li>
<li>
country: country of origin
</li>
<li>
purchase: whether visitor purchased
</li>
<li>
order_value: order value of visitor (in dollars)
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="color" class="level4">
<h4 class="anchored" data-anchor-id="color">
Color
</h4>
<p>
In ggplot2, when we mention <code>color</code> or <code>colour</code>, it usually refers to the color of the geoms. The <code>fill</code> argument is used to specify the color of the shapes in certain cases. In this first section, we will see how we can specify the color for the different geoms we learnt in the previous post.
</p>
<p>
<br>
</p>
</section>
<section id="point" class="level4">
<h4 class="anchored" data-anchor-id="point">
Point
</h4>
<p>
For points, the <code>color</code> argument specifies the color of the point for certain shapes and border for others. The <code>fill</code> argument is used to specify the background for some shapes and will not work with other shapes. Let us look at an example:
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg, color = factor(cyl))) +
  geom_point()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes2-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
We can map the variable to color in the <code>geom_point()</code> function as well since it inherits the data from the <code>ggplot()</code> function.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(aes(color = factor(cyl)))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes3-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
If you do not want to map a variable to color, you can specify it separately using the <code>color</code> argument but in this case it should be outside the <code>aes()</code> function.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(color = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes4-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Now we will change the shape of the points to understand the difference between <code>color</code> and <code>fill</code> arguments. It can be again mapped to variables or values. Let us map shape to variables.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg, shape = factor(cyl))) +
  geom_point()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes5-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Let us map shape to <code>cyl</code> in the <code>geom_point()</code> function. Remember, when you are mapping an aesthetic to a variable, it must be inside <code>aes()</code>.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(aes(shape = factor(cyl)))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes6-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Instead of mapping shape to a variable, let us specify a value for shape. In this case, <code>shape</code> is not wrapped inside <code>aes()</code> as we are not mapping it to a variable.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(shape = 5)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes7-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Let us specify a color for the point using <code>color</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(shape = 5, color = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes8-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Background color cannot be added for all shapes. In the below example, we try to modify the background color using the <code>fill</code> argument but it does not work.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(shape = 5, fill = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes9-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Since the shape number is now greater than 21, <code>fill</code> argument will add background color in the below case.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(shape = 22, fill = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes10-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
In shapes greater than number 21, <code>color</code> argument will modify the border of the shape.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(shape = 22, color = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes11-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Let us map size of points to a variable. It is advised to map size only to continuous variables and not categorical variables.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg, size = disp)) +
  geom_point()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes12-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
If you map size to categorical variables, ggplot2 will throw a warning.
</p>
<p>
Specify value for size.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(size = 4)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes13-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
To modify the opacity of the color, use the <code>alpha</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point(aes(alpha = factor(cyl)), color = 'blue')</code></pre>
<pre><code>## Warning: Using alpha for a discrete variable is not advised.</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes14-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
So far we have focussed on <code>geom_point()</code> to learn how to map aesthetics to variables. To explore line type and line width, we will use <code>geom_line()</code>. In the previous post, we used <code>geom_line()</code> to build line charts. Now we will modify the appearance of the line. In the section below, we will specify values for color, line type and width. In the next section, we will map the same to variables in the data. We will use a new data set. You can download it from <a href="https://github.com/rsquaredacademy/datasets/blob/master/gdp.csv">here</a>. It contains GDP (Gross Domestic Product) growth data for the BRICS (Brazil, Russia, India, China, South Africa) for the years 2000 to 2005.
</p>
</section>
</section>
<section id="data-1" class="level3">
<h3 class="anchored" data-anchor-id="data-1">
Data
</h3>
<pre class="r"><code>gdp &lt;- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/gdp.csv')</code></pre>
<pre><code>## Warning: Missing column names filled in: 'X1' [1]</code></pre>
<p>
A line chart can be created using <code>geom_line()</code>. In the below example, we examine the GDP trend of India and modify the color of the line to <code>‘blue’</code>.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(color = 'blue')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes15-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
To modify the line type, use the <code>linetype</code> argument. It can take values between 1 and 5.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(linetype = 2)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes16-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
The line type can also be mentioned in the following way:
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(linetype = 'dashed')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes17-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The width of the line can be modified using the <code>size</code> argument.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(size = 2)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes18-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Now let us map the aesthetics to the variables. The data used in the above example cannot be used as we need a variable with country names. We will use <code>gather()</code> function from the <code>tidyr</code> package to reshape the data.
</p>
<pre class="r"><code>gdp2 &lt;- 
  gdp %&gt;% 
  select(year, growth, india, china) %&gt;% 
  gather(key = country, value = gdp, -year)

gdp2</code></pre>
<pre><code>## # A tibble: 18 x 3
##    year       country   gdp
##    &lt;date&gt;     &lt;chr&gt;   &lt;dbl&gt;
##  1 2000-01-01 growth      6
##  2 2001-01-01 growth      9
##  3 2002-01-01 growth      8
##  4 2003-01-01 growth      9
##  5 2004-01-01 growth      9
##  6 2005-01-01 growth      8
##  7 2000-01-01 india       5
##  8 2001-01-01 india       9
##  9 2002-01-01 india       8
## 10 2003-01-01 india       8
## 11 2004-01-01 india       5
## 12 2005-01-01 india       7
## 13 2000-01-01 china       8
## 14 2001-01-01 china       5
## 15 2002-01-01 china       6
## 16 2003-01-01 china       8
## 17 2004-01-01 china       9
## 18 2005-01-01 china       8</code></pre>
<p>
<br>
</p>
<p>
To map the aesthetics to a variable, we must use the <code>group</code> argument. In the below example, we map the aesthetics to <code>country</code>. But we cannot distinguish between the lines as their color, width and line type are the same. We have easily plotted the GDP trend of all countries using the <code>group</code> argument. Now, let us ensure that we can distinguish and identidy them using different aesthetics.
</p>
<pre class="r"><code>ggplot(gdp2, aes(year, gdp, group = country)) +
  geom_line()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes20-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Let us begin by ensuring that the lines have different color using the <code>color</code> argument within <code>aes()</code> and assigning it the variable <code>country</code>.
</p>
<pre class="r"><code>ggplot(gdp2, aes(year, gdp, group = country)) +
  geom_line(aes(color = country))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes21-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Instead of color, now we modify the line type using the <code>linetype</code> argument.
</p>
<pre class="r"><code>ggplot(gdp2, aes(year, gdp, group = country)) +
  geom_line(aes(linetype = country))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes22-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
In the below instance, we assign different width to the lines using the <code>size</code> argument.
</p>
<pre class="r"><code>ggplot(gdp2, aes(year, gdp, group = country)) +
  geom_line(aes(size = country))</code></pre>
<pre><code>## Warning: Using size for a discrete variable is not advised.</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes23-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
Before we wrap up, let us quickly see how we can map aesthetics to variables for different plots.
</p>
<section id="bar-plots" class="level4">
<h4 class="anchored" data-anchor-id="bar-plots">
Bar Plots
</h4>
<p>
Here we create a stacked bar plot by mapping <code>fill</code> to <code>purchase</code>.
</p>
<pre class="r"><code>ggplot(ecom, aes(device, fill = purchase)) +
  geom_bar()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes24-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="histograms" class="level4">
<h4 class="anchored" data-anchor-id="histograms">
Histograms
</h4>
<p>
Instead of a bar chart, we create a histogram and again map <code>fill</code> to <code>purchase</code>.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_histogram(aes(duration, fill = purchase), bins = 10)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes25-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="box-plots" class="level4">
<h4 class="anchored" data-anchor-id="box-plots">
Box Plots
</h4>
<p>
We repeat the same exercise below, but replace the bar plot with a box plot.
</p>
<pre class="r"><code>ggplot(ecom) +
  geom_boxplot(aes(device, duration, fill = purchase))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/2017-10-27-ggplot2-introduction-to-aesthetics_files/figure-html/aes26-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
In all the above cases, you can observe that when we are mapping aesthetics such as color, fill, shape, size or linetype to variables, they are all wrapped inside <code>aes()</code>.
</p>
<p>
<br>
</p>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt about aesthetics i.e.&nbsp;how to modify the properties of geoms such as:
</p>
<ul>
<li>
color
</li>
<li>
shape
</li>
<li>
size
</li>
<li>
fill
</li>
<li>
alpha
</li>
<li>
width
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn to modify the axis and labels of a plot.
</p>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-aesthetics/</guid>
  <pubDate>Fri, 27 Oct 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_aesthetics.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2 - Introduction to geoms</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-10-15-ggplot2-introduction-to-geoms.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the third post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we learnt how to create plots using the <code>qplot()</code> function. In this post, we will create some of the most routinely used plots to explore data using the <code>geom_*</code> functions.
</p>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
<li>
<a href="http://tibble.tidyverse.org/">tibble</a>
</li>
<li>
<a href="http://dplyr.tidyverse.org/">dplyr</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/2d0d5d5b60d0ef0f4d1b227c8fb0335d">here</a>.
</p>
<p>
<br>
</p>
</section>
<section id="data" class="level3">
<h3 class="anchored" data-anchor-id="data">
Data
</h3>
<pre class="r"><code>ecom &lt;- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/web.csv')
ecom</code></pre>
<pre><code>## # A tibble: 1,000 x 11
##       id referrer device bouncers n_visit n_pages duration country purchase
##    &lt;dbl&gt; &lt;chr&gt;    &lt;chr&gt;  &lt;lgl&gt;      &lt;dbl&gt;   &lt;dbl&gt;    &lt;dbl&gt; &lt;chr&gt;   &lt;lgl&gt;   
##  1     1 google   laptop TRUE          10       1      693 Czech ~ FALSE   
##  2     2 yahoo    tablet TRUE           9       1      459 Yemen   FALSE   
##  3     3 direct   laptop TRUE           0       1      996 Brazil  FALSE   
##  4     4 bing     tablet FALSE          3      18      468 China   TRUE    
##  5     5 yahoo    mobile TRUE           9       1      955 Poland  FALSE   
##  6     6 yahoo    laptop FALSE          5       5      135 South ~ FALSE   
##  7     7 yahoo    mobile TRUE          10       1       75 Bangla~ FALSE   
##  8     8 direct   mobile TRUE          10       1      908 Indone~ FALSE   
##  9     9 bing     mobile FALSE          3      19      209 Nether~ FALSE   
## 10    10 google   mobile TRUE           6       1      208 Czech ~ FALSE   
## # ... with 990 more rows, and 2 more variables: order_items &lt;dbl&gt;,
## #   order_value &lt;dbl&gt;</code></pre>
<p>
<br>
</p>
<section id="data-dictionary" class="level4">
<h4 class="anchored" data-anchor-id="data-dictionary">
Data Dictionary
</h4>
<ul>
<li>
id: row id
</li>
<li>
referrer: referrer website/search engine
</li>
<li>
os: operating system
</li>
<li>
browser: browser
</li>
<li>
device: device used to visit the website
</li>
<li>
n_pages: number of pages visited
</li>
<li>
duration: time spent on the website (in seconds)
</li>
<li>
repeat: frequency of visits
</li>
<li>
country: country of origin
</li>
<li>
purchase: whether visitor purchased
</li>
<li>
order_value: order value of visitor (in dollars)
</li>
</ul>
<p>
<br>
</p>
</section>
</section>
<section id="scatter-plot" class="level3">
<h3 class="anchored" data-anchor-id="scatter-plot">
Scatter Plot
</h3>
<p>
A scatter plot displays the relationship between two continuous variables. In ggplot2, we can build a scatter plot using <code>geom_point()</code>. Scatterplots can show you visually
</p>
<ul>
<li>
the strength of the relationship between the variables
</li>
<li>
the direction of the relationship between the variables
</li>
<li>
and whether outliers exist
</li>
</ul>
<p>
<br>
</p>
<section id="point" class="level4">
<h4 class="anchored" data-anchor-id="point">
Point
</h4>
<p>
The variables representing the X and Y axis can be specified either in <code>ggplot()</code> or in <code>geom_point()</code>. We will learn to modify the appearance of the points in a different post.
</p>
<pre class="r"><code>ggplot(ecom, aes(x = n_pages, y = duration)) + 
  geom_point()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="regression-line" class="level4">
<h4 class="anchored" data-anchor-id="regression-line">
Regression Line
</h4>
<p>
A regression line can be fit using either:
</p>
<ul>
<li>
<code>geom_abline()</code>
</li>
<li>
<code>geom_smooth()</code>
</li>
</ul>
</section>
<section id="regression-line-1" class="level4">
<h4 class="anchored" data-anchor-id="regression-line-1">
Regression Line
</h4>
<p>
If you are using <code>geom_abline()</code>, you need to specify the intercept and slope as shown in the below example:
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() + 
  geom_abline(intercept = 37.285, slope = -5.344)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms5-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="regression-line-2" class="level4">
<h4 class="anchored" data-anchor-id="regression-line-2">
Regression Line
</h4>
<p>
If you are using <code>geom_smooth()</code>, you need to specify the method of fitting the line, which can be <code>lm</code> or <code>loess</code>. You also need to indicate whether the confidence interval must be displayed using the <code>se</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_smooth(method = 'lm', se = TRUE)</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms6-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="loess-method" class="level4">
<h4 class="anchored" data-anchor-id="loess-method">
Loess Method
</h4>
<p>
Here we use the <code>‘loess’</code> method to fit the regression line.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_smooth(method = 'loess', se = FALSE)</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms7-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="horizontalvertical-lines" class="level4">
<h4 class="anchored" data-anchor-id="horizontalvertical-lines">
Horizontal/Vertical Lines
</h4>
<p>
Add horizontal or vertical lines using
</p>
<ul>
<li>
<code>geom_hline()</code>
</li>
<li>
<code>geom_vline()</code>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="horizontal-line" class="level4">
<h4 class="anchored" data-anchor-id="horizontal-line">
Horizontal Line
</h4>
<p>
To add a horizontal line, the Y axis intercept must be supplied using the <code>yintercept</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_hline(yintercept = 30) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms4-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="vertical-line" class="level4">
<h4 class="anchored" data-anchor-id="vertical-line">
Vertical Line
</h4>
<p>
For the vertical line, the X axis intercept must be supplied using the <code>xintercept</code> argument.
</p>
<pre class="r"><code>ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_vline(xintercept = 5) </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms3-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="bar-plot">
Bar Plot
</h4>
<p>
Bar plots present grouped data with rectangular bars. The bars may represent the frequency of the groups or values. Bar plots can be:
</p>
<ul>
<li>
horizontal
</li>
<li>
vertical
</li>
<li>
grouped
</li>
<li>
stacked
</li>
<li>
proportional
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="frequency" class="level4">
<h4 class="anchored" data-anchor-id="frequency">
Frequency
</h4>
<pre class="r"><code>ggplot(ecom, aes(x = factor(device))) +
  geom_bar()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms8-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="weight" class="level4">
<h4 class="anchored" data-anchor-id="weight">
Weight
</h4>
<p>
If the bars should represent a continuous variable, use the <code>weight</code> argument within <code>aes()</code>. In the below example, the bars do not represent the count of devices, instead, they represent the total order value for each device type.
</p>
<pre class="r"><code>ggplot(ecom, aes(x = factor(device))) +
  geom_bar(aes(weight = order_value))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms9-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="stacked-bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="stacked-bar-plot">
Stacked Bar Plot
</h4>
<p>
To create a stacked bar plot, the <code>fill</code> argument must be mapped to a categorical variable.
</p>
<pre class="r"><code>ggplot(ecom, aes(x = factor(device))) +
  geom_bar(aes(fill = purchase))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms10-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="horizontal-bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="horizontal-bar-plot">
Horizontal Bar Plot
</h4>
<p>
A horizontal bar plot can be created by flipping the coordinate axes using the <code>coord_flip()</code> function.
</p>
<pre class="r"><code>ggplot(ecom, aes(x = factor(device))) +
  geom_bar(aes(fill = purchase)) +
  coord_flip()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms11-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="columns" class="level4">
<h4 class="anchored" data-anchor-id="columns">
Columns
</h4>
<p>
If the data has already been summarized, you can use <code>geom_col()</code> instead of <code>geom_bar()</code>. In the below example, we have the total visits for each device type. The data has already been summarized and as such we cannot use <code>geom_bar()</code>.
</p>
<pre class="r"><code>device &lt;- c('laptop', 'mobile', 'tablet')
visits &lt;- c(30000, 12000, 5000)
traffic &lt;- tibble::tibble(device, visits)
ggplot(traffic, aes(x = device, y = visits)) +
  geom_col(fill = 'blue') </code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms12-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="boxplot" class="level4">
<h4 class="anchored" data-anchor-id="boxplot">
Boxplot
</h4>
<p>
The box plot is a standardized way of displaying the distribution of data based on the five number summary: minimum, first quartile, median, third quartile, and maximum. Box plots are useful for detecting outliers and for comparing distributions. It shows the shape, central tendancy and variability of the data. Use <code>geom_boxplot()</code> to create a box plot.
</p>
<p>
<br>
</p>
<pre class="r"><code>ggplot(ecom, aes(x = factor(device), y = n_pages)) +
  geom_boxplot()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms13-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="histogram" class="level4">
<h4 class="anchored" data-anchor-id="histogram">
Histogram
</h4>
<p>
A histogram is a plot that can be used to examine the shape and spread of continuous data. It looks very similar to a bar graph and can be used to detect outliers and skewness in data. Use <code>geom_histogram()</code> to create a histogram.
</p>
<p>
<br>
</p>
<pre class="r"><code>ggplot(ecom, aes(x = duration)) +
  geom_histogram()</code></pre>
<pre><code>## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms15-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
You can control the number of bins using the <code>bins</code> argument.
</p>
<pre class="r"><code>ggplot(ecom, aes(x = duration)) +
  geom_histogram(bins = 5)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms16-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="line" class="level4">
<h4 class="anchored" data-anchor-id="line">
Line
</h4>
<p>
Line charts are used to examine trends over time. We will use a different data set for exploring line plots.
</p>
<p>
<br>
</p>
</section>
<section id="data-1" class="level4">
<h4 class="anchored" data-anchor-id="data-1">
Data
</h4>
<pre class="r"><code>gdp &lt;- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/gdp.csv')</code></pre>
<pre><code>## Warning: Missing column names filled in: 'X1' [1]</code></pre>
<pre class="r"><code>gdp</code></pre>
<pre><code>## # A tibble: 6 x 6
##      X1     X year       growth india china
##   &lt;dbl&gt; &lt;dbl&gt; &lt;date&gt;      &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
## 1     1     1 2000-01-01      6     5     8
## 2     2     2 2001-01-01      9     9     5
## 3     3     3 2002-01-01      8     8     6
## 4     4     4 2003-01-01      9     8     8
## 5     5     5 2004-01-01      9     5     9
## 6     6     6 2005-01-01      8     7     8</code></pre>
<p>
<br>
</p>
<p>
Use <code>geom_line()</code> to create a line chart. In the below plot, we chart the GDP of India, the fastest growing economy in emerging markets, across years.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geomline1-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
<p>
The color and line type can be modified using the <code>color</code> and <code>linetype</code> arguments. We will explore the different line types in an upcoming post.
</p>
<pre class="r"><code>ggplot(gdp, aes(year, india)) +
  geom_line(color = 'blue', linetype = 'dashed')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geomline2-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="label" class="level4">
<h4 class="anchored" data-anchor-id="label">
Label
</h4>
<p>
You can label the points using <code>geom_label()</code>.
</p>
<pre class="r"><code>ggplot(mtcars, aes(disp, mpg, label = rownames(mtcars))) +
  geom_label()</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms20-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="text" class="level4">
<h4 class="anchored" data-anchor-id="text">
Text
</h4>
<p>
<code>geom_text()</code> offers another way to add text to the plots. We will learn to modify the appearance and location of the text in another post.
</p>
<pre class="r"><code>ggplot(mtcars, aes(disp, mpg, label = rownames(mtcars))) +
  geom_text(check_overlap = TRUE, size = 2)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/2017-10-15-ggplot2-introduction-to-geoms_files/figure-html/geoms19-1.png" width="672" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt about different <code>geoms</code> such as
</p>
<ul>
<li>
<code>geom_point()</code>
</li>
<li>
<code>geom_line()</code>
</li>
<li>
<code>geom_histogram()</code>
</li>
<li>
<code>geom_bar()</code>
</li>
<li>
<code>geom_boxplot()</code>
</li>
<li>
<code>geom_abline()</code>
</li>
<li>
<code>geom_text()</code>
</li>
</ul>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will learn about aesthetics.
</p>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-introduction-to-geoms/</guid>
  <pubDate>Sun, 15 Oct 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_geoms.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>ggplot2: Quick Tour</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-10-03-ggplot2-quick-tour.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the second post in the series <strong>Elegant Data Visualization with ggplot2</strong>. In the previous post, we understood the concept of grammar of graphics and even built a bar plot step by step while exploring the different components of a plot/chart. In this post, we will learn to quickly build a set of plots that are routinely used to explore data using <code>qplot()</code>. It can be used to quickly create plots but also has certain limitations. Nevertheless, if you want to quickly explore data using a single function, <code>qplot()</code> is your friend.
</p>
<p>
<br>
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
We will use the following libraries in this post:
</p>
<ul>
<li>
<a href="http://readr.tidyverse.org/">readr</a>
</li>
<li>
<a href="http://ggplot2.tidyverse.org/">ggplot2</a>
</li>
</ul>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/3b25fa07c60d44d561819d2c6ab77978">here</a>.
</p>
<p>
<br>
</p>
<section id="scatter-plot" class="level4">
<h4 class="anchored" data-anchor-id="scatter-plot">
Scatter Plot
</h4>
<p>
Scatter plots are used to examine the relationship between two continuous variables. The relationship can be examined across the levels of a categorical variable as well. Let us begin by creating scatter plots. The first two inputs are the variables/columns representing the X and Y axis. The next input is the name of the data set.
</p>
<pre class="r"><code>qplot(disp, mpg, data = mtcars)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg2-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
If you want the relationship between the two variables to be represented by both points and line, use the <code>geom</code> argument and supply it the values using a character vector.
</p>
<pre class="r"><code>qplot(disp, mpg, data = mtcars, geom = c('point', 'line'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg3-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
The color of the points can be mapped to a categorical variable, in our case <code>cyl</code>, using the color argument. Ensure that the variable is categorical using <code>factor()</code>.
</p>
<pre class="r"><code>qplot(disp, mpg, data = mtcars, color = factor(cyl))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg4-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
The shape and size of the points can also be mapped to variables using the <code>shape</code> and <code>size</code> argument as shown in the below examples.
</p>
<pre class="r"><code>qplot(disp, mpg, data = mtcars, shape = factor(cyl))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg5-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
Ensure that size is mapped to a continuous variable.
</p>
<pre class="r"><code>qplot(disp, mpg, data = mtcars, size = qsec)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg6-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="bar-plot" class="level4">
<h4 class="anchored" data-anchor-id="bar-plot">
Bar Plot
</h4>
<p>
A bar plot represents data in rectangular bars. The length of the bars are proportional to the values they represent. Bar plots can be either horizontal or vertical. The X axis of the plot represents the levels or the categories and the Y axis represents the frequency/count of the variable.
</p>
<p>
To create a bar plot, the first input must be a categorical variable. You can convert a variable to type <code>factor</code> (R equivalent of categorical) using the <code>factor()</code> function. The next input is the name of the data set and the final input is the <code>geom</code> which is supplied the value <code>‘bar’</code>.
</p>
<pre class="r"><code>qplot(factor(cyl), data = mtcars, geom = c('bar'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg7-1.png" width="576" style="display: block; margin: auto;"> You can create a stacked bar plot using the <code>fill</code> argument and mapping it to another categorical variable.
</p>
<pre class="r"><code>qplot(factor(cyl), data = mtcars, geom = c('bar'), fill = factor(am))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg8-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="box-plot" class="level4">
<h4 class="anchored" data-anchor-id="box-plot">
Box Plot
</h4>
<p>
The box plot is a standardized way of displaying the distribution of data based on the five number summary: minimum, first quartile, median, third quartile, and maximum. Box plots are useful for detecting outliers and for comparing distributions. It shows the shape, central tendancy and variability of the data.
</p>
<p>
Box plots can be created by supplying the value <code>‘boxplot’</code> to the <code>geom</code> argument. The firstinput must be a categorical variable and the second must be a continuous variable.
</p>
<pre class="r"><code>qplot(factor(cyl), mpg, data = mtcars, geom = c('boxplot'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg9-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
Unlike <code>plot()</code>, we cannot create box plots using a single variable. If you are not comparing the distribution of a variable across the levels of a categorical variable, you must supply the value <code>1</code> as the first input as show below.
</p>
<pre class="r"><code>qplot(factor(1), mpg, data = mtcars, geom = c('boxplot'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg10-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="line-chart" class="level4">
<h4 class="anchored" data-anchor-id="line-chart">
Line Chart
</h4>
<p>
Line charts are used to examing trends across time. To create a line chart, supply the value <code>‘line’</code> to the <code>geom</code> argument. The first two inputs should be names of the columns/variables representing the X and Y axis, and the third input must be the name of the data set.
</p>
<pre class="r"><code>qplot(x = date, y = unemploy, data = economics, geom = c('line'))</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg12-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
The appearance of the line can be modified using the <code>color</code> argument as shown below.
</p>
<pre class="r"><code>qplot(x = date, y = unemploy, data = economics, geom = c('line'),
      color = 'red')</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg13-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
<section id="histogram" class="level4">
<h4 class="anchored" data-anchor-id="histogram">
Histogram
</h4>
<p>
A histogram is a plot that can be used to examine the shape and spread of continuous data. It looks very similar to a bar graph and can be used to detect outliers and skewness in data. A histogram is created using the <code>bins</code> argument as shown below. The first input is the name of the continuous variable and the second is the name of the data set.
</p>
<pre class="r"><code>qplot(mpg, data = mtcars, bins = 5)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/2017-10-03-ggplot2-quick-tour_files/figure-html/gg14-1.png" width="576" style="display: block; margin: auto;">
</p>
<p>
<br>
</p>
</section>
</section>
<section id="summary" class="level3">
<h3 class="anchored" data-anchor-id="summary">
Summary
</h3>
<p>
In this post, we learnt to quickly create plots using the <code>qplot()</code> function. While useful, it has limitations and can be used only to quickly visualize data.
</p>
<p>
<br>
</p>
</section>
<section id="up-next.." class="level3">
<h3 class="anchored" data-anchor-id="up-next..">
Up Next..
</h3>
<p>
In the next post, we will create the same set of plots but using <strong>geoms</strong>.
</p>
<p>
<br>
</p>
</section>



 ]]></description>
  <category>ggplot2</category>
  <guid>https://blog.rsquaredacademy.com/posts/ggplot2-quick-tour/</guid>
  <pubDate>Tue, 03 Oct 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/gg_quick_tour.png" medium="image" type="image/png" height="89" width="144"/>
</item>
<item>
  <title>Data Visualization with R - Combining Plots</title>
  <dc:creator>Aravind Hebbali</dc:creator>
  <link>https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/</link>
  <description><![CDATA[ 




<!-- Migrated from content/post/2017-09-09-data-visualization-with-r-combining-plots.Rmd. -->
<!-- Day-1 static bundle: body reuses the pre-rendered .html fragment. -->
<section id="introduction" class="level3">
<h3 class="anchored" data-anchor-id="introduction">
Introduction
</h3>
<p>
This is the tenth post in the series <strong>Data Visualization With R</strong>. In the previous post, we learnt how to add text annotations to plots. In this post, we will learn how to combine multiple plots. Often, it is useful to have multiple plots in the same frame as it allows us to get a comprehensive view of a particular variable or compare among different variables. The Graphics package offers two methods to combine multiple plots. <code>par()</code> can be used to set graphical parameters regarding plot layout using the mfcol and mfrow arguments. <code>layout()</code> serves the same purpose but offers more flexibility by allowing us to modify the height and width of rows and columns.
</p>
<p>
<code>par()</code> allows us to customize the graphical parameters(title, axis, font, color, size) for a particular session. For combining multiple plots, we can use the graphical parameters mfrow and mfcol. These two parameters create a matrix of plots filled by rows and columns respectively. Let us combine plots using both the above parameters.
</p>
<table class="table">
<thead>
<tr class="header">
<th align="left">
Option
</th>
<th align="left">
Description
</th>
<th align="left">
Arguments
</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">
mfrow
</td>
<td align="left">
Fill by rows
</td>
<td align="left">
Number of rows and columns
</td>
</tr>
<tr class="even">
<td align="left">
mfcol
</td>
<td align="left">
Fill by columns
</td>
<td align="left">
Number of rows and columns
</td>
</tr>
</tbody>
</table>
<p>
mfrow combines plots filled by rows i.e it takes two arguments, the number of rows and number of columns and then starts filling the plots by row. Below is the syntax for mfrow.
</p>
<pre class="r"><code># mfrow syntax
mfrow(number of rows, number of columns)</code></pre>
<p>
Let us begin by combining 4 plots in 2 rows and 2 columns:
</p>
</section>
<section id="libraries-code-data" class="level3">
<h3 class="anchored" data-anchor-id="libraries-code-data">
Libraries, Code &amp; Data
</h3>
<p>
All the data sets used in this post can be found <a href="https://github.com/rsquaredacademy/datasets">here</a> and code can be downloaded from <a href="https://gist.github.com/rsquaredacademy/8fc6a6d21c5ab8a0a68f11df51074a9d">here</a>.
</p>
</section>
<section id="case-study-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-1">
Case Study 1
</h3>
<p>
Let us begin by combining 4 plots in 2 rows and 2 columns. The plots will be filled by rows as we are using the mfrow function:
</p>
<pre class="r"><code># store the current parameter settings in init
init &lt;- par(no.readonly=TRUE)
 
# specify that 4 graphs to be combined and filled by rows
par(mfrow = c(2, 2))
 
# specify the graphs to be combined
plot(mtcars$mpg)
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet1-1.png" width="672" style="display: block; margin: auto;">
</p>
<pre class="r"><code> 
# restore the setting stored in init
par(init)</code></pre>
</section>
<section id="case-study-2" class="level3">
<h3 class="anchored" data-anchor-id="case-study-2">
Case Study 2
</h3>
<p>
Combine 2 plots in 1 row and 2 columns.
</p>
<pre class="r"><code># store the current parameter settings in init
init &lt;- par(no.readonly=TRUE)
 
# specify that 2 graphs to be combined and filled by rows
par(mfrow = c(1, 2))
 
# specify the graphs to be combined
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet2-1.png" width="672" style="display: block; margin: auto;">
</p>
<pre class="r"><code> 
# restore the setting stored in init
par(init)</code></pre>
</section>
<section id="case-study-3" class="level3">
<h3 class="anchored" data-anchor-id="case-study-3">
Case Study 3
</h3>
<p>
Combine 2 plots in 2 rows and 1 column.
</p>
<pre class="r"><code># store the current parameter settings in init
init &lt;- par(no.readonly=TRUE)
 
# specify that 2 graphs to be combined and filled by rows
par(mfrow = c(2, 1))
 
# specify the graphs to be combined
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet3-1.png" width="672" style="display: block; margin: auto;">
</p>
<pre class="r"><code> 
# restore the setting stored in init
par(init)</code></pre>
</section>
<section id="case-study-4" class="level3">
<h3 class="anchored" data-anchor-id="case-study-4">
Case Study 4
</h3>
<p>
Combine 3 plots in 1 row and 3 columns.
</p>
<pre class="r"><code># store the current parameter settings in init
init &lt;- par(no.readonly=TRUE)
 
# specify that 3 graphs to be combined and filled by rows
par(mfrow = c(1, 3))
 
# specify the graphs to be combined
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet4-1.png" width="672" style="display: block; margin: auto;">
</p>
<pre class="r"><code> 
# restore the setting stored in init
par(init)</code></pre>
</section>
<section id="case-study-5" class="level3">
<h3 class="anchored" data-anchor-id="case-study-5">
Case Study 5
</h3>
<p>
Combine 3 plots in 3 rows and 1 column.
</p>
<pre class="r"><code># store the current parameter settings in init
init &lt;- par(no.readonly=TRUE)
 
# specify that 3 graphs to be combined and filled by rows
par(mfrow = c(3, 1))
 
# specify the graphs to be combined
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet5-1.png" width="672" style="display: block; margin: auto;">
</p>
<pre class="r"><code> 
# restore the setting stored in init
par(init)</code></pre>
</section>
<section id="mfcol" class="level3">
<h3 class="anchored" data-anchor-id="mfcol">
mfcol
</h3>
<p>
mfcol combines plots filled by columns i.e it takes two arguments, the number of rows and number of columns and then starts filling the plots by columns. Below is the syntax for mfrow:
</p>
<pre class="r"><code># mfcol syntax
mfcol(number of rows, number of columns)</code></pre>
<p>
Let us begin by combining 4 plots in 2 rows and 2 columns:
</p>
<section id="case-study-6" class="level4">
<h4 class="anchored" data-anchor-id="case-study-6">
Case Study 6
</h4>
<p>
Combine 3 plots in 3 rows and 1 column.
</p>
<pre class="r"><code># store the current parameter settings in init
init &lt;- par(no.readonly=TRUE)
 
# specify that 4 graphs to be combined and filled by columns 
par(mfcol = c(2, 2))
 
# specify the graphs to be combined
plot(mtcars$mpg)
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet6-1.png" width="672" style="display: block; margin: auto;">
</p>
<pre class="r"><code> 
# restore the setting stored in init
par(init)</code></pre>
</section>
</section>
<section id="special-cases" class="level3">
<h3 class="anchored" data-anchor-id="special-cases">
Special Cases
</h3>
<p>
What happens if we specify lesser or more number of graphs? In the next two examples, we will specify lesser or more number of graphs than we ask the par() function to combine. Let us see what happens in such instances:
</p>
<p>
Case 1: Lesser number of graphs specified We will specify that 4 plots need to be combined in 2 rows and 2 columns but provide only 3 graphs.
</p>
<p>
Case 2: Extra graph specified We will specify that 4 plots need to be combined in 2 rows and 2 columns but specify 6 graphs instead of 4.
</p>
</section>
<section id="case-study-7" class="level3">
<h3 class="anchored" data-anchor-id="case-study-7">
Case Study 7
</h3>
<pre class="r"><code># store the current parameter settings in init
init &lt;- par(no.readonly=TRUE)
 
# specify that 4 graphs to be combined and filled by rows
par(mfrow = c(2, 2))
 
# specify the graphs to be combined
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)
 
# restore the setting stored in init
par(init)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet7-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="case-study-8" class="level3">
<h3 class="anchored" data-anchor-id="case-study-8">
Case Study 8
</h3>
<pre class="r"><code># store the current parameter settings in init
init &lt;- par(no.readonly=TRUE)
 
# specify that 4 graphs to be combined and filled by rows
par(mfrow = c(2, 2))
 
# specify the graphs to be combined
plot(mtcars$mpg)
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet8-1.png" width="672" style="display: block; margin: auto;">
</p>
<pre class="r"><code>plot(mtcars$disp, mtcars$mpg)
boxplot(mtcars$mpg)

# restore the setting stored in init
par(init)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet8-2.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="layout" class="level3">
<h3 class="anchored" data-anchor-id="layout">
Layout
</h3>
<p>
At the core of the layout() function is a matrix. We communicate the structure in which the plots must be combined using a matrix. As such, the layout function is more flexible compared to the par() function.
</p>
<table class="table">
<thead>
<tr class="header">
<th align="left">
Option
</th>
<th align="left">
Description
</th>
<th align="left">
Value
</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">
matrix
</td>
<td align="left">
matrix specifying location of plants
</td>
<td align="left">
matrix
</td>
</tr>
<tr class="even">
<td align="left">
widths
</td>
<td align="left">
width of columns
</td>
<td align="left">
vector
</td>
</tr>
<tr class="odd">
<td align="left">
heights
</td>
<td align="left">
height of rows
</td>
<td align="left">
vector
</td>
</tr>
</tbody>
</table>
<p>
Let us begin by combining 4 plots in a 2 row/2 column structure. We do this by creating a layout using the matrix function.
</p>
</section>
<section id="case-study-1-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-1-1">
Case Study 1
</h3>
<p>
Combine 4 plots in 2 rows/2 columns filled by rows.
</p>
<pre class="r"><code># specify the layout
# 4 plots to be combined in 2 row/ 2 columns and arranged by row
layout(matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE))
 
# specify the 4 plots
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)
plot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet9-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="case-study-2-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-2-1">
Case Study 2
</h3>
<p>
Combine 4 plots in 2 rows/2 columns filled by columns
</p>
<p>
To fill the plots by column, we specify byrow = FALSE in the matrix.
</p>
<pre class="r"><code># specify the layout
# 4 plots to be combined in 2 row/ 2 columns and filled by columns
layout(matrix(c(1, 2, 3, 4), nrow = 2, byrow = FALSE))
 
# specify the 4 plots
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)
plot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet10-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="case-study-3-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-3-1">
Case Study 3
</h3>
<p>
Combine 3 plots in 2 rows/2 columns filled by rows
</p>
<p>
The magic of the layout() function begins here. We want to combine 3 plots and the first plot should occupy both the columns in row 1 and the next 2 plots should be in row 2. If you look at the matrix below, 1 is specified twice and since the matrix is filled by row, it will occupy both the columns in the first row. Similarly the first plot will occupy the entire first row. It will be crystal clear when you see the plot.
</p>
<pre class="r"><code># specify the matrix
matrix(c(1, 1, 2, 3), nrow = 2, byrow = TRUE)
##      [,1] [,2]
## [1,]    1    1
## [2,]    2    3

# 3 plots to be combined in 2 row/ 2 columns and arranged by row
layout(matrix(c(1, 1, 2, 3), nrow = 2, byrow = TRUE))
 
# specify the 3 plots
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet11-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="case-study-4-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-4-1">
Case Study 4
</h3>
<p>
Combine 3 plots in 2 rows/2 columns filled by rows
</p>
<p>
The plots must be filled by rows and the third plot must occupy both the columns of the second row while the other two plots will be placed in the first row. The matrix would look like this:
</p>
<pre class="r"><code># specify the matrix
matrix(c(1, 2, 3, 3), nrow = 2, byrow = TRUE)
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    3

# 3 plots to be combined in 2 row/ 2 columns and arranged by row
layout(matrix(c(1, 2, 3, 3), nrow = 2, byrow = TRUE))
 
# specify the 3 plots
hist(mtcars$mpg)
boxplot(mtcars$mpg)
plot(mtcars$disp, mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet12-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="case-study-5-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-5-1">
Case Study 5
</h3>
<p>
Combine 3 plots in 2 rows/2 columns filled by columns
</p>
<p>
The plots must be filled by columns and the first plot must occupy both the rows of the first column while the other two plots will be placed in the second column in two rows. The matrix would look like this:
</p>
<pre class="r"><code># specify the matrix
matrix(c(1, 1, 2, 3), nrow = 2, byrow = FALSE)
##      [,1] [,2]
## [1,]    1    2
## [2,]    1    3

# 3 plots to be combined in 2 row/ 2 columns and arranged by columns
layout(matrix(c(1, 1, 2, 3), nrow = 2, byrow = FALSE))
 
# specify the 3 plots
hist(mtcars$mpg)
plot(mtcars$disp, mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet13-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="case-study-6-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-6-1">
Case Study 6
</h3>
<p>
Combine 3 plots in 2 rows/2 columns filled by columns
</p>
<p>
The plots must be filled by columns and the first plot must occupy both the rows of the second column while the other two plots will be placed in the first column in two rows. The matrix would look like this:
</p>
<pre class="r"><code># specify the matrix
matrix(c(1, 2, 3, 3), nrow = 2, byrow = FALSE)
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    3

# 3 plots to be combined in 2 row/ 2 columns and arranged by columns
layout(matrix(c(1, 2, 3, 3), nrow = 2, byrow = FALSE))
 
# specify the 3 plots
boxplot(mtcars$mpg)
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet14-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="widths" class="level3">
<h3 class="anchored" data-anchor-id="widths">
Widths
</h3>
<p>
In all the layouts created so far, we have kept the size of the rows and columns equal. What if you want to modify the width and height of the columns and rows? The widths and heights arguments in the layout() function address the above mentioned issue. Let us check them out one by one: The widths argument is used for specifying the width of the columns. Based on the number of columns in the layout, you can specify the width of each column. Let us look at some examples.
</p>
</section>
<section id="case-study-7-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-7-1">
Case Study 7
</h3>
<p>
Width of the 2nd column is twice the width of the 1st column
</p>
<pre class="r"><code># specify the matrix
matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4

# 4 plots to be combined in 2 row/ 2 columns and arranged by columns
layout(matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE), widths = c(1, 3))
 
# specify the plots
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)
plot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet15-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="case-study-8-1" class="level3">
<h3 class="anchored" data-anchor-id="case-study-8-1">
Case Study 8
</h3>
<p>
Width of the 2nd column is twice that of the first and last column
</p>
<pre class="r"><code># specify the matrix
matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6

# 6 plots to be combined in 2 row/ 3 columns and filled by rows
layout(matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE), widths = c(1, 2, 1))
 
# specify the plots
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)
plot(mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet16-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="heights" class="level3">
<h3 class="anchored" data-anchor-id="heights">
Heights
</h3>
<p>
The heights arguments is used to modify the height of the rows and based on the number of rows specified in the layout, we can specify the height of each row.
</p>
</section>
<section id="case-study-9" class="level3">
<h3 class="anchored" data-anchor-id="case-study-9">
Case Study 9
</h3>
<p>
Height of the 2nd row is twice that of the first row
</p>
<pre class="r"><code># 4 plots to be combined in 2 row/ 2 columns and filled by rows
layout(matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE), heights= c(1, 2))
 
# specify the 4 plots
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)
plot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet17-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>
<section id="putting-it-all-together" class="level3">
<h3 class="anchored" data-anchor-id="putting-it-all-together">
Putting it all together…
</h3>
<p>
Before we end this section, let us combine plots using both the widths and heights option
</p>
<pre class="r"><code># specify the matrix
matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, byrow = TRUE)
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4
## [3,]    5    6

# 6 plots to be combined in 3 row/ 2 columns and arranged by rows
layout(matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, byrow = TRUE), heights= c(1, 2, 1),
widths = c(2, 1))
 
# specify the 6 plots
plot(mtcars$disp, mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)
plot(mtcars$mpg)
hist(mtcars$mpg)
boxplot(mtcars$mpg)</code></pre>
<p>
<img src="https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/2017-09-09-data-visualization-with-r-combining-plots_files/figure-html/facet18-1.png" width="672" style="display: block; margin: auto;">
</p>
</section>



 ]]></description>
  <category>data-visualization</category>
  <guid>https://blog.rsquaredacademy.com/posts/data-visualization-with-r-combining-plots/</guid>
  <pubDate>Sat, 09 Sep 2017 00:00:00 GMT</pubDate>
  <media:content url="https://blog.rsquaredacademy.com/img/viz_facet.png" medium="image" type="image/png" height="89" width="144"/>
</item>
</channel>
</rss>
