<?xml version="1.0" encoding="UTF-8" ?>
<!-- RSS generated by PHPBoost on Wed, 29 Apr 2026 01:57:39 +0200 -->

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Easy Guides]]></title>
		<atom:link href="https://www.sthda.com/english/syndication/rss/wiki/27" rel="self" type="application/rss+xml"/>
		<link>https://www.sthda.com</link>
		<description><![CDATA[Last articles of the category: ggplot2 - Essentials]]></description>
		<copyright>(C) 2005-2026 PHPBoost</copyright>
		<language>en</language>
		<generator>PHPBoost</generator>
		
		
		<item>
			<title><![CDATA[ggplot2 texts : Add text annotations to a graph in R software]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-texts-add-text-annotations-to-a-graph-in-r-software</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-texts-add-text-annotations-to-a-graph-in-r-software</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#install-required-packages">Install required packages</a></li>
<li><a href="#create-some-data">Create some data</a></li>
<li><a href="#text-annotations-using-geom_text-and-geom_label">Text annotations using geom_text and geom_label</a></li>
<li><a href="#change-the-text-color-and-size-by-groups">Change the text color and size by groups</a></li>
<li><a href="#add-a-text-annotation-at-a-particular-coordinate">Add a text annotation at a particular coordinate</a></li>
<li><a href="#annotation_custom-add-a-static-text-annotation-in-the-top-right-top-left">annotation_custom : Add a static text annotation in the top-right, top-left, …</a></li>
<li><a href="#ggrepel-avoid-overlapping-of-text-labels">ggrepel: Avoid overlapping of text labels</a><ul>
<li><a href="#scatter-plots-with-text-annotations">Scatter plots with text annotations</a></li>
<li><a href="#volcano-plot">Volcano plot</a></li>
</ul></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>This article describes how to <strong>add a text</strong> annotation to a plot generated using <strong>ggplot2</strong> package.</p>
<p>The functions below can be used :</p>
<ul>
<li><strong>geom_text</strong>(): adds text directly to the plot</li>
<li><strong>geom_label</strong>(): draws a rectangle underneath the text, making it easier to read.</li>
<li><strong>annotate</strong>(): useful for adding small text annotations at a particular location on the plot</li>
<li><strong>annotation_custom</strong>(): Adds static annotations that are the same in every panel</li>
</ul>
<p>It’s also possible to use the R package <strong>ggrepel</strong>, which is an extension and provides <strong>geom</strong> for ggplot2 to repel <strong>overlapping text</strong> labels away from each other.</p>
<p><span class="success">We’ll start by describing how to use ggplot2 official functions for adding text annotations. In the last sections, examples using <strong>ggrepel</strong> extensions are provided.</span></p>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="install-required-packages" class="section level1">
<h1>Install required packages</h1>
<pre class="r"><code># Install ggplot2
install.packages("ggplot2")
# Install ggrepel
install.packages("ggrepel")</code></pre>
</div>
<div id="create-some-data" class="section level1">
<h1>Create some data</h1>
<p>We’ll use a subset of mtcars data. The function <strong>sample</strong>() can be used to randomly extract 10 rows:</p>
<pre class="r"><code># Subset 10 rows
set.seed(1234)
ss <- sample(1:32, 10)
df <- mtcars[ss, ]</code></pre>
</div>
<div id="text-annotations-using-geom_text-and-geom_label" class="section level1">
<h1>Text annotations using geom_text and geom_label</h1>
<pre class="r"><code>library(ggplot2)
# Simple scatter plot
sp <- ggplot(df, aes(wt, mpg, label = rownames(df)))+
  geom_point()
 
# Add texts
sp + geom_text()
# Change the size of the texts
sp + geom_text(size=6)
# Change vertical and horizontal adjustement
sp +  geom_text(hjust=0, vjust=0)
# Change fontface. Allowed values : 1(normal),
# 2(bold), 3(italic), 4(bold.italic)
sp + geom_text(aes(fontface=2))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-3.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-4.png" width="240" /></p>
<ul>
<li>Change font family</li>
</ul>
<pre class="r"><code>sp + geom_text(family = "Times New Roman")</code></pre>
<ul>
<li><strong>geom_label</strong>() works like <strong>geom_text</strong>() but draws a rounded rectangle underneath each label. This is useful when you want to label plots that are dense with data.</li>
</ul>
<pre class="r"><code>sp + geom_label()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom_label-1.png" width="288" /></p>
<br/>
<div class="block">
<p>Others useful arguments for <strong>geom_text</strong>() and <strong>geom_label</strong>() are:</p>
<ul>
<li><strong>nudge_x</strong> and <strong>nudge_y</strong>: let you offset labels from their corresponding points. The function <strong>position_nudge</strong>() can be also used.</li>
<li><strong>check_overlap</strong> = TRUE: for avoiding overplotting of labels</li>
<li><strong>hjust</strong> and <strong>vjust</strong> can now be character vectors (ggplot2 v >= 2.0.0): “left”, “center”, “right”, “bottom”, “middle”, “top”. New options include “inward” and “outward” which align text towards and away from the center of the plot respectively.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="change-the-text-color-and-size-by-groups" class="section level1">
<h1>Change the text color and size by groups</h1>
<p>It’s possible to change the appearance of the texts using aesthetics (color, size,…) :</p>
<pre class="r"><code>sp2 <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars)))+
  geom_point()
# Color by groups
sp2 + geom_text(aes(color=factor(cyl)))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-appearance-1.png" width="384" /></p>
<pre class="r"><code># Set the size of the text using a continuous variable
sp2 + geom_text(aes(size=wt))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-appearance-2.png" width="384" /></p>
<pre class="r"><code># Define size range
sp2 + geom_text(aes(size=wt)) + scale_size(range=c(3,6))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-appearance-3.png" width="384" /></p>
</div>
<div id="add-a-text-annotation-at-a-particular-coordinate" class="section level1">
<h1>Add a text annotation at a particular coordinate</h1>
<p>The functions <strong>geom_text()</strong> and <strong>annotate()</strong> can be used :</p>
<pre class="r"><code># Solution 1
sp2 + geom_text(x=3, y=30, label="Scatter plot")
# Solution 2
sp2 + annotate(geom="text", x=3, y=30, label="Scatter plot",
              color="red")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-annotation-coordinate-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-geom-text-annotation-coordinate-2.png" width="192" /></p>
</div>
<div id="annotation_custom-add-a-static-text-annotation-in-the-top-right-top-left" class="section level1">
<h1>annotation_custom : Add a static text annotation in the top-right, top-left, …</h1>
<p>The functions <strong>annotation_custom()</strong> and <strong>textGrob()</strong> are used to add static annotations which are the same in every panel.The <em>grid</em> package is required :</p>
<pre class="r"><code>library(grid)
# Create a text
grob <- grobTree(textGrob("Scatter plot", x=0.1,  y=0.95, hjust=0,
  gp=gpar(col="red", fontsize=13, fontface="italic")))
# Plot
sp2 + annotation_custom(grob)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-text-grob-1.png" width="192" /></p>
<p><strong>Facet</strong> : In the plot below, the annotation is at the same place (in each facet) even if the axis scales vary.</p>
<pre class="r"><code>sp2 + annotation_custom(grob)+facet_wrap(~cyl, scales="free")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-annotation-custom-faceting-1.png" width="480" /></p>
</div>
<div id="ggrepel-avoid-overlapping-of-text-labels" class="section level1">
<h1>ggrepel: Avoid overlapping of text labels</h1>
<p>There are two important functions in <strong>ggrepel</strong> R packages:</p>
<ul>
<li><strong>geom_label_repel</strong>()</li>
<li><strong>geom_text_repel</strong>()</li>
</ul>
<div id="scatter-plots-with-text-annotations" class="section level2">
<h2>Scatter plots with text annotations</h2>
<p>We start by creating a simple scatter plot using a subset of the <em>mtcars</em> data set containing 15 rows.</p>
<ol style="list-style-type: decimal">
<li><strong>Prepare some data</strong>:</li>
</ol>
<pre class="r"><code># Take a subset of 15 random points
set.seed(1234)
ss <- sample(1:32, 15)
df <- mtcars[ss, ]</code></pre>
<ol start="2" style="list-style-type: decimal">
<li><strong>Create a scatter plot</strong>:</li>
</ol>
<pre class="r"><code>p <- ggplot(df, aes(wt, mpg)) +
  geom_point(color = 'red') +
  theme_classic(base_size = 10)</code></pre>
<ol start="3" style="list-style-type: decimal">
<li><strong>Add text labels</strong>:</li>
</ol>
<pre class="r"><code># Add text annotations using ggplot2::geom_text
p + geom_text(aes(label = rownames(df)),
              size = 3.5)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-ggrepel-1.png" width="537.6" /></p>
<pre class="r"><code># Use ggrepel::geom_text_repel
require("ggrepel")
set.seed(42)
p + geom_text_repel(aes(label = rownames(df)),
                    size = 3.5) </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-ggrepel-2.png" width="537.6" /></p>
<pre class="r"><code># Use ggrepel::geom_label_repel and 
# Change color by groups
set.seed(42)
p + geom_label_repel(aes(label = rownames(df),
                    fill = factor(cyl)), color = 'white',
                    size = 3.5) +
   theme(legend.position = "bottom")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-ggrepel-3.png" width="537.6" /></p>
</div>
<div id="volcano-plot" class="section level2">
<h2>Volcano plot</h2>
<pre class="r"><code>genes <- read.table("https://gist.githubusercontent.com/stephenturner/806e31fce55a8b7175af/raw/1a507c4c3f9f1baaa3a69187223ff3d3050628d4/results.txt", header = TRUE)
genes$Significant <- ifelse(genes$padj < 0.05, "FDR < 0.05", "Not Sig")
ggplot(genes, aes(x = log2FoldChange, y = -log10(pvalue))) +
  geom_point(aes(color = Significant)) +
  scale_color_manual(values = c("red", "grey")) +
  theme_bw(base_size = 12) + theme(legend.position = "bottom") +
  geom_text_repel(
    data = subset(genes, padj < 0.05),
    aes(label = Gene),
    size = 5,
    box.padding = unit(0.35, "lines"),
    point.padding = unit(0.3, "lines")
  )</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-text-volcano-plot-1.png" width="537.6" /></p>
<p><a href="http://www.gettinggeneticsdone.com/2016/01/repel-overlapping-text-labels-in-ggplot2.html">source</a></p>
</div>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning">This analysis has been performed using <strong>R software</strong> (ver. 3.2.4) and <strong>ggplot2</strong> (ver. )</span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:54:07 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[ggplot2 density plot : Quick start guide - R software and data visualization]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-density-plot-quick-start-guide-r-software-and-data-visualization</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-density-plot-quick-start-guide-r-software-and-data-visualization</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#prepare-the-data">Prepare the data</a></li>
<li><a href="#basic-density-plots">Basic density plots</a></li>
<li><a href="#change-density-plot-line-types-and-colors">Change density plot line types and colors</a></li>
<li><a href="#change-density-plot-colors-by-groups">Change density plot colors by groups</a><ul>
<li><a href="#calculate-the-mean-of-each-group">Calculate the mean of each group :</a></li>
<li><a href="#change-line-colors">Change line colors</a></li>
<li><a href="#change-fill-colors">Change fill colors</a></li>
</ul></li>
<li><a href="#change-the-legend-position">Change the legend position</a></li>
<li><a href="#combine-histogram-and-density-plots">Combine histogram and density plots</a></li>
<li><a href="#use-facets">Use facets</a></li>
<li><a href="#customized-density-plots">Customized density plots</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>This <strong>R tutorial</strong> describes how to create a <strong>density plot</strong> using <strong>R software</strong> and <strong>ggplot2</strong> package.</p>
<p>The function <strong>geom_density()</strong> is used. You can also add a line for the mean using the function <a href="https://www.sthda.com/english/english/wiki/ggplot2-add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines">geom_vline</a>.</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-logo-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="384" /></p>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="prepare-the-data" class="section level1">
<h1>Prepare the data</h1>
<p>This data will be used for the examples below :</p>
<pre class="r"><code>set.seed(1234)
df <- data.frame(
  sex=factor(rep(c("F", "M"), each=200)),
  weight=round(c(rnorm(200, mean=55, sd=5),
                 rnorm(200, mean=65, sd=5)))
  )
head(df)</code></pre>
<pre><code>##   sex weight
## 1   F     49
## 2   F     56
## 3   F     60
## 4   F     43
## 5   F     57
## 6   F     58</code></pre>
</div>
<div id="basic-density-plots" class="section level1">
<h1>Basic density plots</h1>
<pre class="r"><code>library(ggplot2)
# Basic density
p <- ggplot(df, aes(x=weight)) + 
  geom_density()
p
# Add mean line
p+ geom_vline(aes(xintercept=mean(weight)),
            color="blue", linetype="dashed", size=1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-basic-density-plot-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-basic-density-plot-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="192" /></p>
</div>
<div id="change-density-plot-line-types-and-colors" class="section level1">
<h1>Change density plot line types and colors</h1>
<pre class="r"><code># Change line color and fill color
ggplot(df, aes(x=weight))+
  geom_density(color="darkblue", fill="lightblue")
# Change line type
ggplot(df, aes(x=weight))+
  geom_density(linetype="dashed")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-change-color-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-change-color-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="192" /></p>
<p>Read more on ggplot2 line types : <a href="https://www.sthda.com/english/english/wiki/ggplot2-qq-plot-quantile-quantile-graph-r-software-and-data-visualization">ggplot2 line types</a></p>
</div>
<div id="change-density-plot-colors-by-groups" class="section level1">
<h1>Change density plot colors by groups</h1>
<div id="calculate-the-mean-of-each-group" class="section level2">
<h2>Calculate the mean of each group :</h2>
<pre class="r"><code>library(plyr)
mu <- ddply(df, "sex", summarise, grp.mean=mean(weight))
head(mu)</code></pre>
<pre><code>##   sex grp.mean
## 1   F    54.70
## 2   M    65.36</code></pre>
</div>
<div id="change-line-colors" class="section level2">
<h2>Change line colors</h2>
<p>Density plot line colors can be automatically controlled by the levels of <em>sex</em> :</p>
<pre class="r"><code># Change density plot line colors by groups
ggplot(df, aes(x=weight, color=sex)) +
  geom_density()
# Add mean lines
p<-ggplot(df, aes(x=weight, color=sex)) +
  geom_density()+
  geom_vline(data=mu, aes(xintercept=grp.mean, color=sex),
             linetype="dashed")
p</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-change-group-colors-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-change-group-colors-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /></p>
<p>It is also possible to <em>change manually density plot line colors</em> using the functions :</p>
<ul>
<li><em>scale_color_manual()</em> : to use custom colors</li>
<li><em>scale_color_brewer()</em> : to use color palettes from <em>RColorBrewer</em> package</li>
<li><em>scale_color_grey()</em> : to use grey color palettes</li>
</ul>
<pre class="r"><code># Use custom color palettes
p+scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))
# Use brewer color palettes
p+scale_color_brewer(palette="Dark2")
# Use grey scale
p + scale_color_grey() + theme_classic()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-manual-color-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-manual-color-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-manual-color-data-visualization-3.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /></p>
<p>Read more on ggplot2 colors here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually">ggplot2 colors</a></p>
</div>
<div id="change-fill-colors" class="section level2">
<h2>Change fill colors</h2>
<p>Density plot fill colors can be automatically controlled by the levels of <em>sex</em> :</p>
<pre class="r"><code># Change density plot fill colors by groups
ggplot(df, aes(x=weight, fill=sex)) +
  geom_density()
# Use semi-transparent fill
p<-ggplot(df, aes(x=weight, fill=sex)) +
  geom_density(alpha=0.4)
p
# Add mean lines
p+geom_vline(data=mu, aes(xintercept=grp.mean, color=sex),
             linetype="dashed")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-change-group-fill-colors-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-change-group-fill-colors-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-change-group-fill-colors-data-visualization-3.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /></p>
<p>It is also possible to change manually density plot fill colors using the functions :</p>
<ul>
<li><em>scale_fill_manual()</em> : to use custom colors</li>
<li><em>scale_fill_brewer()</em> : to use color palettes from <em>RColorBrewer</em> package</li>
<li><em>scale_fill_grey()</em> : to use grey color palettes</li>
</ul>
<pre class="r"><code># Use custom color palettes
p+scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"))
# use brewer color palettes
p+scale_fill_brewer(palette="Dark2")
# Use grey scale
p + scale_fill_grey() + theme_classic()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-manual-fill-color-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-manual-fill-color-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-manual-fill-color-data-visualization-3.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /></p>
<p>Read more on ggplot2 colors here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually">ggplot2 colors</a></p>
</div>
</div>
<div id="change-the-legend-position" class="section level1">
<h1>Change the legend position</h1>
<pre class="r"><code>p + theme(legend.position="top")
p + theme(legend.position="bottom")
p + theme(legend.position="none") # Remove legend</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-legend-position-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-legend-position-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-legend-position-data-visualization-3.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="240" /></p>
<p><span class="success">The allowed values for the arguments <strong>legend.position</strong> are : “left”,“top”, “right”, “bottom”.</span></p>
<p>Read more on ggplot legends : <a href="https://www.sthda.com/english/english/wiki/ggplot2-legend-easy-steps-to-change-the-position-and-the-appearance-of-a-graph-legend-in-r-software">ggplot2 legends</a></p>
</div>
<div id="combine-histogram-and-density-plots" class="section level1">
<h1>Combine histogram and density plots</h1>
<ul>
<li>The histogram is plotted with density instead of count values on y-axis</li>
<li>Overlay with transparent density plot</li>
</ul>
<pre class="r"><code># Histogram with density plot
ggplot(df, aes(x=weight)) + 
 geom_histogram(aes(y=..density..), colour="black", fill="white")+
 geom_density(alpha=.2, fill="#FF6666") 
# Color by groups
ggplot(df, aes(x=weight, color=sex, fill=sex)) + 
 geom_histogram(aes(y=..density..), alpha=0.5, 
                position="identity")+
 geom_density(alpha=.2) </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-histogram-and-density-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-histogram-and-density-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="259.2" /></p>
</div>
<div id="use-facets" class="section level1">
<h1>Use facets</h1>
<p>Split the plot in multiple panels :</p>
<pre class="r"><code>p<-ggplot(df, aes(x=weight))+
  geom_density()+facet_grid(sex ~ .)
p
# Add mean lines
p+geom_vline(data=mu, aes(xintercept=grp.mean, color="red"),
             linetype="dashed")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-facet-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-facet-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="192" /></p>
<p>Read more on facets : <a href="https://www.sthda.com/english/english/wiki/ggplot2-facet-split-a-plot-into-a-matrix-of-panels">ggplot2 facets</a></p>
</div>
<div id="customized-density-plots" class="section level1">
<h1>Customized density plots</h1>
<pre class="r"><code># Basic density
ggplot(df, aes(x=weight, fill=sex)) +
  geom_density(fill="gray")+
  geom_vline(aes(xintercept=mean(weight)), color="blue",
             linetype="dashed")+
  labs(title="Weight density curve",x="Weight(kg)", y = "Density")+
  theme_classic()
# Change line colors by groups
p<- ggplot(df, aes(x=weight, color=sex)) +
  geom_density()+
  geom_vline(data=mu, aes(xintercept=grp.mean, color=sex),
             linetype="dashed")+
  labs(title="Weight density curve",x="Weight(kg)", y = "Density")
  
p + scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))+
  theme_classic()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-customized-density-plot-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-customized-density-plot-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="259.2" /></p>
<p>Change line colors manually :</p>
<pre class="r"><code># Continuous colors
p + scale_color_brewer(palette="Paired") + theme_classic()
# Discrete colors
p + scale_color_brewer(palette="Dark2") + theme_minimal()
# Gradient colors
p + scale_color_brewer(palette="Accent") + theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-customized-change-color-data-visualization-1.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-customized-change-color-data-visualization-2.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-density-customized-change-color-data-visualization-3.png" title="ggplot2 density - R software and data visualization" alt="ggplot2 density - R software and data visualization" width="259.2" /></p>
<p>Read more on ggplot2 colors here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually">ggplot2 colors</a></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>ggplot2</strong> (ver. 1.0.0) </span></p>
</div>
<script>jQuery(document).ready(function () {
  jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:53:03 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Be Awesome in ggplot2: A Practical Guide to be Highly Effective - R software and data visualization]]></title>
			<link>https://www.sthda.com/english/wiki/be-awesome-in-ggplot2-a-practical-guide-to-be-highly-effective-r-software-and-data-visualization</link>
			<guid>https://www.sthda.com/english/wiki/be-awesome-in-ggplot2-a-practical-guide-to-be-highly-effective-r-software-and-data-visualization</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="basics" class="section level1">
<h1>Basics</h1>
<p><strong>ggplot2</strong> is a powerful and a flexible <strong>R package</strong>, implemented by <strong>Hadley Wickham</strong>, for producing elegant graphics. The <strong>gg</strong> in ggplot2 means <strong>Grammar of Graphics</strong>, a graphic concept which describes plots by using a “grammar”.</p>
<p>According to ggplot2 concept, a plot can be divided into different fundamental parts : <strong>Plot = data + Aesthetics + Geometry</strong>.</p>
<p>The principal components of every plot can be defined as follow:</p>
<ul>
<li><strong>data</strong> is a data frame
</li>
<li><strong>Aesthetics</strong> is used to indicate x and y variables. It can also be used to control the <strong>color</strong>, the <strong>size</strong> or the <strong>shape</strong> of points, the height of bars, etc…..
</li>
<li><strong>Geometry</strong> corresponds to the type of graphics (<strong>histogram</strong>, <strong>box plot</strong>, <strong>line plot</strong>, <strong>density plot</strong>, <strong>dot plot</strong>, ….)</li>
</ul>
<p>Two main functions, for creating plots, are available in <strong>ggplot2</strong> package : a <strong>qplot()</strong> and <strong>ggplot()</strong> functions.</p>
<ul>
<li><strong>qplot()</strong> is a quick plot function which is easy to use for simple plots.</li>
<li>The <strong>ggplot()</strong> function is more flexible and robust than <strong>qplot</strong> for building a plot piece by piece.</li>
</ul>
<p>The generated plot can be kept as a variable and then printed at any time using the function <strong>print</strong>().</p>
<p>After creating plots, two other important functions are:</p>
<ul>
<li><strong>last_plot()</strong>, which returns the last plot to be modified</li>
<li><strong>ggsave(“plot.png”, width = 5, height = 5)</strong>, which saves the last plot in the current working directory.</li>
</ul>
<p><span class="success">This document describes how to create and customize different types of graphs using ggplot2. Many examples of code and graphics are provided.</span></p>
</div>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="types-of-graphs-for-data-visualization" class="section level1">
<h1>Types of graphs for data visualization</h1>
<p>The type of plots, to be created, depends on the format of your data. The ggplot2 package provides methods for visualizing the following data structures:</p>
<ol style="list-style-type: decimal">
<li><strong>One variable - x</strong>: continuous or discrete</li>
<li><strong>Two variables - x &amp; y</strong>: continuous and/or discrete</li>
<li><strong>Continuous bivariate distribution - x &amp; y</strong> (both continuous)</li>
<li><strong>Continuous function</strong></li>
<li><strong>Error bar</strong></li>
<li><strong>Maps</strong></li>
<li><strong>Three variables</strong></li>
</ol>
<p>In the current document we’ll provide the essential ggplot2 functions for drawing each of these seven data formats.</p>
</div>
<div id="how-this-document-is-organized" class="section level1">
<h1>How this document is organized?</h1>
<div id="TOC">
<ul>
<li><a href="#basics">Basics</a></li>
<li><a href="#types-of-graphs-for-data-visualization">Types of graphs for data visualization</a></li>
<li><a href="#how-this-document-is-organized">How this document is organized?</a></li>
<li><a href="#install-and-load-ggplot2-package">Install and load ggplot2 package</a></li>
<li><a href="#data-format-and-preparation">Data format and preparation</a></li>
<li><a href="#qplot-quick-plot-with-ggplot2">qplot(): Quick plot with ggplot2</a><ul>
<li><a href="#scatter-plots">Scatter plots</a></li>
<li><a href="#box-plot-violin-plot-and-dot-plot">Box plot, violin plot and dot plot</a></li>
<li><a href="#histogram-and-density-plots">Histogram and density plots</a></li>
</ul></li>
<li><a href="#ggplot-build-plots-piece-by-piece">ggplot(): build plots piece by piece</a><ul>
<li><a href="#one-variable-continuous">One variable: Continuous</a><ul>
<li><a href="#geom_area-create-an-area-plot">geom_area(): Create an area plot</a></li>
<li><a href="#geom_density-create-a-smooth-density-estimate">geom_density(): Create a smooth density estimate</a></li>
<li><a href="#geom_dotplot-dot-plot">geom_dotplot(): Dot plot</a></li>
<li><a href="#geom_freqpoly-frequency-polygon">geom_freqpoly(): Frequency polygon</a></li>
<li><a href="#geom_histogram-histogram">geom_histogram(): Histogram</a></li>
<li><a href="#stat_ecdf-empirical-cumulative-density-function">stat_ecdf(): Empirical Cumulative Density Function</a></li>
<li><a href="#stat_qq-quantile---quantile-plot">stat_qq(): quantile - quantile plot</a></li>
</ul></li>
<li><a href="#one-variable-discrete">One variable: Discrete</a></li>
<li><a href="#two-variables-continuous-x-continuous-y">Two variables: Continuous X, Continuous Y</a><ul>
<li><a href="#geom_point-scatter-plot">geom_point(): Scatter plot</a></li>
<li><a href="#geom_smooth-add-regression-line-or-smoothed-conditional-mean">geom_smooth(): Add regression line or smoothed conditional mean</a></li>
<li><a href="#geom_quantile-add-quantile-lines-from-a-quantile-regression">geom_quantile(): Add quantile lines from a quantile regression</a></li>
<li><a href="#geom_rug-add-marginal-rug-to-scatter-plots">geom_rug(): Add marginal rug to scatter plots</a></li>
<li><a href="#geom_jitter-jitter-points-to-reduce-overplotting">geom_jitter(): Jitter points to reduce overplotting</a></li>
<li><a href="#geom_text-textual-annotations">geom_text(): Textual annotations</a></li>
</ul></li>
<li><a href="#two-variables-continuous-bivariate-distribution">Two variables: Continuous bivariate distribution</a><ul>
<li><a href="#geom_bin2d-add-heatmap-of-2d-bin-counts">geom_bin2d(): Add heatmap of 2d bin counts</a></li>
<li><a href="#geom_hex-add-hexagon-bining">geom_hex(): Add hexagon bining</a></li>
<li><a href="#geom_density_2d-add-contours-from-a-2d-density-estimate">geom_density_2d(): Add contours from a 2d density estimate</a></li>
</ul></li>
<li><a href="#two-variables-continuous-function">Two variables: Continuous function</a></li>
<li><a href="#two-variables-discrete-x-continuous-y">Two variables: Discrete X, Continuous Y</a><ul>
<li><a href="#geom_boxplot-box-and-whiskers-plot">geom_boxplot(): Box and whiskers plot</a></li>
<li><a href="#geom_violin-violin-plot">geom_violin(): Violin plot</a></li>
<li><a href="#geom_dotplot-dot-plot-1">geom_dotplot(): Dot plot</a></li>
<li><a href="#geom_jitter-strip-charts">geom_jitter(): Strip charts</a></li>
<li><a href="#geom_line-line-plot">geom_line(): Line plot</a></li>
<li><a href="#geom_bar-bar-plot">geom_bar(): Bar plot</a></li>
</ul></li>
<li><a href="#two-variables-discrete-x-discrete-y">Two variables: Discrete X, Discrete Y</a></li>
<li><a href="#two-variables-visualizing-error">Two variables: Visualizing error</a><ul>
<li><a href="#geom_crossbar-hollow-bar-with-middle-indicated-by-horizontal-line">geom_crossbar(): Hollow bar with middle indicated by horizontal line</a></li>
<li><a href="#geom_errorbar-error-bars">geom_errorbar(): Error bars</a></li>
<li><a href="#geom_errorbarh-horizontal-error-bars">geom_errorbarh(): Horizontal error bars</a></li>
<li><a href="#geom_linerange-and-geom_pointrange-an-interval-represented-by-a-vertical-line">geom_linerange() and geom_pointrange(): An interval represented by a vertical line</a></li>
<li><a href="#combine-geom_dotplot-and-error-bars">Combine geom_dotplot and error bars</a></li>
</ul></li>
<li><a href="#two-variables-maps">Two variables: Maps</a></li>
<li><a href="#three-variables">Three variables</a></li>
<li><a href="#other-types-of-graphs">Other types of graphs</a></li>
<li><a href="#graphical-primitives-polygon-path-ribbon-segment-rectangle">Graphical primitives: polygon, path, ribbon, segment, rectangle</a></li>
</ul></li>
<li><a href="#graphical-parameters">Graphical parameters</a><ul>
<li><a href="#main-title-axis-labels-and-legend-title">Main title, axis labels and legend title</a></li>
<li><a href="#legend-position-and-appearance">Legend position and appearance</a></li>
<li><a href="#change-colors-automatically-and-manually">Change colors automatically and manually</a></li>
<li><a href="#point-shapes-colors-and-size">Point shapes, colors and size</a></li>
<li><a href="#add-text-annotations-to-a-graph">Add text annotations to a graph</a></li>
<li><a href="#line-types">Line types</a></li>
<li><a href="#themes-and-background-colors">Themes and background colors</a></li>
<li><a href="#axis-limits-minimum-and-maximum-values">Axis limits: Minimum and Maximum values</a></li>
<li><a href="#axis-transformations-log-and-sqrt-scales">Axis transformations: log and sqrt scales</a></li>
<li><a href="#axis-ticks-customize-tick-marks-and-labels-reorder-and-select-items">Axis ticks: customize tick marks and labels, reorder and select items</a></li>
<li><a href="#add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines">Add straight lines to a plot: horizontal, vertical and regression lines</a></li>
<li><a href="#rotate-a-plot-flip-and-reverse">Rotate a plot: flip and reverse</a></li>
<li><a href="#faceting-split-a-plot-into-a-matrix-of-panels">Faceting: split a plot into a matrix of panels</a></li>
<li><a href="#position-adjustements">Position adjustements</a></li>
<li><a href="#coordinate-systems">Coordinate systems</a></li>
</ul></li>
<li><a href="#extensions-to-ggplot2-r-packages-and-functions">Extensions to ggplot2: R packages and functions</a></li>
<li><a href="#ressources-to-improve-your-ggplot2-skills">Ressources to improve your ggplot2 skills</a><ul>
<li><a href="#books">Books</a></li>
<li><a href="#blog-posts">Blog posts</a></li>
<li><a href="#cheat-sheets">Cheat Sheets</a></li>
</ul></li>
<li><a href="#acknoweledgment">Acknoweledgment</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
</div>
<div id="install-and-load-ggplot2-package" class="section level1">
<h1>Install and load ggplot2 package</h1>
<p>Use the <strong>R</strong> code below:</p>
<pre class="r"><code># Installation
install.packages('ggplot2')
# Loading
library(ggplot2)</code></pre>
</div>
<div id="data-format-and-preparation" class="section level1">
<h1>Data format and preparation</h1>
<p><span class="warning">The data should be a <strong>data.frame</strong> (columns are variables and rows are observations).</span></p>
<p>The data set <strong>mtcars</strong> is used in the examples below:</p>
<pre class="r"><code># Load the data
data(mtcars)
df <- mtcars[, c("mpg", "cyl", "wt")]
# Convert cyl to a factor variable
df$cyl <- as.factor(df$cyl)
head(df)</code></pre>
<pre><code>##                    mpg cyl    wt
## Mazda RX4         21.0   6 2.620
## Mazda RX4 Wag     21.0   6 2.875
## Datsun 710        22.8   4 2.320
## Hornet 4 Drive    21.4   6 3.215
## Hornet Sportabout 18.7   8 3.440
## Valiant           18.1   6 3.460</code></pre>
<br/>
<div class="block">
<p><strong>mtcars : Motor Trend Car Road Tests.</strong></p>
<p><strong>Description</strong>: The data comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973 - 74 models).</p>
<p><strong>Format</strong>: A data frame with 32 observations on 3 variables.</p>
<ul>
<li>[, 1] mpg Miles/(US) gallon</li>
<li>[, 2] cyl Number of cylinders</li>
<li>[, 3] wt Weight (lb/1000)</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="qplot-quick-plot-with-ggplot2" class="section level1">
<h1>qplot(): Quick plot with ggplot2</h1>
<p>The <strong>qplot()</strong> function is very similar to the standard <strong>R</strong> <strong>plot()</strong> function. It can be used to create quickly and easily different types of graphs: <strong>scatter plots</strong>, <strong>box plots</strong>, <strong>violin plots</strong>, <strong>histogram</strong> and <strong>density plots</strong>.</p>
<p>A simplified format of <strong>qplot()</strong> is :</p>
<pre class="r"><code>qplot(x, y = NULL, data, geom="auto")</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x, y</strong> : x and y values, respectively. The argument y is optional depending on the type of graphs to be created.</li>
<li><strong>data</strong> : data frame to use (optional).</li>
<li><strong>geom</strong> : Character vector specifying geom to use. Defaults to “point” if x and y are specified, and “histogram” if only x is specified.</li>
</ul>
</div>
<p><br/></p>
<p>Other arguments such as <em>main</em>, <em>xlab</em> and <em>ylab</em> can be also used to add main title and axis labels to the plot.</p>
<p><span class="success">Read more about <strong>qplot()</strong>: <a href="https://www.sthda.com/english/english/wiki/qplot-quick-plot-with-ggplot2-r-software-and-data-visualization">Quick plot with ggplot2</a>.</span></p>
<div id="scatter-plots" class="section level2">
<h2>Scatter plots</h2>
<p>The R code below creates basic <strong>scatter plots</strong> using the argument <strong>geom = “point”</strong>. It’s also possible to combine different geoms (e.g.: <strong>geom = c(“point”, “smooth”)</strong>).</p>
<pre class="r"><code># Basic scatter plot
qplot(x = mpg, y = wt, data = df, geom = "point")
# Scatter plot with smoothed line
qplot(mpg, wt, data = df, 
      geom = c("point", "smooth"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scatter-plots-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scatter-plots-2.png" width="192" /></p>
<p>The following R code will change the <strong>color</strong> and the <strong>shape</strong> of points by groups. The column <em>cyl</em> will be used as grouping variable. In other words, the color and the shape of points will be changed by the levels of <em>cyl</em>.</p>
<pre class="r"><code>qplot(mpg, wt, data = df, colour = cyl, shape = cyl)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scatter-plot-color-shape-1.png" width="288" /></p>
</div>
<div id="box-plot-violin-plot-and-dot-plot" class="section level2">
<h2>Box plot, violin plot and dot plot</h2>
<p>The R code below generates some data containing the weights by sex (M for male; F for female):</p>
<pre class="r"><code>set.seed(1234)
wdata = data.frame(
        sex = factor(rep(c("F", "M"), each=200)),
        weight = c(rnorm(200, 55), rnorm(200, 58)))
head(wdata)</code></pre>
<pre><code>##   sex   weight
## 1   F 53.79293
## 2   F 55.27743
## 3   F 56.08444
## 4   F 52.65430
## 5   F 55.42912
## 6   F 55.50606</code></pre>
<pre class="r"><code># Basic box plot from data frame
qplot(sex, weight, data = wdata, 
      geom= "boxplot", fill = sex)
# Violin plot
qplot(sex, weight, data = wdata, geom = "violin")
# Dot plot
qplot(sex, weight, data = wdata, geom = "dotplot",
      stackdir = "center", binaxis = "y", dotsize = 0.5)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-box-plot-violin-dot-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-box-plot-violin-dot-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-box-plot-violin-dot-3.png" width="240" /></p>
</div>
<div id="histogram-and-density-plots" class="section level2">
<h2>Histogram and density plots</h2>
<p>The <strong>histogram</strong> and <strong>density</strong> plots are used to display the distribution of data.</p>
<pre class="r"><code># Histogram  plot
# Change histogram fill color by group (sex)
qplot(weight, data = wdata, geom = "histogram",
      fill = sex)
# Density plot
# Change density plot line color by group (sex)
# change line type
qplot(weight, data = wdata, geom = "density",
    color = sex, linetype = sex)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-histogram-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-histogram-2.png" width="240" /></p>
</div>
</div>
<div id="ggplot-build-plots-piece-by-piece" class="section level1">
<h1>ggplot(): build plots piece by piece</h1>
<p>As mentioned above, there are two main functions in <strong>ggplot2</strong> package for generating graphics:</p>
<ul>
<li>The quick and easy-to-use function: <strong>qplot()</strong></li>
<li>The more powerful and flexible function to build plots piece by piece: <strong>ggplot()</strong></li>
</ul>
<p>This section describes briefly how to use the function <strong>ggplot()</strong>. Recall that, the concept of <strong>ggplot</strong> divides a plot into three different fundamental parts: <strong>plot = data + Aesthetics + geometry</strong>.</p>
<ul>
<li><strong>data</strong>: a data frame.</li>
<li><strong>Aesthetics</strong>: used to specify x and y variables, color, size, shape, ….
</li>
<li><strong>Geometry</strong>: the type of plots (<strong>histogram</strong>, <strong>boxplot</strong>, <strong>line</strong>, <strong>density</strong>, <strong>dotplot</strong>, <strong>bar</strong>, …)</li>
</ul>
<p>To demonstrate how the function <strong>ggplot()</strong> works, we’ll draw a <strong>scatter plot</strong>. The function <strong>aes</strong>() is used to specify aesthetics. An alternative option is the function <strong>aes_string</strong>() which generates mappings from a string. <strong>aes_string</strong>() is particularly useful when writing functions that create plots because you can use strings to define the aesthetic mappings, rather than having to use substitute to generate a call to <strong>aes</strong>()</p>
<pre class="r"><code># Basic scatter plot
ggplot(data = mtcars, aes(x = wt, y = mpg)) + 
  geom_point()
# Change the point size, and shape
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point(size = 2, shape = 23)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scatter-plot-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scatter-plot-2.png" width="192" /></p>
<p>The function <strong>aes_string</strong>() can be used as follow:</p>
<pre class="r"><code>ggplot(mtcars, aes_string(x = "wt", y = "mpg")) +
  geom_point(size = 2, shape = 23)</code></pre>
<p><span class="notice">Note that, some plots visualize a <strong>transformation</strong> of the original data set. In this case, an alternative way to build a layer is to use <strong>stat_*()</strong> functions.</span></p>
<p>In the following example, the function <strong>geom_density()</strong> does the same as the function <strong>stat_density()</strong>:</p>
<pre class="r"><code># Use geometry function
ggplot(wdata, aes(x = weight)) + geom_density()
# OR use stat function
ggplot(wdata, aes(x = weight)) + stat_density()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-stats-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-stats-2.png" width="259.2" /></p>
<p><span class="success">For each plot type, we’ll provide the <strong>geom_*()</strong> function and the corresponding <strong>stat_*()</strong> function (if available).</span></p>
<div id="one-variable-continuous" class="section level2">
<h2>One variable: Continuous</h2>
<p>We’ll use weight data (<em>wdata</em>), generated in the previous sections.</p>
<pre class="r"><code>head(wdata)</code></pre>
<pre><code>##   sex   weight
## 1   F 53.79293
## 2   F 55.27743
## 3   F 56.08444
## 4   F 52.65430
## 5   F 55.42912
## 6   F 55.50606</code></pre>
<p>The following R code computes the mean value by sex:</p>
<pre class="r"><code>library(plyr)
mu <- ddply(wdata, "sex", summarise, grp.mean=mean(weight))
head(mu)</code></pre>
<pre><code>##   sex grp.mean
## 1   F 54.94224
## 2   M 58.07325</code></pre>
<p><span class="success">We start by creating a plot, named <strong>a</strong>, that we’ll finish in the next section by adding a layer.</span></p>
<pre class="r"><code>a <- ggplot(wdata, aes(x = weight))</code></pre>
<br/>
<div class="block">
<p>Possible layers are:</p>
<ul>
<li>For <strong>one continuous variable</strong>:
<ul>
<li><strong>geom_area()</strong> for <em>area plot</em></li>
<li><strong>geom_density()</strong> for <em>density plot</em></li>
<li><strong>geom_dotplot()</strong> for <em>dot plot</em></li>
<li><strong>geom_freqpoly()</strong> for <em>frequency polygon</em></li>
<li><strong>geom_histogram()</strong> for <em>histogram plot</em></li>
<li><strong>stat_ecdf()</strong> for <em>empirical cumulative density function</em></li>
<li><strong>stat_qq()</strong> for <em>quantile - quantile plot</em></li>
</ul></li>
<li>For <strong>one discrete variable</strong>:
<ul>
<li><strong>geom_bar()</strong> for <em>bar plot</em></li>
</ul></li>
</ul>
</div>
<p><br/></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-one-continuous-variable-1.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-one-continuous-variable-2.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-one-continuous-variable-3.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-one-continuous-variable-4.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-one-continuous-variable-5.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-one-continuous-variable-6.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-one-continuous-variable-7.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-one-continuous-variable-8.png" width="144" /></p>
<div id="geom_area-create-an-area-plot" class="section level3">
<h3>geom_area(): Create an area plot</h3>
<pre class="r"><code># Basic plot
a + geom_area(stat = "bin")
# change fill colors by sex
a + geom_area(aes(fill = sex), stat ="bin", alpha=0.6) +
  theme_classic()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_area-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_area-2.png" width="259.2" /></p>
<p><span class="notice">Note that, by default y axis corresponds to the <em>count</em> of weight values. If you want to change the plot in order to have the <em>density</em> on y axis, the R code would be as follow.</span></p>
<pre class="r"><code>a + geom_area(aes(y = ..density..), stat ="bin")</code></pre>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em>, <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-area-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 area plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-area-plot-customize-1.png" width="384" /></p>
<ul>
<li><strong>Key function</strong>: <em>geom_area()</em></li>
<li><strong>Alternative function</strong>: <em>stat_bin()</em></li>
</ul>
<pre class="r"><code>a + stat_bin(geom = "area")</code></pre>
</div>
<div id="geom_density-create-a-smooth-density-estimate" class="section level3">
<h3>geom_density(): Create a smooth density estimate</h3>
<p>We’ll use the following functions:</p>
<ul>
<li><strong>geom_density()</strong> to create a <strong>density plot</strong></li>
<li><strong>geom_vline()</strong> to add a vertical lines corresponding to group mean values</li>
<li><strong>scale_color_manual()</strong> to change the color manually by groups</li>
</ul>
<pre class="r"><code># Basic plot
a + geom_density()
# change line colors by sex
a + geom_density(aes(color = sex)) 
# Change fill color by sex
# Use semi-transparent fill: alpha = 0.4
a + geom_density(aes(fill = sex), alpha=0.4)
   
# Add mean line and Change color manually
a + geom_density(aes(color = sex)) +
  geom_vline(data=mu, aes(xintercept=grp.mean, color=sex),
             linetype="dashed") +
  scale_color_manual(values=c("#999999", "#E69F00"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_density-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_density-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_density-3.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_density-4.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em>, <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-density-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 density plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_density-logo-1.png" width="384" /></p>
<ul>
<li><strong>Key function</strong>: <em>geom_density()</em></li>
<li><strong>Alternative function</strong>: <em>stat_density()</em></li>
</ul>
<pre class="r"><code>a + stat_density()</code></pre>
</div>
<div id="geom_dotplot-dot-plot" class="section level3">
<h3>geom_dotplot(): Dot plot</h3>
<p>In a <strong>dot plot</strong>, dots are stacked with each dot representing one observation.</p>
<pre class="r"><code># Basic plot
a + geom_dotplot()
# change fill and color by sex
a + geom_dotplot(aes(fill = sex)) 
# Change fill color manually 
a + geom_dotplot(aes(fill = sex)) +
  scale_fill_manual(values=c("#999999", "#E69F00"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_dotplot-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_dotplot-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_dotplot-3.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em> and <em>dotsize</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-dot-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 dot plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_dotplot-logo-1.png" width="384" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_dotplot()</em></li>
</ul>
</div>
<div id="geom_freqpoly-frequency-polygon" class="section level3">
<h3>geom_freqpoly(): Frequency polygon</h3>
<pre class="r"><code># Basic plot
a + geom_freqpoly() 
# change y axis to density value
# and change theme
a + geom_freqpoly(aes(y = ..density..)) +
  theme_minimal()
# change color and linetype by sex
a + geom_freqpoly(aes(color = sex, linetype = sex)) +
  theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_freqpoly-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_freqpoly-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_freqpoly-3.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em> and <em>size</em>.</span></p>
<ul>
<li><strong>Key function</strong>: <em>geom_freqpoly()</em></li>
<li><strong>Alternative function</strong>: <em>stat_bin()</em></li>
</ul>
</div>
<div id="geom_histogram-histogram" class="section level3">
<h3>geom_histogram(): Histogram</h3>
<pre class="r"><code># Basic plot
a + geom_histogram()
# change line colors by sex
a + geom_histogram(aes(color = sex), fill = "white",
                   position = "dodge") </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_histogram-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_histogram-2.png" width="259.2" /></p>
<p><span class="notice">If you want to change the plot in order to have the <em>density</em> on y axis, the R code would be as follow.</span></p>
<pre class="r"><code>a + geom_histogram(aes(y = ..density..))</code></pre>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-histogram-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 histogram plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_histogram-logo-1.png" width="384" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_histogram()</em></li>
<li><strong>Position adjustments</strong>: “identity” (or <em>position_identity()</em>), “stack” (or <em>position_stack()</em>), “dodge” ( or <em>position_dodge()</em>). Default value is “stack”</li>
<li><strong>Alternative function</strong>: <em>stat_bin()</em></li>
</ul>
<pre class="r"><code>a + stat_bin(geom = "histogram")</code></pre>
</div>
<div id="stat_ecdf-empirical-cumulative-density-function" class="section level3">
<h3>stat_ecdf(): Empirical Cumulative Density Function</h3>
<pre class="r"><code>a + stat_ecdf()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-stat_ecdf-1.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-ecdf-plot-quick-start-guide-for-empirical-cumulative-density-function-r-software-and-data-visualization">ggplot2 ECDF</a>.</span></p>
<ul>
<li><strong>Key function</strong>: <em>stat_ecdf()</em></li>
</ul>
</div>
<div id="stat_qq-quantile---quantile-plot" class="section level3">
<h3>stat_qq(): quantile - quantile plot</h3>
<pre class="r"><code>ggplot(mtcars, aes(sample=mpg)) + stat_qq()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-stat_qq-1.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>shape</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-qq-plot-quantile-quantile-graph-quick-start-guide-r-software-and-data-visualization">ggplot2 quantile - quantile plot</a>.</span></p>
<ul>
<li><strong>Key function</strong>: <em>stat_qq()</em></li>
</ul>
</div>
</div>
<div id="one-variable-discrete" class="section level2">
<h2>One variable: Discrete</h2>
<p>The function <strong>geom_bar()</strong> can be used to visualize one discrete variable. In this case, the count of each level is plotted. We’ll use the <strong>mpg</strong> data set [in <strong>ggplot2</strong> package]. The R code is as follow:</p>
<pre class="r"><code>data(mpg)
b <- ggplot(mpg, aes(fl))
# Basic plot
b + geom_bar()
# Change fill color
b + geom_bar(fill = "steelblue", color ="steelblue") +
  theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-discrete-variable-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-discrete-variable-2.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-barplots-quick-start-guide-r-software-and-data-visualization">ggplot2 bar plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-logo-1.png" width="384" /></p>
<ul>
<li><strong>Key function</strong>: <em>geom_bar()</em></li>
<li><strong>Alternative function</strong>: <em>stat_count()</em></li>
</ul>
<pre class="r"><code>b + stat_count()</code></pre>
</div>
<div id="two-variables-continuous-x-continuous-y" class="section level2">
<h2>Two variables: Continuous X, Continuous Y</h2>
<p>We’ll use the <strong>mtcars</strong> data set. The variable <em>cyl</em> is used as grouping variable.</p>
<pre class="r"><code>data(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)
head(mtcars[, c("wt", "mpg", "cyl")])</code></pre>
<pre><code>##                      wt  mpg cyl
## Mazda RX4         2.620 21.0   6
## Mazda RX4 Wag     2.875 21.0   6
## Datsun 710        2.320 22.8   4
## Hornet 4 Drive    3.215 21.4   6
## Hornet Sportabout 3.440 18.7   8
## Valiant           3.460 18.1   6</code></pre>
<p><span class="success">We start by creating a plot, named <strong>b</strong>, that we’ll finish in the next section by adding a layer. </span></p>
<pre class="r"><code>b <- ggplot(mtcars, aes(x = wt, y = mpg))</code></pre>
<br/>
<div class="block">
<p>Possible layers include:</p>
<ul>
<li><strong>geom_point()</strong> for scatter plot</li>
<li><strong>geom_smooth()</strong> for adding smoothed line such as regression line</li>
<li><strong>geom_quantile()</strong> for adding quantile lines</li>
<li><strong>geom_rug()</strong> for adding a marginal rug</li>
<li><strong>geom_jitter()</strong> for avoiding overplotting</li>
<li><strong>geom_text()</strong> for adding textual annotations</li>
</ul>
</div>
<p><br/></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-two-continuous-variable-1.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-two-continuous-variable-2.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-two-continuous-variable-3.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-two-continuous-variable-4.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-two-continuous-variable-5.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-two-continuous-variable-6.png" width="144" /></p>
<div id="geom_point-scatter-plot" class="section level3">
<h3>geom_point(): Scatter plot</h3>
<pre class="r"><code># Basic plot
b + geom_point()
   
# change the color and the point 
# by the levels of cyl variable
b + geom_point(aes(color = cyl, shape = cyl)) 
# Change color manually
b + geom_point(aes(color = cyl, shape = cyl)) +
  scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9"))+
  theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_point-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_point-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_point-3.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>shape</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization">ggplot2 scatter plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_point-logo-1.png" width="384" /></p>
<ul>
<li><strong>key function</strong>: <em>geom_point()</em></li>
</ul>
</div>
<div id="geom_smooth-add-regression-line-or-smoothed-conditional-mean" class="section level3">
<h3>geom_smooth(): Add regression line or smoothed conditional mean</h3>
<p>To add a <strong>regression line</strong> on a scatter plot, the function <strong>geom_smooth()</strong> is used in combination with the argument <strong>method = lm</strong>. <strong>lm</strong> stands for <strong>linear model</strong>.</p>
<pre class="r"><code># Regression line only
b + geom_smooth(method = lm)
  
# Point + regression line
# Remove the confidence interval 
b + geom_point() + 
  geom_smooth(method = lm, se = FALSE)
# loess method: local regression fitting
b + geom_point() + geom_smooth()
# Change color and shape by groups (cyl)
b + geom_point(aes(color=cyl, shape=cyl)) + 
  geom_smooth(aes(color=cyl, shape=cyl), 
              method=lm, se=FALSE, fullrange=TRUE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_smooth-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_smooth-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_smooth-3.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_smooth-4.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>shape</em> , <strong>linetype</strong> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization#add-regression-lines">ggplot2 scatter plot</a></span></p>
<ul>
<li><strong>key function</strong>: <em>geom_smooth()</em></li>
<li><strong>Alternative function</strong>: <em>stat_smooth()</em></li>
</ul>
<pre class="r"><code>b + stat_smooth(method = "lm")</code></pre>
</div>
<div id="geom_quantile-add-quantile-lines-from-a-quantile-regression" class="section level3">
<h3>geom_quantile(): Add quantile lines from a quantile regression</h3>
<p><strong>Quantile lines</strong> can be used as a continuous analogue of a <strong>geom_boxplot()</strong>.</p>
<p>We’ll use the <strong>mpg</strong> data set [in <strong>ggplot2</strong>].</p>
<p>The function <strong>geom_quantile()</strong> can be used for adding quantile lines:</p>
<pre class="r"><code>ggplot(mpg, aes(cty, hwy)) +
  geom_point() + geom_quantile() +
  theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_quantile-1.png" width="384" /></p>
<p>An alternative to <strong>geom_quantile()</strong> is the function <strong>stat_quantile()</strong>:</p>
<pre class="r"><code>ggplot(mpg, aes(cty, hwy)) +
  geom_point() + stat_quantile(quantiles = c(0.25, 0.5, 0.75))</code></pre>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <strong>linetype</strong> and <em>size</em>. Learn more here: <a href="http://docs.ggplot2.org/current/stat_quantile.html">Continuous quantiles</a></span></p>
<ul>
<li><strong>Key function</strong>: <em>geom_quantile()</em></li>
<li><strong>Alternative function</strong>: <em>stat_quantile()</em></li>
</ul>
</div>
<div id="geom_rug-add-marginal-rug-to-scatter-plots" class="section level3">
<h3>geom_rug(): Add marginal rug to scatter plots</h3>
<p>We’ll use <strong>faithful</strong> data set.</p>
<pre class="r"><code># Add marginal rugs using faithful data
ggplot(faithful, aes(x=eruptions, y=waiting)) +
  geom_point() + geom_rug()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_rug-1.png" width="336" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <strong>linetype</strong> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization#add-marginal-rugs-to-a-scatter-plot">ggplot2 scatter plot</a></span></p>
<ul>
<li><strong>key function</strong>: <em>geom_rug()</em></li>
</ul>
</div>
<div id="geom_jitter-jitter-points-to-reduce-overplotting" class="section level3">
<h3>geom_jitter(): Jitter points to reduce overplotting</h3>
<p>The function <strong>geom_jitter()</strong> is a convenient default for <strong>geom_point(position = ‘jitter’)</strong>. The <strong>mpg</strong> data set [in <strong>ggplot2</strong>] is used in the following examples.</p>
<pre class="r"><code>p <- ggplot(mpg, aes(displ, hwy))
# Default scatter plot
p + geom_point()
# Use jitter to reduce overplotting
p + geom_jitter(
    position = position_jitter(width = 0.5, height = 0.5))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_jitter-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_jitter-2.png" width="259.2" /></p>
<p>To adjust the extent of jittering, the function <strong>position_jitter()</strong> with the arguments <strong>width</strong> and <strong>height</strong> are used:</p>
<ul>
<li><strong>width</strong>: degree of jitter in x direction.</li>
<li><strong>height</strong>: degree of jitter in y direction.</li>
</ul>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>shape</em> and <em>size</em>. Learn more here: <a href="http://docs.ggplot2.org/current/geom_jitter.html">ggplot2 jitter</a></span></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_jitter()</em>, <em>position_jitter()</em></li>
</ul>
</div>
<div id="geom_text-textual-annotations" class="section level3">
<h3>geom_text(): Textual annotations</h3>
<p>The argument <strong>label</strong> is used to specify a vector of labels for point annotations.</p>
<pre class="r"><code>b + geom_text(aes(label = rownames(mtcars)))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_text-1.png" width="384" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>label</em>, <em>alpha</em>, <em>angle</em>, <em>color</em>, <em>family</em>, <em>fontface</em>, <em>hjust</em>, <em>lineheight</em>, <em>size</em>, and <em>vjust</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-texts-add-text-annotations-to-a-graph-in-r-software">ggplot2 add textual annotations</a></span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_text-logo-1.png" width="384" /></p>
<ul>
<li><strong>key function</strong>: <em>geom_text()</em>, <em>annotation_custom()</em></li>
</ul>
</div>
</div>
<div id="two-variables-continuous-bivariate-distribution" class="section level2">
<h2>Two variables: Continuous bivariate distribution</h2>
<p>We start by using the <strong>diamonds</strong> data set [in <strong>ggplot2</strong>].</p>
<pre class="r"><code>data(diamonds)
head(diamonds[, c("carat", "price")])</code></pre>
<pre><code>##   carat price
## 1  0.23   326
## 2  0.21   326
## 3  0.23   327
## 4  0.29   334
## 5  0.31   335
## 6  0.24   336</code></pre>
<p><span class="success">We start by creating a plot, named <strong>c</strong>, that we’ll finish in the next section by adding a layer. </span></p>
<pre class="r"><code>c <- ggplot(diamonds, aes(carat, price))</code></pre>
<br/>
<div class="block">
<p>Possible layers include:</p>
<ul>
<li><strong>geom_bin2d()</strong> for adding a heatmap of <strong>2d bin counts</strong>. Rectangular bining.</li>
<li><strong>geom_hex()</strong> for adding <strong>hexagon bining</strong>. The R package <strong>hexbin</strong> is required for this functionality</li>
<li><strong>geom_density_2d()</strong> for adding contours from a <strong>2d density</strong> estimate</li>
</ul>
</div>
<p><br/></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-Continuous-bivariate-distribution-1.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-Continuous-bivariate-distribution-2.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-Continuous-bivariate-distribution-3.png" width="144" /></p>
<div id="geom_bin2d-add-heatmap-of-2d-bin-counts" class="section level3">
<h3>geom_bin2d(): Add heatmap of 2d bin counts</h3>
<p>The function <strong>geom_bin2d()</strong> produces a scatter plot with rectangular bins. The number of observations is counted in each bins and displayed as a heatmap.</p>
<pre class="r"><code># Default plot 
c + geom_bin2d()
# Change the number of bins
c + geom_bin2d(bins = 15)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bin2d-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bin2d-2.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>xmax</em>, <em>xmin</em>, <em>ymax</em>, <em>ymin</em>, <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization#scatter-plots-with-rectangular-bins">ggplot2 Scatter plots with rectangular bins</a></span></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_bin2d()</em></li>
<li><strong>Alternative functions</strong>: <em>stat_bin_2d()</em>, <em>stat_summary_2d()</em></li>
</ul>
<pre class="r"><code>c + stat_bin_2d()
c + stat_summary_2d(aes(z = depth))</code></pre>
</div>
<div id="geom_hex-add-hexagon-bining" class="section level3">
<h3>geom_hex(): Add hexagon bining</h3>
<p>The function <strong>geom_hex()</strong> produces a scatter plot with hexagon bining. The <strong>hexbin</strong> R package is required for hexagon bining. If you don’t have it, use the R code below to install it:</p>
<pre class="r"><code>install.packages("hexbin")</code></pre>
<p>The function <strong>geom_hex()</strong> can be used as follow:</p>
<pre class="r"><code>require(hexbin)
# Default plot 
c + geom_hex()
# Change the number of bins
c + geom_hex(bins = 10)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_hex-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_hex-2.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization#scatter-plots-with-rectangular-bins">ggplot2 Scatter plots with rectangular bins</a></span></p>
<ul>
<li><strong>Key function</strong>: <em>geom_hex()</em></li>
<li><strong>Alternative functions</strong>: <em>stat_bin_hex()</em>, <em>stat_summary_hex()</em></li>
</ul>
<pre class="r"><code>c + stat_bin_hex()
c + stat_summary_hex(aes(z = depth))</code></pre>
</div>
<div id="geom_density_2d-add-contours-from-a-2d-density-estimate" class="section level3">
<h3>geom_density_2d(): Add contours from a 2d density estimate</h3>
<p>The functions <strong>geom_density_2d()</strong> or <strong>stat_density_2d()</strong> can be used to add 2d density estimate to a scatter plot.</p>
<p><strong>faithful</strong> data set is used in this section, and we first start by creating a scatter plot (**sp*) as follow:</p>
<pre class="r"><code># Scatter plot 
sp <- ggplot(faithful, aes(x=eruptions, y=waiting)) </code></pre>
<pre class="r"><code># Default plot
sp + geom_density_2d()
# Add points
sp + geom_point() + geom_density_2d()
# Use stat_density_2d with geom = "polygon"
sp + geom_point() + 
  stat_density_2d(aes(fill = ..level..), geom="polygon")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_density_2d-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_density_2d-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_density_2d-3.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization#scatter-plots-with-the-2d-density-estimation">ggplot2 Scatter plots with the 2d density estimation</a></span></p>
<ul>
<li><strong>Key function</strong>: <em>geom_density_2d()</em></li>
<li><strong>Alternative functions</strong>: <em>stat_density_2d()</em></li>
</ul>
<pre class="r"><code>sp + stat_density_2d()</code></pre>
<ul>
<li><strong>See also</strong>: <em>stat_contour()</em>, <em>geom_contour()</em></li>
</ul>
</div>
</div>
<div id="two-variables-continuous-function" class="section level2">
<h2>Two variables: Continuous function</h2>
<p>In this section, we’ll see how to connect observations by <strong>line</strong>. The <strong>economics</strong> data set [in <strong>ggplot2</strong>] is used.</p>
<pre class="r"><code>data(economics)
head(economics)</code></pre>
<pre><code>##         date   pce    pop psavert uempmed unemploy
## 1 1967-07-01 507.4 198712    12.5     4.5     2944
## 2 1967-08-01 510.5 198911    12.5     4.7     2945
## 3 1967-09-01 516.3 199113    11.7     4.6     2958
## 4 1967-10-01 512.9 199311    12.5     4.9     3143
## 5 1967-11-01 518.1 199498    12.5     4.7     3066
## 6 1967-12-01 525.8 199657    12.1     4.8     3018</code></pre>
<p><span class="success">We start by creating a plot, named <strong>d</strong>, that we’ll finish in the next section by adding a layer. </span></p>
<pre class="r"><code>d <- ggplot(economics, aes(x = date, y = unemploy))</code></pre>
<br/>
<div class="block">
<p>Possible layers include:</p>
<ul>
<li><strong>geom_area()</strong> for area plot</li>
<li><strong>geom_line()</strong> for line plot connecting observations, ordered by x</li>
<li><strong>geom_step()</strong> for connecting observations by stairs</li>
</ul>
</div>
<p><br/></p>
<pre class="r"><code># Area plot
d + geom_area()
# Line plot: connecting observations, ordered by x
d + geom_line()
# Connecting observations by stairs
# a subset of economics data set is used
set.seed(1234)
ss <- economics[sample(1:nrow(economics), 20), ]
ggplot(ss, aes(x = date, y = unemploy)) + 
  geom_step()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-continuous-function-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-continuous-function-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-continuous-function-3.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em>, <em>size</em> and <em>fill</em> (for geom_area only). Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-line-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 line plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-logo-data-visualization-1.png" width="384" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_area()</em>, <em>geom_line()</em>, <em>geom_step()</em></li>
</ul>
</div>
<div id="two-variables-discrete-x-continuous-y" class="section level2">
<h2>Two variables: Discrete X, Continuous Y</h2>
<p>The <strong>ToothGrowth</strong> data set we’ll be used to plot the continuous variable <strong>len</strong> (for tooth length) by the discrete variable <strong>dose</strong>. The following R code converts the variable <strong>dose</strong> from a numeric to a discrete factor variable.</p>
<pre class="r"><code>data("ToothGrowth")
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth)</code></pre>
<pre><code>##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5</code></pre>
<p><span class="success">We start by creating a plot, named <strong>e</strong>, that we’ll finish in the next section by adding a layer. </span></p>
<pre class="r"><code>e <- ggplot(ToothGrowth, aes(x = dose, y = len))</code></pre>
<br/>
<div class="block">
<p>Possible layers include:</p>
<ul>
<li><strong>geom_boxplot()</strong> for box plot</li>
<li><strong>geom_violin()</strong> for violin plot</li>
<li><strong>geom_dotplot()</strong> for dot plot</li>
<li><strong>geom_jitter()</strong> for stripchart</li>
<li><strong>geom_line()</strong> for line plot</li>
<li><strong>geom_bar()</strong> for bar plot</li>
</ul>
</div>
<p><br/></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-discrete-x-continuous-y-1.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-discrete-x-continuous-y-2.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-discrete-x-continuous-y-3.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-discrete-x-continuous-y-4.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-discrete-x-continuous-y-5.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-discrete-x-continuous-y-6.png" width="144" /></p>
<div id="geom_boxplot-box-and-whiskers-plot" class="section level3">
<h3>geom_boxplot(): Box and whiskers plot</h3>
<pre class="r"><code># Default plot
e + geom_boxplot()
# Notched box plot
e + geom_boxplot(notch = TRUE)
# Color by group (dose)
e + geom_boxplot(aes(color = dose))
# Change fill color by group (dose)
e + geom_boxplot(aes(fill = dose))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_boxplot-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_boxplot-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_boxplot-3.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_boxplot-4.png" width="240" /></p>
<pre class="r"><code># Box plot with multiple groups
ggplot(ToothGrowth, aes(x=dose, y=len, fill=supp)) +
  geom_boxplot()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_boxplot-multiple-group-1.png" width="288" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em>, <em>shape</em>, <em>size</em> and <em>fill</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-box-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 box plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_boxplot-logo-data-visualization-1.png" width="384" /></p>
<ul>
<li><strong>Key function</strong>: <em>geom_boxplot()</em></li>
<li><strong>Alternative functions</strong>: <em>stat_boxplot()</em></li>
</ul>
<pre class="r"><code>e + stat_boxplot(coeff = 1.5)</code></pre>
</div>
<div id="geom_violin-violin-plot" class="section level3">
<h3>geom_violin(): Violin plot</h3>
<p>Violin plots are similar to box plots, except that they also show the kernel probability density of the data at different values.</p>
<pre class="r"><code># Default plot
e + geom_violin(trim = FALSE)
# violin plot with mean points (+/- SD)
e + geom_violin(trim = FALSE) + 
  stat_summary(fun.data="mean_sdl",  fun.args = list(mult=1), 
               geom="pointrange", color = "red")
# Combine with box plot
e + geom_violin(trim = FALSE) + 
  geom_boxplot(width = 0.2)
# Color by group (dose) 
e + geom_violin(aes(color = dose), trim = FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_violin-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_violin-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_violin-3.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_violin-4.png" width="240" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em>, <em>size</em> and <em>fill</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-violin-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 violin plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_violin-logo-data-visualization-1.png" width="384" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_violin()</em></li>
<li><strong>Alternative functions</strong>: <em>stat_ydensity()</em></li>
</ul>
<pre class="r"><code>e + stat_ydensity(trim = FALSE)</code></pre>
</div>
<div id="geom_dotplot-dot-plot-1" class="section level3">
<h3>geom_dotplot(): Dot plot</h3>
<pre class="r"><code># Default plot
e + geom_dotplot(binaxis = "y", stackdir = "center")
# Dot plot with mean points (+/- SD)
e + geom_dotplot(binaxis = "y", stackdir = "center") + 
  stat_summary(fun.data="mean_sdl",  fun.args = list(mult=1), 
               geom="pointrange", color = "red")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-2.png" width="240" /></p>
<pre class="r"><code># Combine with box plot
e + geom_boxplot() + 
  geom_dotplot(binaxis = "y", stackdir = "center") 
# Add violin plot
e + geom_violin(trim = FALSE) +
  geom_dotplot(binaxis='y', stackdir='center')
  
# Color and fill by group (dose) 
e + geom_dotplot(aes(color = dose, fill = dose), 
                 binaxis = "y", stackdir = "center")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-combine-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-combine-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-combine-3.png" width="240" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>dotsize</em> and <em>fill</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-dot-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 dot plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-logo-data-visualization-1.png" width="384" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_dotplot()</em>, <em>stat_summary()</em></li>
</ul>
</div>
<div id="geom_jitter-strip-charts" class="section level3">
<h3>geom_jitter(): Strip charts</h3>
<p><strong>Stripcharts</strong> are also known as one dimensional scatter plots. These plots are suitable compared to box plots when sample sizes are small.</p>
<pre class="r"><code># Default plot
e + geom_jitter(position=position_jitter(0.2))
# Strip charts with mean points (+/- SD)
e + geom_jitter(position=position_jitter(0.2)) + 
  stat_summary(fun.data="mean_sdl",  fun.args = list(mult=1), 
               geom="pointrange", color = "red")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_strip-charts-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_strip-charts-2.png" width="240" /></p>
<pre class="r"><code># Combine with box plot
e + geom_jitter(position=position_jitter(0.2)) + 
  geom_dotplot(binaxis = "y", stackdir = "center") 
# Add violin plot
e + geom_violin(trim = FALSE) +
  geom_jitter(position=position_jitter(0.2))
  
# Change color and shape by group (dose) 
e +  geom_jitter(aes(color = dose, shape = dose),
                 position=position_jitter(0.2))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_jitter-combine-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_jitter-combine-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_jitter-combine-3.png" width="240" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>shape</em>, <em>size</em> and <em>fill</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-stripchart-jitter-quick-start-guide-r-software-and-data-visualization">ggplot2 strip charts</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_jitter-logo-data-visualization-1.png" width="384" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_jitter()</em>, <em>stat_summary()</em></li>
</ul>
</div>
<div id="geom_line-line-plot" class="section level3">
<h3>geom_line(): Line plot</h3>
<p>Data derived from <em>ToothGrowth</em> data sets are used.</p>
<pre class="r"><code>df <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                dose=rep(c("D0.5", "D1", "D2"),2),
                len=c(6.8, 15, 33, 4.2, 10, 29.5))
head(df)</code></pre>
<pre><code>##   supp dose  len
## 1   VC D0.5  6.8
## 2   VC   D1 15.0
## 3   VC   D2 33.0
## 4   OJ D0.5  4.2
## 5   OJ   D1 10.0
## 6   OJ   D2 29.5</code></pre>
<p>In the graphs below, line types and point shapes are controlled automatically by the levels of the variable <em>supp</em> :</p>
<pre class="r"><code># Change line types by groups (supp)
ggplot(df, aes(x=dose, y=len, group=supp)) +
  geom_line(aes(linetype=supp))+
  geom_point()
# Change line types, point shapes and colors
ggplot(df, aes(x=dose, y=len, group=supp)) +
  geom_line(aes(linetype=supp, color = supp))+
  geom_point(aes(shape=supp, color = supp))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_line-multiple-groups-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_line-multiple-groups-2.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-line-plot-quick-start-guide-r-software-and-data-visualization">ggplot2 line plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_line-logo-data-visualization-1.png" width="384" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_line()</em>, <em>geom_step()</em></li>
</ul>
</div>
<div id="geom_bar-bar-plot" class="section level3">
<h3>geom_bar(): Bar plot</h3>
<p>Data derived from <em>ToothGrowth</em> data sets are used.</p>
<pre class="r"><code>df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5))
head(df)</code></pre>
<pre><code>##   dose  len
## 1 D0.5  4.2
## 2   D1 10.0
## 3   D2 29.5</code></pre>
<pre class="r"><code>df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                dose=rep(c("D0.5", "D1", "D2"),2),
                len=c(6.8, 15, 33, 4.2, 10, 29.5))
head(df2)</code></pre>
<pre><code>##   supp dose  len
## 1   VC D0.5  6.8
## 2   VC   D1 15.0
## 3   VC   D2 33.0
## 4   OJ D0.5  4.2
## 5   OJ   D1 10.0
## 6   OJ   D2 29.5</code></pre>
<p>We start by creating a simple <strong>bar plot</strong> (named <strong>f</strong>) using the <em>df</em> data set:</p>
<pre class="r"><code>f <- ggplot(df, aes(x = dose, y = len))</code></pre>
<pre class="r"><code># Basic bar plot
f + geom_bar(stat = "identity")
# Change fill color and add labels
f + geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=len), vjust=-0.3, size=3.5)+
  theme_minimal()
# Change bar plot line colors by groups
f + geom_bar(aes(color = dose),
             stat="identity", fill="white")
# Change bar plot fill colors by groups
f + geom_bar(aes(fill = dose), stat="identity")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-3.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-4.png" width="259.2" /></p>
<p>Bar plot with multiple groups:</p>
<pre class="r"><code>g <- ggplot(data=df2, aes(x=dose, y=len, fill=supp)) 
# Stacked bar plot
g + geom_bar(stat = "identity")
# Use position=position_dodge()
g + geom_bar(stat="identity", position=position_dodge())</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-multiple-groups-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_bar-multiple-groups-2.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-barplots-quick-start-guide-r-software-and-data-visualization">ggplot2 bar plot</a>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_bar-logo-data-visualization-1.png" width="384" /></p>
<ul>
<li><strong>Key function</strong>: <em>geom_bar()</em></li>
<li><strong>Alternative function</strong>: <em>stat_identity()</em></li>
</ul>
<pre class="r"><code>g + stat_identity(geom = "bar")
g + stat_identity(geom = "bar", position = "dodge")</code></pre>
</div>
</div>
<div id="two-variables-discrete-x-discrete-y" class="section level2">
<h2>Two variables: Discrete X, Discrete Y</h2>
<p>The <strong>diamonds</strong> data set [in <strong>ggplot2</strong>] we’ll be used to plot the discrete variable <strong>color</strong> (for diamond colors) by the discrete variable <strong>cut</strong> (for diamond cut types). The plot is created using the function <strong>geom_jitter()</strong>.</p>
<pre class="r"><code>ggplot(diamonds, aes(cut, color)) +
  geom_jitter(aes(color = cut), size = 0.5)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-discrete-x-discrete-y-1.png" width="480" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>shape</em> and <em>size</em>.</span></p>
<ul>
<li><strong>Key function</strong>: <em>geom_jitter()</em></li>
</ul>
</div>
<div id="two-variables-visualizing-error" class="section level2">
<h2>Two variables: Visualizing error</h2>
<p>The <strong>ToothGrowth</strong> data set we’ll be used. We start by creating a data set named <strong>df</strong> which holds <strong>ToothGrowth</strong> data.</p>
<pre class="r"><code># ToothGrowth data set
df <- ToothGrowth
df$dose <- as.factor(df$dose)
head(df)</code></pre>
<pre><code>##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5</code></pre>
<p>The helper function below (<strong>data_summary()</strong>) will be used to calculate the mean and the standard deviation (used as error), for the variable of interest, in each group. The <strong>plyr</strong> package is required.</p>
<pre class="r"><code># Calculate the mean and the SD in each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of the variable to be summariezed
# grps : column names to be used as grouping variables
data_summary <- function(data, varname, grps){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      sd = sd(x[[col]], na.rm=TRUE))
  }
  data_sum<-ddply(data, grps, .fun=summary_func, varname)
  data_sum <- rename(data_sum, c("mean" = varname))
 return(data_sum)
}</code></pre>
<p>Using the function <strong>data_summary()</strong>, the following R code creates a data set named <strong>df2</strong> which holds the mean and the SD of tooth length (<em>len</em>) by groups (<em>dose</em>).</p>
<pre class="r"><code>df2 <- data_summary(df, varname="len", grps= "dose")
# Convert dose to a factor variable
df2$dose=as.factor(df2$dose)
head(df2)</code></pre>
<pre><code>##   dose    len       sd
## 1  0.5 10.605 4.499763
## 2    1 19.735 4.415436
## 3    2 26.100 3.774150</code></pre>
<p><span class="success">We start by creating a plot, named <strong>f</strong>, that we’ll finish in the next section by adding a layer.</span></p>
<pre class="r"><code>f <- ggplot(df2, aes(x = dose, y = len, 
                     ymin = len-sd, ymax = len+sd))</code></pre>
<br/>
<div class="block">
<p>Possible layers include:</p>
<ul>
<li><strong>geom_crossbar()</strong> for hollow bar with middle indicated by horizontal line</li>
<li><strong>geom_errorbar()</strong> for error bars</li>
<li><strong>geom_errorbarh()</strong> for horizontal error bars</li>
<li><strong>geom_linerange()</strong> for drawing an interval represented by a vertical line</li>
<li><strong>geom_pointrange()</strong> for creating an interval represented by a vertical line, with a point in the middle.</li>
</ul>
</div>
<p><br/></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-error-bars-1.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-error-bars-2.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-error-bars-3.png" width="144" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-graphics-error-bars-4.png" width="144" /></p>
<div id="geom_crossbar-hollow-bar-with-middle-indicated-by-horizontal-line" class="section level3">
<h3>geom_crossbar(): Hollow bar with middle indicated by horizontal line</h3>
<p>We’ll use the data set named <strong>df2</strong>, which holds the mean and the SD of tooth length (<em>len</em>) by groups (<em>dose</em>).</p>
<pre class="r"><code># Default plot
f + geom_crossbar()
# color by groups
f + geom_crossbar(aes(color = dose))
# Change color manually
f + geom_crossbar(aes(color = dose)) + 
  scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9"))+
  theme_minimal()
# fill by groups and change color manually
f + geom_crossbar(aes(fill = dose)) + 
  scale_fill_manual(values = c("#999999", "#E69F00", "#56B4E9"))+
  theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_crossbar-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_crossbar-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_crossbar-3.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_crossbar-4.png" width="259.2" /></p>
<p><strong>Cross bar with multiple groups</strong>: Using the function <strong>data_summary()</strong>, we start by creating a data set named <strong>df3</strong> which holds the mean and the SD of tooth length (<em>len</em>) by 2 groups (<em>supp</em> and <em>dose</em>).</p>
<pre class="r"><code>df3 <- data_summary(df, varname="len", grps= c("supp", "dose"))
head(df3)</code></pre>
<pre><code>##   supp dose   len       sd
## 1   OJ  0.5 13.23 4.459709
## 2   OJ    1 22.70 3.910953
## 3   OJ    2 26.06 2.655058
## 4   VC  0.5  7.98 2.746634
## 5   VC    1 16.77 2.515309
## 6   VC    2 26.14 4.797731</code></pre>
<p>The data set <strong>df3</strong> is used to create <strong>cross bars with multiple groups</strong>. For this end, the variable <strong>len</strong> is plotted by <strong>dose</strong> and the color is changed by the levels of the factor <strong>supp</strong>.</p>
<pre class="r"><code>f <- ggplot(df3, aes(x = dose, y = len, 
                     ymin = len-sd, ymax = len+sd))
# Default plot
f + geom_crossbar(aes(color = supp))
# Use position_dodge() to avoid overlap
f + geom_crossbar(aes(color = supp), 
                  position = position_dodge(1))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_crossbar-multiple-groups-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_crossbar-multiple-groups-2.png" width="259.2" /></p>
<p><span class="warning">A simple alternative to <strong>geom_crossbar()</strong> is to use the function <strong>stat_summary()</strong> as follow. In this case, the mean and the SD can be computed automatically.</span></p>
<pre class="r"><code>f <- ggplot(df, aes(x = dose, y = len, color = supp)) 
# Use geom_crossbar()
f + stat_summary(fun.data="mean_sdl", fun.args = list(mult=1), 
                 geom="crossbar", width = 0.6, 
                 position = position_dodge(0.8))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_crossbar-multiple-groups-2-1.png" width="288" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-error-bars-quick-start-guide-r-software-and-data-visualization">ggplot2 error bars</a>.</span></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_crossbar()</em>, <em>stat_summary()</em></li>
</ul>
</div>
<div id="geom_errorbar-error-bars" class="section level3">
<h3>geom_errorbar(): Error bars</h3>
<p>We’ll use the data set named <strong>df2</strong>, which holds the mean and the SD of tooth length (<em>len</em>) by groups (<em>dose</em>).</p>
<p>We start by creating a plot, named <strong>f</strong>, that we’ll finish next by adding a layer.</p>
<pre class="r"><code>f <- ggplot(df2, aes(x = dose, y = len, 
                     ymin = len-sd, ymax = len+sd))</code></pre>
<pre class="r"><code># Error bars colored by groups
f + geom_errorbar(aes(color = dose), width = 0.2)
# Combine with line plot
f + geom_line(aes(group = 1)) + 
  geom_errorbar(width = 0.2)
# Combine with bar plot, color by groups
f + geom_bar(aes(color = dose), stat = "identity", fill ="white") + 
  geom_errorbar(aes(color = dose), width = 0.2)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_error-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_error-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_error-3.png" width="259.2" /></p>
<p><strong>Error bars with multiple groups</strong>:</p>
<p>The data set <strong>df3</strong> is used to create <strong>cross bars with multiple groups</strong>. For this end, the variable <strong>len</strong> is plotted by <strong>dose</strong> and the color is changed by the levels of the factor <strong>supp</strong>.</p>
<pre class="r"><code>f <- ggplot(df3, aes(x = dose, y = len, 
                     ymin = len-sd, ymax = len+sd))
# Default plot
f + geom_bar(aes(fill = supp), stat = "identity",
             position = "dodge") + 
  geom_errorbar(aes(color = supp),  position = "dodge")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_errorbar-multiple-groups-1.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em>, <em>size</em> and <em>width</em>. </span></p>
<p>Learn more here:</p>
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/ggplot2-error-bars-quick-start-guide-r-software-and-data-visualization">ggplot2 error bars</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/ggplot2-barplots-quick-start-guide-r-software-and-data-visualization#barplot-with-error-bars">Bar plot with error bars</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/ggplot2-line-plot-quick-start-guide-r-software-and-data-visualization#line-graph-with-error-bars">Line plot with error bars</a></li>
</ul>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_errorbar-logo-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_errorbar-logo-2.png" width="259.2" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_errorbar()</em>, <em>stat_summary()</em></li>
</ul>
</div>
<div id="geom_errorbarh-horizontal-error-bars" class="section level3">
<h3>geom_errorbarh(): Horizontal error bars</h3>
<p>We’ll use the data set named <strong>df2</strong>, which holds the mean and the SD of tooth length (<em>len</em>) by groups (<em>dose</em>):</p>
<pre class="r"><code>df2 <- data_summary(ToothGrowth, varname="len", grps = "dose")
head(df2)</code></pre>
<pre><code>##   dose    len       sd
## 1  0.5 10.605 4.499763
## 2    1 19.735 4.415436
## 3    2 26.100 3.774150</code></pre>
<p>We start by creating a plot, named <strong>f</strong>, that we’ll finish next by adding a layer.</p>
<pre class="r"><code>f <- ggplot(df2, aes(x = len, y = dose ,
                     xmin=len-sd, xmax=len+sd))</code></pre>
<p>The arguments <strong>xmin</strong> and <strong>xmax</strong> are used for horizontal error bars.</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_errorbarh-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_errorbarh-2.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em>, <em>size</em> and <em>height</em>.</span></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_errorbarh()</em></li>
</ul>
</div>
<div id="geom_linerange-and-geom_pointrange-an-interval-represented-by-a-vertical-line" class="section level3">
<h3>geom_linerange() and geom_pointrange(): An interval represented by a vertical line</h3>
<ul>
<li><strong>geom_linerange()</strong>: Add an interval represented by a vertical line</li>
<li><strong>geom_pointrange()</strong>: Add an interval represented by a vertical line with a point in the middle</li>
</ul>
<p>We’ll use the data set <strong>df2</strong>.</p>
<pre class="r"><code>f <- ggplot(df2, aes(x = dose, y = len,
                     ymin=len-sd, ymax=len+sd))
# Line range
f + geom_linerange()
# Point range
f + geom_pointrange()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_linerange-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_linerange-2.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em>, <em>size</em>, <em>shape</em> and <em>fill</em> (for geom_pointrange()).</span></p>
</div>
<div id="combine-geom_dotplot-and-error-bars" class="section level3">
<h3>Combine geom_dotplot and error bars</h3>
<p>It’s also possible to combine <strong>geom_dotplot()</strong> and <strong>error bars</strong>. We’ll use the <strong>ToothGrowth</strong> data set. You don’t need to compute the <em>mean</em> and <em>SD</em>. This can be done automatically by using the function <strong>stat_summary()</strong> in combination with the argument <strong>fun.data = “mean_sdl”</strong>.</p>
<p><span class="success">We start by creating a dot plot, named <strong>g</strong>, that we’ll finish in the next section by adding error bar layers.</span></p>
<pre class="r"><code>g <- ggplot(df, aes(x=dose, y=len)) + 
  geom_dotplot(binaxis='y', stackdir='center')</code></pre>
<pre class="r"><code># use geom_crossbar()
g + stat_summary(fun.data="mean_sdl", fun.args = list(mult=1), 
                 geom="crossbar", width=0.5)
# Use geom_errorbar()
g + stat_summary(fun.data=mean_sdl, fun.args = list(mult=1), 
        geom="errorbar", color="red", width=0.2) +
  stat_summary(fun.y=mean, geom="point", color="red")
   
# Use geom_pointrange()
g + stat_summary(fun.data=mean_sdl, fun.args = list(mult=1), 
                 geom="pointrange", color="red")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-error-bar-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-error-bar-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_dotplot-error-bar-3.png" width="240" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-error-bars-quick-start-guide-r-software-and-data-visualization">ggplot2 error bars</a>.</span></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_errorbarh()</em>, <em>geom_errorbar()</em>, <em>geom_linerange()</em>, <em>geom_pointrange()</em>, <em>geom_crossbar()</em>, <em>stat_summary()</em></li>
</ul>
</div>
</div>
<div id="two-variables-maps" class="section level2">
<h2>Two variables: Maps</h2>
<p>The function <strong>geom_map()</strong> can be used to create a map with <strong>ggplot2</strong>. The R package <strong>map</strong> is required. It contains geographical information useful for drawing easily maps in ggplot2.</p>
<p>Install <strong>map</strong> package (if you don’t have it):</p>
<pre class="r"><code>install.packages("map")</code></pre>
<p>In the following R code, we’ll create USA map and <strong>USArrests</strong> crime data to shade each region.</p>
<pre class="r"><code># Prepare the data
crimes <- data.frame(state = tolower(rownames(USArrests)), 
                     USArrests)
library(reshape2) # for melt
crimesm <- melt(crimes, id = 1)
# Get map data
require(maps) 
map_data <- map_data("state")
# Plot the map with Murder data
ggplot(crimes, aes(map_id = state)) + 
  geom_map(aes(fill = Murder), map = map_data) + 
  expand_limits(x = map_data$long, y = map_data$lat)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_map-1.png" width="432" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="http://docs.ggplot2.org/current/geom_map.html">ggplot2 map</a>.</span></p>
<p><strong>Key function:</strong> <em>geom_map()</em></p>
</div>
<div id="three-variables" class="section level2">
<h2>Three variables</h2>
<p>The <strong>mtcars</strong> data set we’ll be used. We first compute a <strong>correlation matrix</strong>, which will be visualized using specific ggplot2 functions.</p>
<p><strong>Prepare the data</strong>:</p>
<pre class="r"><code>df <- mtcars[, c(1,3,4,5,6,7)]
# Correlation matrix
cormat <- round(cor(df),2)
# Melt the correlation matrix
require(reshape2)
cormat <- melt(cormat)
head(cormat)</code></pre>
<pre><code>##   Var1 Var2 value
## 1  mpg  mpg  1.00
## 2 disp  mpg -0.85
## 3   hp  mpg -0.78
## 4 drat  mpg  0.68
## 5   wt  mpg -0.87
## 6 qsec  mpg  0.42</code></pre>
<p><span class="success">We start by creating a plot, named <strong>g</strong>, that we’ll finish in the next section by adding a layer. </span></p>
<pre class="r"><code>g <- ggplot(cormat, aes(x = Var1, y = Var2))</code></pre>
<br/>
<div class="block">
<p>Possible layers include:</p>
<ul>
<li><strong>geom_tile()</strong>: Tile plane with rectangles (similar to <strong>levelplot</strong> and <strong>image</strong>)</li>
<li><strong>geom_raster()</strong>: High-performance rectangular tiling. This is a special case of <strong>geom_tile</strong> where all tiles are the same size.</li>
</ul>
</div>
<p><br/></p>
<p>We’ll use the function <strong>geom_tile()</strong> to visualize a correlation matrix.</p>
<p><strong>Compute and visualize correlation matrix</strong>:</p>
<pre class="r"><code># 1. Compute correlation
cormat <- round(cor(df),2)
# 2. Reorder the correlation matrix by 
# Hierarchical clustering
hc <- hclust(as.dist(1-cormat)/2)
cormat.ord <- cormat[hc$order, hc$order]
# 3. Get the upper triangle
cormat.ord[lower.tri(cormat.ord)]<- NA
# 4. Melt the correlation matrix
require(reshape2)
melted_cormat <- melt(cormat.ord, na.rm = TRUE)
# Create the heatmap
ggplot(melted_cormat, aes(Var2, Var1, fill = value))+
  geom_tile(color = "white")+
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
   midpoint = 0, limit = c(-1,1), space = "Lab",
   name="Pearson\nCorrelation") + # Change gradient color
  theme_minimal()+ # minimal theme
 theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                  size = 12, hjust = 1))+
 coord_fixed()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2_tile-1.png" width="480" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-quick-correlation-matrix-heatmap-r-software-and-data-visualization">ggplot2 correlation matrix heatmap</a>.</span></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_tile()</em>, <em>geom_raster()</em></li>
</ul>
</div>
<div id="other-types-of-graphs" class="section level2">
<h2>Other types of graphs</h2>
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/ggplot2-pie-chart-quick-start-guide-r-software-and-data-visualization"><strong>Pie chart</strong></a>: (click to read more)</li>
</ul>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-pie-chart-1.png" width="384" /></p>
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/ggally-r-package-extension-to-ggplot2-for-correlation-matrix-and-survival-plots-r-software-and-data-visualization"><strong>Survival curves</strong></a>: (click to read more)</li>
</ul>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-ggplot2-survival-curves-1.png" width="384" /></p>
</div>
<div id="graphical-primitives-polygon-path-ribbon-segment-rectangle" class="section level2">
<h2>Graphical primitives: polygon, path, ribbon, segment, rectangle</h2>
<p>This section describes how to add <strong>graphical elements</strong> to a plot. The functions below we’ll be used:</p>
<br/>
<div class="block">
<ul>
<li><strong>geom_polygon()</strong>: Add <strong>polygon</strong>, a filled path</li>
<li><strong>geom_path()</strong>: <strong>Connect observations</strong> in original order</li>
<li><strong>geom_ribbon()</strong>: Add <strong>ribbons</strong>, y range with continuous x values.</li>
<li><strong>geom_segment()</strong>: Add a single line <strong>segments</strong></li>
<li><strong>geom_curve()</strong>: Add curves</li>
<li><strong>geom_rect()</strong>: Add a 2d <strong>rectangles</strong>.</li>
</ul>
</div>
<p><br/></p>
<ol style="list-style-type: decimal">
<li>The R code below draws <em>France map</em> using <strong>geom_polygon()</strong>:</li>
</ol>
<pre class="r"><code>require(maps)
france = map_data('world', region = 'France')
ggplot(france, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = 'white', colour = 'black')</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_polygon-1.png" width="288" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em>, <em>linetype</em> and <em>size</em>.</span></p>
<ol start="2" style="list-style-type: decimal">
<li>The following R code uses <strong>econimics</strong> data [in <strong>ggplot2</strong>] and produces <strong>path</strong>, <strong>ribbon</strong> and <strong>rectangles</strong>.</li>
</ol>
<pre class="r"><code>h <- ggplot(economics, aes(date, unemploy))
# Path
h + geom_path()
# Ribbon
h + geom_ribbon(aes(ymin = unemploy-900, ymax = unemploy+900),
                fill = "steelblue") +
  geom_path(size = 0.8)
# Rectangle
h + geom_rect(aes(xmin = as.Date('1980-01-01'), ymin = -Inf, 
                 xmax = as.Date('1985-01-01'), ymax = Inf),
             fill = "steelblue") +
  geom_path(size = 0.8) </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_path-geom_ribbon-geom_rect-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_path-geom_ribbon-geom_rect-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_path-geom_ribbon-geom_rect-3.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>fill</em> (for ribbon only), <em>linetype</em> and <em>size</em>.</span></p>
<ol start="3" style="list-style-type: decimal">
<li><strong>Add line segments</strong> between points (x1, y1) and (x2, y2):</li>
</ol>
<pre class="r"><code># Create a scatter plot
i <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
# Add segment
i + geom_segment(aes(x = 2, y = 15, xend = 3, yend = 15))
# Add arrow
require(grid)
i + geom_segment(aes(x = 5, y = 30, xend = 3.5, yend = 25),
                  arrow = arrow(length = unit(0.5, "cm")))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_segment-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_segment-2.png" width="259.2" /></p>
<p><span class="success">To customize the plot, the following arguments can be used: <em>alpha</em>, <em>color</em>, <em>linetype</em> and <em>size</em>. Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines#geom_segment-add-a-line-segment">ggplot2 add line segment</a>.</span></p>
<ol start="4" style="list-style-type: decimal">
<li><strong>Add curves</strong> between points (x1, y1) and (x2, y2):</li>
</ol>
<pre class="r"><code>i + geom_curve(aes(x = 2, y = 15, xend = 3, yend = 15))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_curve-1.png" width="259.2" /></p>
<ul>
<li><strong>Key functions</strong>: <em>geom_path()</em>, <em>geom_ribbon()</em>, <em>geom_rect()</em>, <em>geom_segment()</em></li>
</ul>
</div>
</div>
<div id="graphical-parameters" class="section level1">
<h1>Graphical parameters</h1>
<div id="main-title-axis-labels-and-legend-title" class="section level2">
<h2>Main title, axis labels and legend title</h2>
<p>We start by creating a box plot using the data set <strong>ToothGrowth</strong>:</p>
<pre class="r"><code># Convert the variable dose from numeric to factor variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()</code></pre>
<p>The function below can be used for changing <strong>titles</strong> and <strong>labels</strong>:</p>
<br/>
<div class="block">
<ul>
<li>p + <strong>ggtitle</strong>(“New main title”): Adds a main title above the plot</li>
<li>p + <strong>xlab</strong>(“New X axis label”): Changes the X axis label</li>
<li>p + <strong>ylab</strong>(“New Y axis label”): Changes the Y axis label</li>
<li>p + <strong>labs</strong>(title = “New main title”, x = “New X axis label”, y = “New Y axis label”): Changes main title and axis labels</li>
</ul>
</div>
<p><br/></p>
<p><span class="notice">The function <strong>labs</strong>() can be also used to change the <strong>legend title</strong>.</span></p>
<ol style="list-style-type: decimal">
<li><strong>Change main title and axis labels</strong></li>
</ol>
<pre class="r"><code># Default plot
print(p)
# Change title and axis labels
p <- p +labs(title="Plot of length \n by dose",
        x ="Dose (mg)", y = "Teeth length")
p</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-title-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-title-2.png" width="240" /></p>
<p><span class="warning">Note that, <strong>\n</strong> is used to split long title into multiple lines.</span></p>
<ol start="2" style="list-style-type: decimal">
<li><strong>Change the appearance of labels</strong>:</li>
</ol>
<p>To change the appearance(<strong>color</strong>, <strong>size</strong> and <strong>face</strong> ) of labels, the functions <strong>theme()</strong> and <strong>element_text()</strong> can be used.</p>
<p>The function <strong>element_blank()</strong> hides the labels.</p>
<pre class="r"><code># Change the appearance of labels
p + theme(
plot.title = element_text(color="red", size=14, face="bold.italic"),
axis.title.x = element_text(color="blue", size=14, face="bold"),
axis.title.y = element_text(color="#993333", size=14, face="bold")
)
# Hide labels
p + theme(plot.title = element_blank(), 
          axis.title.x = element_blank(),
          axis.title.y = element_blank())</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-color-size-face-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-color-size-face-2.png" width="240" /></p>
<ol start="3" style="list-style-type: decimal">
<li><strong>Change legend titles</strong>: Scale functions (fill, color, size, shape, …) are used to update <strong>legend titles</strong>.</li>
</ol>
<pre class="r"><code># Default plot
p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose))+
  geom_boxplot()
p
# Modify legend titles
p + labs(fill = "Dose (mg)")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-legend-titles-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-legend-titles-2.png" width="259.2" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-title-main-axis-and-legend-titles">ggplot2 title: main, axis and legend titles</a>.</span></p>
</div>
<div id="legend-position-and-appearance" class="section level2">
<h2>Legend position and appearance</h2>
<ol style="list-style-type: decimal">
<li>Create a box plot</li>
</ol>
<pre class="r"><code># Convert the variable dose from numeric to factor variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose))+
  geom_boxplot()</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>Change legend position and appearance</li>
</ol>
<pre class="r"><code># Change legend position: "left","top", "right", "bottom", "none"
p + theme(legend.position="top")
# Remove legends
p + theme(legend.position = "none")
# Change the appearance of legend title and labels
p + theme(legend.title = element_text(colour="blue"),
          legend.text = element_text(colour="red"))
# Change legend box background color
p + theme(legend.background = element_rect(fill="lightblue"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-legend-position-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-legend-position-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-legend-position-3.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-legend-position-4.png" width="240" /></p>
<ol start="3" style="list-style-type: decimal">
<li>Customize legends using scale functions
<ul>
<li>Change the order of legend items: <strong>scale_x_discrete()</strong></li>
<li>Set legend title and labels: <strong>scale_fill_discrete()</strong></li>
</ul></li>
</ol>
<pre class="r"><code># Change the order of legend items
p + scale_x_discrete(limits=c("2", "0.5", "1"))
# Set legend title and labels
p + scale_fill_discrete(name = "Dose", labels = c("A", "B", "C"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-legend-item-order-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-legend-item-order-2.png" width="240" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-legend-easy-steps-to-change-the-position-and-the-appearance-of-a-graph-legend-in-r-software">ggplot2 legend position and appearance</a>.</span></p>
</div>
<div id="change-colors-automatically-and-manually" class="section level2">
<h2>Change colors automatically and manually</h2>
<p><em>ToothGrowth</em> and <em>mtcars</em> data sets are used in the examples below.</p>
<pre class="r"><code># Convert dose and cyl columns from numeric to factor variables
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
mtcars$cyl <- as.factor(mtcars$cyl)</code></pre>
<p>We start by creating some plots which will be finished hereafter:</p>
<pre class="r"><code># Box plot
bp <- ggplot(ToothGrowth, aes(x=dose, y=len))
# Scatter plot
sp <- ggplot(mtcars, aes(x=wt, y=mpg))</code></pre>
<ol style="list-style-type: decimal">
<li><strong>Draw plots: change fill and outline colors</strong></li>
</ol>
<pre class="r"><code># box plot
bp + geom_boxplot(fill='steelblue', color="red")
# scatter plot
sp + geom_point(color='darkblue')</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-unique-color-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-unique-color-2.png" width="192" /></p>
<ol start="2" style="list-style-type: decimal">
<li><strong>Change color by groups</strong> using the levels of <strong>dose</strong> variable</li>
</ol>
<pre class="r"><code># Box plot
bp <- bp + geom_boxplot(aes(fill = dose))
bp
# Scatter plot
sp <- sp + geom_point(aes(color = cyl))
sp</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-group-color-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-group-color-2.png" width="240" /></p>
<ol start="3" style="list-style-type: decimal">
<li><strong>Change colors manually</strong>:</li>
</ol>
<ul>
<li><strong>scale_fill_manual</strong>() for box plot, bar plot, violin plot, etc</li>
<li><strong>scale_color_manual</strong>() for lines and points</li>
</ul>
<pre class="r"><code># Box plot
bp + scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"))
# Scatter plot
sp + scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-color-manual-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-color-manual-2.png" width="240" /></p>
<ol start="4" style="list-style-type: decimal">
<li><strong>Use RColorBrewer palettes</strong>: (Read more about RColorBrewer: <a href="https://www.sthda.com/english/english/wiki/colors-in-r">color in R</a>)</li>
</ol>
<ul>
<li><strong>scale_fill_brewer</strong>() for box plot, bar plot, violin plot, etc</li>
<li><strong>scale_color_brewer</strong>() for lines and points</li>
</ul>
<pre class="r"><code># Box plot
bp + scale_fill_brewer(palette="Dark2")
# Scatter plot
sp + scale_color_brewer(palette="Dark2")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-group-color-rcolorbrewer-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-group-color-rcolorbrewer-2.png" width="240" /></p>
<p>Available color palettes in the RColorBrewer package:</p>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/images/rcolorbrewer.png" alt="RColorBrewer palettes" /><p class="caption">RColorBrewer palettes</p>
</div>
<ol start="5" style="list-style-type: decimal">
<li><strong>Use gray colors</strong>:</li>
</ol>
<ul>
<li><strong>scale_fill_grey()</strong> for box plot, bar plot, violin plot, etc</li>
<li><strong>scale_colour_grey()</strong> for points, lines, etc</li>
</ul>
<pre class="r"><code># Box plot
bp + scale_fill_grey() + theme_classic()
# Scatter plot
sp + scale_color_grey() + theme_classic()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-color-grey-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-color-grey-2.png" width="240" /></p>
<ol start="6" style="list-style-type: decimal">
<li><strong>Gradient or continuous colors</strong>:</li>
</ol>
<p>Plots can be colored according to the values of a continuous variable using the functions :</p>
<ul>
<li><strong>scale_color_gradient</strong>(), <strong>scale_fill_gradient</strong>() for sequential gradients between two colors</li>
<li><strong>scale_color_gradient2</strong>(), <strong>scale_fill_gradient2</strong>() for diverging gradients</li>
<li><strong>scale_color_gradientn</strong>(), <strong>scale_fill_gradientn</strong>() for gradient between n colors</li>
</ul>
<p><strong>Gradient colors for scatter plots</strong>: The graphs are colored using the <em>qsec</em> continuous variable :</p>
<pre class="r"><code># Color by qsec values
sp2<-ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point(aes(color = qsec))
sp2
# Change the low and high colors
# Sequential color scheme
sp2+scale_color_gradient(low="blue", high="red")
# Diverging color scheme
mid<-mean(mtcars$qsec)
sp2+scale_color_gradient2(midpoint=mid, low="blue", mid="white",
                          high="red", space = "Lab" )</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-color-gradient-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-color-gradient-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-color-gradient-3.png" width="240" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually">ggplot2 colors</a>.</span></p>
</div>
<div id="point-shapes-colors-and-size" class="section level2">
<h2>Point shapes, colors and size</h2>
<p>The different <strong>points shapes</strong> commonly used in <strong>R</strong> are shown in the image below:</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/images/points-symbols.png" style="width:250px" alt ="r point shape"/></p>
<p><em>mtcars</em> data is used in the following examples.</p>
<pre class="r"><code># Convert cyl as factor variable
mtcars$cyl <- as.factor(mtcars$cyl)</code></pre>
<p>Create a scatter plot and change point shapes, colors and size:</p>
<pre class="r"><code># Basic scatter plot
ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point(shape = 18, color = "steelblue", size = 4)
# Change point shapes and colors by groups
ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point(aes(shape = cyl, color = cyl))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-point-shape-scatter-plot-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-point-shape-scatter-plot-2.png" width="240" /></p>
<p>It’s also possible to manually change the appearance of points:</p>
<ul>
<li><strong>scale_shape_manual</strong>() : to change point shapes</li>
<li><strong>scale_color_manual</strong>() : to change point colors</li>
<li><strong>scale_size_manual</strong>() : to change the size of points</li>
</ul>
<pre class="r"><code># Change colors and shapes manually
ggplot(mtcars, aes(x=wt, y=mpg, group=cyl)) +
  geom_point(aes(shape=cyl, color=cyl), size=2)+
  scale_shape_manual(values=c(3, 16, 17))+
  scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
  theme(legend.position="top")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scatter-plot-multiple-groups-manual-scale-1.png" width="240" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-point-shapes">ggplot2 point shapes, colors and size</a>.</span></p>
</div>
<div id="add-text-annotations-to-a-graph" class="section level2">
<h2>Add text annotations to a graph</h2>
<p>There are three important functions for adding texts to a plot:</p>
<ul>
<li><strong>geom_text</strong>(): Textual annotations</li>
<li><strong>annotate</strong>(): Textual annotations</li>
<li><strong>annotation_custom</strong>(): Static annotations that are the same in every panel. These annotations are not affected by the plot scales.</li>
</ul>
<p>A subset of <strong>mtcars</strong> data is used:</p>
<pre class="r"><code>set.seed(1234)
df <- mtcars[sample(1:nrow(mtcars), 10), ]
df$cyl <- as.factor(df$cyl)</code></pre>
<p>Scatter plots with textual annotations:</p>
<pre class="r"><code># Scatter plot
sp <- ggplot(df, aes(x=wt, y=mpg))+ geom_point() 
# Add text, change colors by groups
sp + geom_text(aes(label = rownames(df), color = cyl),
               size = 3, vjust = -1)
# Add text at a particular coordinate
sp + geom_text(x = 3, y = 30, label = "Scatter plot",
              color="red")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_text-appearance-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-geom_text-appearance-2.png" width="259.2" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-texts-add-text-annotations-to-a-graph-in-r-software">ggplot2 text: Add text annotations to a graph</a>.</span></p>
</div>
<div id="line-types" class="section level2">
<h2>Line types</h2>
<p>The different line types available in <strong>R software</strong> are : <strong>“blank”, “solid”, “dashed”, “dotted”, “dotdash”, “longdash”, “twodash”</strong>.</p>
<p><span class="warning">Note that, line types can be also specified using numbers : <strong>0, 1, 2, 3, 4, 5, 6</strong>. 0 is for “blank”, 1 is for “solid”, 2 is for “dashed”, ….</span></p>
<p>A graph of the different line types is shown below :</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-line-type-1.png" width="384" /></p>
<ol style="list-style-type: decimal">
<li><strong>Basic line plot</strong></li>
</ol>
<pre class="r"><code># Create some data
df <- data.frame(time=c("breakfeast", "Lunch", "Dinner"),
                bill=c(10, 30, 15))
head(df)</code></pre>
<pre><code>##         time bill
## 1 breakfeast   10
## 2      Lunch   30
## 3     Dinner   15</code></pre>
<pre class="r"><code># Basic line plot with points
# Change the line type
ggplot(data=df, aes(x=time, y=bill, group=1)) +
  geom_line(linetype = "dashed")+
  geom_point()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-basic-line-plot-1.png" width="240" /></p>
<ol start="2" style="list-style-type: decimal">
<li><strong>Line plots with multiple groups</strong></li>
</ol>
<pre class="r"><code># Create some data
df2 <- data.frame(sex = rep(c("Female", "Male"), each=3),
                  time=c("breakfeast", "Lunch", "Dinner"),
                  bill=c(10, 30, 15, 13, 40, 17) )
head(df2)</code></pre>
<pre><code>##      sex       time bill
## 1 Female breakfeast   10
## 2 Female      Lunch   30
## 3 Female     Dinner   15
## 4   Male breakfeast   13
## 5   Male      Lunch   40
## 6   Male     Dinner   17</code></pre>
<pre class="r"><code># Line plot with multiple groups
# Change line types and colors by groups (sex)
ggplot(df2, aes(x=time, y=bill, group=sex)) +
  geom_line(aes(linetype = sex, color = sex))+
  geom_point(aes(color=sex))+
  theme(legend.position="top")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-line-plot-multiple-groups-1.png" width="240" /></p>
<p>The functions below can be used to change the appearance of line types manually:</p>
<ul>
<li><strong>scale_linetype_manual</strong>() : to change line types</li>
<li><strong>scale_color_manual</strong>() : to change line colors</li>
<li><strong>scale_size_manual</strong>() : to change the size of lines</li>
</ul>
<pre class="r"><code># Change line types, colors and sizes
ggplot(df2, aes(x=time, y=bill, group=sex)) +
  geom_line(aes(linetype=sex, color=sex, size=sex))+
  geom_point()+
  scale_linetype_manual(values=c("twodash", "dotted"))+
  scale_color_manual(values=c('#999999','#E69F00'))+
  scale_size_manual(values=c(1, 1.5))+
  theme(legend.position="top")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-multiple-groups-manual-scale-1.png" width="288" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software">ggplot2 line types</a>.</span></p>
</div>
<div id="themes-and-background-colors" class="section level2">
<h2>Themes and background colors</h2>
<p>ToothGrowth data is used :</p>
<pre class="r"><code># Convert the column dose from numeric to factor variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)</code></pre>
<ol style="list-style-type: decimal">
<li><strong>Create a box plot</strong></li>
</ol>
<pre class="r"><code>p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_boxplot()</code></pre>
<ol start="2" style="list-style-type: decimal">
<li><strong>Change plot themes</strong></li>
</ol>
<p>Several functions are available in ggplot2 package for changing quickly the theme of plots :</p>
<ul>
<li><strong>theme_gray</strong>(): gray background color and white grid lines</li>
<li><strong>theme_bw</strong>() : white background and gray grid lines</li>
</ul>
<pre class="r"><code>p + theme_gray(base_size = 14)
p + theme_bw()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-theme-gray-theme-bw-1.png" alt="ggplot2 background color, theme_gray and theme_bw, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-theme-gray-theme-bw-2.png" alt="ggplot2 background color, theme_gray and theme_bw, R programming" width="192" />
<p class="caption">
ggplot2 background color, theme_gray and theme_bw, R programming
</p>
</div>
<ul>
<li><strong>theme_linedraw</strong> : black lines around the plot</li>
<li><strong>theme_light</strong> : light gray lines and axis (more attention towards the data)</li>
</ul>
<pre class="r"><code>p + theme_linedraw()
p + theme_light()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-theme-linedraw-theme-light-1.png" alt="ggplot2 background color, theme_linedraw and theme_light, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-theme-linedraw-theme-light-2.png" alt="ggplot2 background color, theme_linedraw and theme_light, R programming" width="192" />
<p class="caption">
ggplot2 background color, theme_linedraw and theme_light, R programming
</p>
</div>
<ul>
<li><strong>theme_minimal</strong>: no background annotations</li>
<li><strong>theme_classic</strong> : theme with axis lines and no grid lines</li>
</ul>
<pre class="r"><code>p + theme_minimal()
p + theme_classic()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-theme-minimal-theme-classic-1.png" alt="ggplot2 background color, theme_minimal and theme_classic, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-theme-minimal-theme-classic-2.png" alt="ggplot2 background color, theme_minimal and theme_classic, R programming" width="192" />
<p class="caption">
ggplot2 background color, theme_minimal and theme_classic, R programming
</p>
</div>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-themes-and-background-colors-the-3-elements">ggplot2 themes and background colors</a>.</span></p>
</div>
<div id="axis-limits-minimum-and-maximum-values" class="section level2">
<h2>Axis limits: Minimum and Maximum values</h2>
<p>Create a plot:</p>
<pre class="r"><code>p <- ggplot(cars, aes(x = speed, y = dist)) + geom_point()</code></pre>
<p>Different functions are available for setting axis limits:</p>
<br/>
<div class="block">
<ol style="list-style-type: decimal">
<li><strong>Without clipping (preferred)</strong>:
<ul>
<li>p + <strong>coord_cartesian</strong>(xlim = c(5, 20), ylim = (0, 50)): <strong>Cartesian coordinates</strong>. The Cartesian coordinate system is the most common type of coordinate system. It will zoom the plot (like you’re looking at it with a magnifying glass), without clipping the data.</li>
</ul></li>
<li><strong>With clipping the data</strong> (removes unseen data points): Observations not in this range will be dropped completely and not passed to any other layers.
<ul>
<li>p + <strong>xlim</strong>(5, 20) + <strong>ylim</strong>(0, 50)</li>
<li>p + <strong>scale_x_continuous</strong>(limits = c(5, 20)) + <strong>scale_y_continuous</strong>(limits = c(0, 50))</li>
</ul></li>
<li><strong>Expand the plot limits with data</strong>: This function is a thin wrapper around <strong>geom_blank()</strong> that makes it easy to add data to a plot.
<ul>
<li>p + <strong>expand_limits</strong>(x = 0, y = 0): set the intercept of x and y axes at (0,0)</li>
<li>p + <strong>expand_limits</strong>(x = c(5, 50), y = c(0, 150))</li>
</ul></li>
</ol>
</div>
<p><br/></p>
<pre class="r"><code># Default plot
print(p)
# Change axis limits using coord_cartesian()
p + coord_cartesian(xlim =c(5, 20), ylim = c(0, 50))
# Use xlim() and ylim()
p + xlim(5, 20) + ylim(0, 50)
# Expand limits
p + expand_limits(x = c(5, 50), y = c(0, 150))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-axis-limits-1.png" width="220.8" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-axis-limits-2.png" width="220.8" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-axis-limits-3.png" width="220.8" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-axis-limits-4.png" width="220.8" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-axis-scales-and-transformations">ggplot2 axis limits</a>.</span></p>
<p><span class="warning">Note that, <strong>date axis</strong> limits can be set using the functions <strong>scale_x_date</strong>() and <strong>scale_y_date</strong>(). Read more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-axis-scales-and-transformations#format-date-axes">ggplot2 date axis</a>.</span></p>
</div>
<div id="axis-transformations-log-and-sqrt-scales" class="section level2">
<h2>Axis transformations: log and sqrt scales</h2>
<ol style="list-style-type: decimal">
<li>Create a scatter plot:</li>
</ol>
<pre class="r"><code>p <- ggplot(cars, aes(x = speed, y = dist)) + geom_point()</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>ggplot2 functions for continuous axis transformations:</li>
</ol>
<br/>
<div class="block">
<ul>
<li><p>p + <strong>scale_x_log10</strong>(), p + <strong>scale_y_log10</strong>() : Plot x and y on <strong>log10</strong> scale, respectively.</p></li>
<li><p>p + <strong>scale_x_sqrt</strong>(), p + <strong>scale_y_sqrt</strong>() : Plot x and y on <strong>square root</strong> scale, respectively.</p></li>
<li><p>p + <strong>scale_x_reverse</strong>(), p + <strong>scale_y_reverse</strong>() : Reverse direction of axes</p></li>
<li><p>p + <strong>coord_trans</strong>(x =“log10”, y=“log10”) : transformed cartesian coordinate system. Possible values for x and y are “log2”, “log10”, “sqrt”, …</p></li>
<li>p + <strong>scale_x_continuous</strong>(trans=‘log2’), p + <strong>scale_y_continuous</strong>(trans=‘log2’) : another allowed value for the argument <em>trans</em> is ‘log10’</li>
</ul>
</div>
<p><br/></p>
<ol start="3" style="list-style-type: decimal">
<li>The R code below uses the function <strong>scale_xx_continuous</strong>() to transform axis scales:</li>
</ol>
<pre class="r"><code># Default scatter plot
print(p)
# Log transformation using scale_xx()
# possible values for trans : 'log2', 'log10','sqrt'
p + scale_x_continuous(trans='log2') +
  scale_y_continuous(trans='log2')
# Format axis tick mark labels
require(scales)
p + scale_y_continuous(trans = log2_trans(),
    breaks = trans_breaks("log2", function(x) 2^x),
    labels = trans_format("log2", math_format(2^.x)))
# Reverse coordinates
p + scale_y_reverse() </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-axis-transformations-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-axis-transformations-2.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-axis-transformations-3.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-axis-transformations-4.png" width="192" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-axis-scales-and-transformations">ggplot2 axis limits</a>.</span></p>
</div>
<div id="axis-ticks-customize-tick-marks-and-labels-reorder-and-select-items" class="section level2">
<h2>Axis ticks: customize tick marks and labels, reorder and select items</h2>
<ol style="list-style-type: decimal">
<li><strong>Functions for changing the style of axis tick mark labels</strong>:</li>
</ol>
<br/>
<div class="block">
<ul>
<li><strong>element_text</strong>(face, color, size, angle): change text style</li>
<li><strong>element_blank</strong>(): Hide text</li>
</ul>
</div>
<p><br/></p>
<ol start="2" style="list-style-type: decimal">
<li><strong>Create a box plot</strong>:</li>
</ol>
<pre class="r"><code>p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
# print(p)</code></pre>
<ol start="3" style="list-style-type: decimal">
<li><strong>Change the style and the orientation angle of axis tick labels</strong></li>
</ol>
<pre class="r"><code># Change the style of axis tick labels
# face can be "plain", "italic", "bold" or "bold.italic"
p + theme(axis.text.x = element_text(face="bold", color="#993333", 
                           size=14, angle=45),
          axis.text.y = element_text(face="bold", color="blue", 
                           size=14, angle=45))
# Remove axis ticks and tick mark labels
p + theme(
  axis.text.x = element_blank(), # Remove x axis tick labels
  axis.text.y = element_blank(), # Remove y axis tick labels
  axis.ticks = element_blank()) # Remove ticks</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-color-size-face-angle-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-color-size-face-angle-2.png" width="240" /></p>
<ol start="4" style="list-style-type: decimal">
<li><strong>Customize continuous and discrete axes</strong>:</li>
</ol>
<ul>
<li><strong>Discrete axes</strong>
<ul>
<li><strong>scale_x_discrete</strong>(name, breaks, labels, limits): for X axis</li>
<li><strong>scale_y_discrete</strong>(name, breaks, labels, limits): for y axis</li>
</ul></li>
<li><strong>Continuous axes</strong>
<ul>
<li><strong>scale_x_continuous</strong>(name, breaks, labels, limits, trans): for X axis</li>
<li><strong>scale_y_continuous</strong>(name, breaks, labels, limits, trans): for y axis</li>
</ul></li>
</ul>
<p>Briefly, the meaning of the arguments are as follow:</p>
<br/>
<div class="block">
<ul>
<li><strong>name</strong> : x or y axis labels</li>
<li><strong>breaks</strong> : vector specifying which breaks to display</li>
<li><strong>labels</strong> : labels of axis tick marks</li>
<li><strong>limits</strong> : vector indicating the data range</li>
</ul>
(Read more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-axis-ticks-a-guide-to-customize-tick-marks-and-labels#set-axis-ticks-for-discrete-and-continuous-axes">Set axis ticks for discrete and continuous axes</a>)
</div>
<p><br/></p>
<p><em>scale_xx()</em> functions can be used to change the following x or y axis parameters :</p>
<ul>
<li>axis titles</li>
<li>axis limits (data range to display)</li>
<li>choose where tick marks appear</li>
<li>manually label tick marks</li>
</ul>
<p>4.1. <strong>Discrete axes</strong>:</p>
<pre class="r"><code># Change x axis label and the order of items
p + scale_x_discrete(name ="Dose (mg)", 
                    limits=c("2","1","0.5"))
# Change tick mark labels
p + scale_x_discrete(breaks=c("0.5","1","2"),
        labels=c("Dose 0.5", "Dose 1", "Dose 2"))
# Choose which items to display
p + scale_x_discrete(limits=c("0.5", "2"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-the-order-of-items-discrete-axis-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-the-order-of-items-discrete-axis-2.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-change-the-order-of-items-discrete-axis-3.png" width="192" /></p>
<p>4.2. <strong>Continuous axes</strong>:</p>
<pre class="r"><code># Default scatter plot
# +++++++++++++++++
sp <- ggplot(cars, aes(x = speed, y = dist)) + geom_point()
sp
# Customize the plot
#+++++++++++++++++++++
# 1. Change x and y axis labels, and limits
sp <- sp + scale_x_continuous(name="Speed of cars", limits=c(0, 30)) +
  scale_y_continuous(name="Stopping distance", limits=c(0, 150))
# 2. Set tick marks on y axis: a tick mark is shown on every 50
sp + scale_y_continuous(breaks=seq(0, 150, 50))
# Format the labels
# +++++++++++++++++
require(scales)
sp + scale_y_continuous(labels = percent) # labels as percents</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-continuous-axis-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-continuous-axis-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-scale-continuous-axis-3.png" width="240" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-axis-ticks-a-guide-to-customize-tick-marks-and-labels">ggplot2 Axis ticks: tick marks and labels</a>.</span></p>
</div>
<div id="add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines" class="section level2">
<h2>Add straight lines to a plot: horizontal, vertical and regression lines</h2>
<p>The R function below can be used :</p>
<ul>
<li><strong>geom_hline</strong>(yintercept, linetype, color, size): for horizontal lines</li>
<li><strong>geom_vline</strong>(xintercept, linetype, color, size): for vertical lines</li>
<li><strong>geom_abline</strong>(intercept, slope, linetype, color, size): for regression lines</li>
<li><strong>geom_segment()</strong> to add segments</li>
</ul>
<ol style="list-style-type: decimal">
<li><strong>Create a simple scatter plot</strong></li>
</ol>
<pre class="r"><code># Simple scatter plot
sp <- ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()</code></pre>
<ol start="2" style="list-style-type: decimal">
<li><strong>Add straight lines</strong></li>
</ol>
<pre class="r"><code># Add horizontal line at y = 2O; change line type and color
sp + geom_hline(yintercept=20, linetype="dashed", color = "red")
# Add vertical line at x = 3; change line type, color and size
sp + geom_vline(xintercept = 3, color = "blue", size=1.5)
# Add regression line
sp + geom_abline(intercept = 37, slope = -5, color="blue")+
  ggtitle("y = -5X + 37")
# Add horizontal line segment
sp + geom_segment(aes(x = 2, y = 15, xend = 3, yend = 15))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-straight-line-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-straight-line-2.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-straight-line-3.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-straight-line-4.png" width="192" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines">ggplot2 add straight lines to a plot</a>.</span></p>
</div>
<div id="rotate-a-plot-flip-and-reverse" class="section level2">
<h2>Rotate a plot: flip and reverse</h2>
<ul>
<li><strong>coord_flip</strong>(): Create <strong>horizontal plots</strong></li>
<li><strong>scale_x_reverse</strong>(), <strong>scale_y_reverse</strong>(): Reverse the axes</li>
</ul>
<pre class="r"><code>set.seed(1234)
# Basic histogram
hp <- qplot(x=rnorm(200), geom="histogram")
hp
# Horizontal histogram
hp + coord_flip()
# Y axis reversed
hp + scale_y_reverse()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-coord_flip-scale_y_reverse-histogram-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-coord_flip-scale_y_reverse-histogram-2.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-coord_flip-scale_y_reverse-histogram-3.png" width="192" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-rotate-a-graph-reverse-and-flip-the-plot">ggplot2 rotate a graph</a>.</span></p>
</div>
<div id="faceting-split-a-plot-into-a-matrix-of-panels" class="section level2">
<h2>Faceting: split a plot into a matrix of panels</h2>
<p><strong>Facets</strong> divide a plot into subplots based on the values of one or more categorical variables.</p>
<p>There are two main functions for faceting :</p>
<ul>
<li><strong>facet_grid()</strong></li>
<li><strong>facet_wrap()</strong></li>
</ul>
<p>Create a box plot filled by groups:</p>
<pre class="r"><code>p <- ggplot(ToothGrowth, aes(x=dose, y=len, group=dose)) + 
  geom_boxplot(aes(fill=dose))
p</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-basic-boxplot-facets-1.png" width="240" /></p>
<p>The following functions can be used for facets:</p>
<br/>
<div class="block">
<ul>
<li><p>p + <strong>facet_grid</strong>(supp ~ .): Facet in vertical direction based on the levels of <em>supp</em> variable.</p></li>
<li><p>p + <strong>facet_grid</strong>(. ~ supp): Facet in horizontal direction based on the levels of <em>supp</em> variable.</p></li>
<li><p>p + <strong>facet_grid</strong>(dose ~ supp): Facet in horizontal and vertical directions based on two variables: <em>dose</em> and <em>supp</em>.</p></li>
<li>p + <strong>facet_wrap</strong>(~ fl): Place facet side by side into a rectangular layout
</li>
</ul>
</div>
<p><br/></p>
<ol style="list-style-type: decimal">
<li><strong>Facet with one discrete variable</strong>: Split by the levels of the group “supp”</li>
</ol>
<pre class="r"><code># Split in vertical direction
p + facet_grid(supp ~ .)
# Split in horizontal direction
p + facet_grid(. ~ supp)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-facet-with-one-variable-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-facet-with-one-variable-2.png" width="259.2" /></p>
<ol start="2" style="list-style-type: decimal">
<li><strong>Facet with two discrete variables</strong>: Split by the levels of the groups “dose” and “supp”</li>
</ol>
<pre class="r"><code># Facet by two variables: dose and supp.
# Rows are dose and columns are supp
p + facet_grid(dose ~ supp)
# Facet by two variables: reverse the order of the 2 variables
# Rows are supp and columns are dose
p + facet_grid(supp ~ dose)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-facet-with-two-variable-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-facet-with-two-variable-2.png" width="259.2" /></p>
<p><span class="warning">By default, all the panels have the same scales (<em>scales=“fixed”</em>). They can be made independent, by setting scales to <em>free</em>, <em>free_x</em>, or <em>free_y</em>. </span></p>
<pre class="r"><code>p + facet_grid(dose ~ supp, scales='free')</code></pre>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-facet-split-a-plot-into-a-matrix-of-panels">ggplot2 facet : split a plot into a matrix of panels</a>.</span></p>
</div>
<div id="position-adjustements" class="section level2">
<h2>Position adjustements</h2>
<p>Position adjustments determine how to arrange geoms. The argument <strong>position</strong> is used to adjust geom positions:</p>
<pre class="r"><code>p <- ggplot(mpg, aes(fl, fill = drv))
# Arrange elements side by side
p + geom_bar(position = "dodge")
# Stack objects on top of one another, 
# and normalize to have equal height
p + geom_bar(position = "fill")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-position-adjustements-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-position-adjustements-2.png" width="259.2" /></p>
<pre class="r"><code># Stack elements on top of one another
p + geom_bar(position = "stack")
# Add random noise to X and Y position 
# of each element to avoid overplotting
ggplot(mpg, aes(cty, hwy)) + 
  geom_point(position = "jitter")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-position-adjustements-2-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-position-adjustements-2-2.png" width="259.2" /></p>
<p><span class="warning">Note that, each of these position adjustments can be done using a function with manual <strong>width</strong> and <strong>height</strong> argument.</span></p>
<ul>
<li><strong>position_dodge</strong>(width, height)</li>
<li><strong>position_fill</strong>(width, height)</li>
<li><strong>position_stack</strong>(width, height)</li>
<li><strong>position_jitter</strong>(width, height)</li>
</ul>
<pre class="r"><code>p + geom_bar(position = position_dodge(width = 1))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-position-adjustements-3-1.png" width="288" /></p>
<p><span class="success">Learn more here: <a href="https://www.sthda.com/english/english/wiki/ggplot2-barplots-quick-start-guide-r-software-and-data-visualization">ggplot2 bar plots</a>.</span></p>
</div>
<div id="coordinate-systems" class="section level2">
<h2>Coordinate systems</h2>
<pre class="r"><code>p <- ggplot(mpg, aes(fl)) + geom_bar()</code></pre>
<p>The <strong>coordinate systems</strong> in ggplot2 are:</p>
<br/>
<div class="block">
<ul>
<li><p>p + <strong>coord_cartesian</strong>(xlim = NULL, ylim = NULL): <strong>Cartesian coordinate system</strong> (default). It’s the most familiar and common, type of coordinate system.</p></li>
<li><p>p + <strong>coord_fixed</strong>(ratio = 1, xlim = NULL, ylim = NULL): <strong>Cartesian coordinates with fixed relationship between x and y scales</strong>. The ratio represents the number of units on the y-axis equivalent to one unit on the x-axis. The default, ratio = 1, ensures that one unit on the x-axis is the same length as one unit on the y-axis.</p></li>
<li><p>p + <strong>coord_flip</strong>(…): <strong>Flipped cartesian coordinates</strong>. Useful for creating horizontal plot by rotating.</p></li>
<li><p>p + <strong>coord_polar</strong>(theta = “x”, start = 0, direction = 1): <strong>Polar coordinates</strong>. The polar coordinate system is most commonly used for pie charts, which are a stacked bar chart in polar coordinates.</p></li>
<li><p>p + <strong>coord_trans</strong>(x, y, limx, limy): <strong>Transformed cartesian coordinate system</strong>.</p></li>
<li><strong>coord_map</strong>(): Map projections. Provides the full range of map projections available in the mapproj package.</li>
</ul>
</div>
<p><br/></p>
<ol style="list-style-type: decimal">
<li>Arguments for coord_cartesian(), coord_fixed() and coord_flip()
<ul>
<li><strong>xlim</strong>: limits for the x axis</li>
<li><strong>ylim</strong>: limits for the y axis</li>
<li><strong>ratio</strong>: aspect ratio, expressed as y/x</li>
<li><strong>…</strong>: Other arguments passed onto coord_cartesian</li>
</ul></li>
<li>Arguments for coord_polar()
<ul>
<li><strong>theta</strong>: variable to map angle to (x or y)</li>
<li><strong>start</strong>: offset of starting point from 12 o’clock in radians</li>
<li><strong>direction</strong>: 1, clockwise; -1, anticlockwise</li>
</ul></li>
<li>Arguments for coord_trans()
<ul>
<li><strong>x, y</strong>: transformers for x and y axes</li>
<li><strong>limx, limy</strong>: limits for x and y axes.</li>
</ul></li>
</ol>
<pre class="r"><code>p + coord_cartesian(ylim = c(0, 200))
p + coord_fixed(ratio = 1/50)
p + coord_flip()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-coordinate-system-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-coordinate-system-2.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-coordinate-system-3.png" width="192" /></p>
<pre class="r"><code>p + coord_polar(theta = "x", direction = 1)
p + coord_trans(y = "sqrt")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-coordinate-system-2-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-cheatsheet-coordinate-system-2-2.png" width="192" /></p>
</div>
</div>
<div id="extensions-to-ggplot2-r-packages-and-functions" class="section level1">
<h1>Extensions to ggplot2: R packages and functions</h1>
<ul>
<li><p><a href="https://www.sthda.com/english/english/wiki/explore-the-outputs-of-a-principal-component-analysis-r-software-and-data-mining">factoextra</a>: <strong>factoextra : Extract and Visualize the outputs of a multivariate analysis</strong>. <strong>factoextra</strong> provides some easy-to-use functions to extract and visualize the output of PCA (Principal Component Analysis), CA (Correspondence Analysis) and MCA (Multiple Correspondence Analysis) functions from several packages (FactoMineR, stats, ade4 and MASS). It contains also many functions for simplifying clustering analysis workflows. Ggplot2 plotting system is used.</p></li>
<li><p><a href="https://www.sthda.com/english/english/wiki/easyggplot2">easyggplot2</a>: <strong>Perform and customize easily a plot with ggplot2</strong>. The idea behind ggplot2 is seductively simple but the detail is, yes, difficult. To customize a plot, the syntax is sometimes a tiny bit opaque and this raises the level of difficulty. <strong>easyGgplot2</strong> package (which depends on ggplot2) to make and customize quickly plots including box plot, dot plot, strip chart, violin plot, histogram, density plot, scatter plot, bar plot, line plot, etc, …</p></li>
<li><p><a href="https://www.sthda.com/english/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page-r-software-and-data-visualization">ggplot2 - Easy way to mix multiple graphs on the same page</a>: The R package <strong>gridExtra</strong> and <strong>cowplot</strong> are used.</p></li>
<li><p><a href="https://www.sthda.com/english/english/wiki/ggplot2-quick-correlation-matrix-heatmap-r-software-and-data-visualization">ggplot2: Correlation matrix heatmap</a></p></li>
<li><p><a href="https://www.sthda.com/english/english/wiki/ggfortify-extension-to-ggplot2-to-handle-some-popular-packages-r-software-and-data-visualization">ggfortify</a>: Define <strong>fortify</strong> and <strong>autoplot</strong> functions to allow ggplot2 to handle some popular R packages. These include plotting 1) Matrix; 2) Linear Model and Generalized Linear Model; 3) Time Series; 4) PCA/Clustering; 5) Survival Curve; 6) Probability distribution</p></li>
<li><p><a href="https://www.sthda.com/english/english/wiki/ggally-r-package-extension-to-ggplot2-for-correlation-matrix-and-survival-plots-r-software-and-data-visualization">GGally</a>: <strong>GGally</strong> extends ggplot2 by providing several functions including <strong>pairwise correlation matrix</strong>, <strong>scatterplot plot matrix</strong>, <strong>parallel coordinates plot</strong>, <strong>survival plot</strong> and several functions to plot networks.</p></li>
<li><p><a href="https://cran.r-project.org/web/packages/ggRandomForests/index.html">ggRandomForests</a>: Graphical analysis of <strong>random forests</strong> with the randomForestSRC and ggplot2 packages.</p></li>
<li><p><a href="https://cran.r-project.org/web/packages/ggdendro/index.html">ggdendro</a>: Create dendrograms and tree diagrams using ggplot2</p></li>
<li><p><a href="https://cran.r-project.org/web/packages/ggmcmc/index.html">ggmcmc</a>: Tools for Analyzing MCMC Simulations from Bayesian Inference</p></li>
<li><p><a href="https://www.sthda.com/english/english/wiki/ggplot2-themes-and-background-colors-the-3-elements">ggthemes: Package with additional ggplot2 themes and scales</a></p></li>
<li><p><a href="https://github.com/robertwilson190/ggplot2-theme/blob/master/themes.R">Theme used to create journal ready figures easily</a></p></li>
</ul>
</div>
<div id="ressources-to-improve-your-ggplot2-skills" class="section level1">
<h1>Ressources to improve your ggplot2 skills</h1>
<div id="books" class="section level2">
<h2>Books</h2>
<ul>
<li><a href="https://www.sthda.com/english/english/download/download-5+ggplot2-the-elements-for-elegant-data-visualization-in-r.php">ggplot2: The Elements for Elegant Data Visualization in R</a></li>
</ul>
<p><a href="https://www.sthda.com/english/english/download/download-5+ggplot2-the-elements-for-elegant-data-visualization-in-r.php"><img src="https://www.sthda.com/english/sthda/RDoc/images/ggplot2_cover.png" alt = "ggplot2 book" /></a></p>
<ul>
<li><a href="http://www.cookbook-r.com/Graphs/">Cookbook for R</a></li>
</ul>
</div>
<div id="blog-posts" class="section level2">
<h2>Blog posts</h2>
<ul>
<li><a href="http://rpubs.com/hadley/ggplot2-layers">Build a plot layer by layer</a></li>
</ul>
</div>
<div id="cheat-sheets" class="section level2">
<h2>Cheat Sheets</h2>
<ul>
<li><a href="https://www.rstudio.com/wp-content/uploads/2015/11/ggplot2-cheatsheet.pdf">Data Visualization with ggplot2, RStudio cheat sheet</a></li>
<li><a href="http://zevross.com/blog/2014/08/04/beautiful-plotting-in-r-a-ggplot2-cheatsheet-3/">Beautiful plotting in R: A ggplot2 cheatsheet</a></li>
</ul>
</div>
</div>
<div id="acknoweledgment" class="section level1">
<h1>Acknoweledgment</h1>
<ul>
<li>Thanks to Hadley Wickham for ggplot2 package: <a href="http://docs.ggplot2.org/current/">ggplot2 online documentation</a></li>
<li>Thanks to RStudio for <a href="https://www.rstudio.com/wp-content/uploads/2015/11/ggplot2-cheatsheet.pdf">ggplot2 cheatseet</a>)</li>
</ul>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning">This analysis was performed using R (ver. 3.2.4) and ggplot2 (ver 2.1.0). </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:51:54 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[ggplot2 themes and background colors : The 3 elements]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-themes-and-background-colors-the-3-elements</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-themes-and-background-colors-the-3-elements</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#prepare-the-data">Prepare the data</a></li>
<li><a href="#example-of-plot">Example of plot</a></li>
<li><a href="#quick-functions-to-change-plot-themes">Quick functions to change plot themes</a></li>
<li><a href="#customize-the-appearance-of-the-plot-background">Customize the appearance of the plot background</a><ul>
<li><a href="#change-the-colors-of-the-plot-panel-background-and-the-grid-lines">Change the colors of the plot panel background and the grid lines</a></li>
<li><a href="#remove-plot-panel-borders-and-grid-lines">Remove plot panel borders and grid lines</a></li>
<li><a href="#change-the-plot-background-color-not-the-panel">Change the plot background color (not the panel)</a></li>
</ul></li>
<li><a href="#use-a-custom-theme">Use a custom theme</a><ul>
<li><a href="#theme_tufte-a-minimalist-theme">theme_tufte : a minimalist theme</a></li>
<li><a href="#theme_economist-theme-based-on-the-plots-in-the-economist-magazine">theme_economist : theme based on the plots in the economist magazine</a></li>
<li><a href="#theme_stata-theme-based-on-stata-graph-schemes.">theme_stata: theme based on Stata graph schemes.</a></li>
<li><a href="#theme_wsj-theme-based-on-plots-in-the-wall-street-journal">theme_wsj: theme based on plots in the Wall Street Journal</a></li>
<li><a href="#theme_calc-theme-based-on-libreoffice-calc">theme_calc : theme based on LibreOffice Calc</a></li>
<li><a href="#theme_hc-theme-based-on-highcharts-js">theme_hc : theme based on Highcharts JS</a></li>
</ul></li>
<li><a href="#create-a-custom-theme">Create a custom theme</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>This <strong>R tutorial</strong> describes how to change the look of a plot <strong>theme</strong> (<strong>background color</strong>, <strong>panel background color</strong> and <strong>grid lines</strong>) using <strong>R software</strong> and <strong>ggplot2</strong> package. You’ll also learn how to use the base themes of ggplot2 and to create your own theme.</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-logo-1.png" width="384" /></p>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="prepare-the-data" class="section level1">
<h1>Prepare the data</h1>
<p>ToothGrowth data is used :</p>
<pre class="r"><code># Convert the column dose from numeric to factor variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth)</code></pre>
<pre><code>##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5</code></pre>
<p><span class="warning">Make sure that the variable <em>dose</em> is converted as a factor using the above R script.</span></p>
</div>
<div id="example-of-plot" class="section level1">
<h1>Example of plot</h1>
<pre class="r"><code>library(ggplot2)
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
p</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-example-1.png" width="192" /></p>
</div>
<div id="quick-functions-to-change-plot-themes" class="section level1">
<h1>Quick functions to change plot themes</h1>
<p>Several functions are available in ggplot2 package for changing quickly the theme of plots :</p>
<ul>
<li><strong>theme_gray</strong> : gray background color and white grid lines</li>
<li><strong>theme_bw</strong> : white background and gray grid lines</li>
</ul>
<pre class="r"><code>p + theme_gray(base_size = 14)
p + theme_bw()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-gray-theme-bw-1.png" alt="ggplot2 background color, theme_gray and theme_bw, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-gray-theme-bw-2.png" alt="ggplot2 background color, theme_gray and theme_bw, R programming" width="192" />
<p class="caption">
ggplot2 background color, theme_gray and theme_bw, R programming
</p>
</div>
<ul>
<li><strong>theme_linedraw</strong> : black lines around the plot</li>
<li><strong>theme_light</strong> : light gray lines and axis (more attention towards the data)</li>
</ul>
<pre class="r"><code>p + theme_linedraw()
p + theme_light()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-linedraw-theme-light-1.png" alt="ggplot2 background color, theme_linedraw and theme_light, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-linedraw-theme-light-2.png" alt="ggplot2 background color, theme_linedraw and theme_light, R programming" width="192" />
<p class="caption">
ggplot2 background color, theme_linedraw and theme_light, R programming
</p>
</div>
<ul>
<li><strong>theme_minimal</strong>: no background annotations</li>
<li><strong>theme_classic</strong> : theme with axis lines and no grid lines</li>
</ul>
<pre class="r"><code>p + theme_minimal()
p + theme_classic()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-minimal-theme-classic-1.png" alt="ggplot2 background color, theme_minimal and theme_classic, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-minimal-theme-classic-2.png" alt="ggplot2 background color, theme_minimal and theme_classic, R programming" width="192" />
<p class="caption">
ggplot2 background color, theme_minimal and theme_classic, R programming
</p>
</div>
<ul>
<li><strong>theme_void</strong>: Empty theme, useful for plots with non-standard coordinates or for drawings</li>
<li><strong>theme_dark</strong>(): Dark background designed to make colours pop out</li>
</ul>
<pre class="r"><code>p + theme_void()
p + theme_dark()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-void-theme-dark-1.png" alt="ggplot2 background color, theme_void and theme_dark, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-void-theme-dark-2.png" alt="ggplot2 background color, theme_void and theme_dark, R programming" width="192" />
<p class="caption">
ggplot2 background color, theme_void and theme_dark, R programming
</p>
</div>
<p>The functions theme_xx() can take the two arguments below :</p>
<ul>
<li><strong>base_size</strong> : base font size (to change the size of all plot text elements)</li>
<li><strong>base_family</strong> : base font family</li>
</ul>
<p>The size of all the plot text elements can be easily changed at once :</p>
<pre class="r"><code># Example 1
theme_set(theme_gray(base_size = 20))
ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
# Example 2
ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()+
  theme_classic(base_size = 25)</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-font-size-1.png" alt="ggplot2 background color, font size, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-font-size-2.png" alt="ggplot2 background color, font size, R programming" width="192" />
<p class="caption">
ggplot2 background color, font size, R programming
</p>
</div>
<p><span class="warning">Note that, the function <strong>theme_set()</strong> changes the theme for the entire session.</span></p>
</div>
<div id="customize-the-appearance-of-the-plot-background" class="section level1">
<h1>Customize the appearance of the plot background</h1>
<p>The function <strong>theme()</strong> is used to control non-data parts of the graph including :</p>
<ul>
<li><strong>Line elements</strong> : axis lines, minor and major grid lines, plot panel border, axis ticks background color, etc.</li>
<li><strong>Text elements</strong> : plot title, axis titles, legend title and text, axis tick mark labels, etc.</li>
<li><strong>Rectangle elements</strong> : plot background, panel background, legend background, etc.</li>
</ul>
<p>There is a specific function to modify each of these three elements :</p>
<ul>
<li><strong>element_line()</strong> to modify the line elements of the theme</li>
<li><strong>element_text()</strong> to modify the text elements</li>
<li><strong>element_rect()</strong> to change the appearance of the rectangle elements</li>
</ul>
<p><span class="warning">Note that, each of the theme elements can be removed using the function <strong>element_blank()</strong></span></p>
<div id="change-the-colors-of-the-plot-panel-background-and-the-grid-lines" class="section level2">
<h2>Change the colors of the plot panel background and the grid lines</h2>
<ol style="list-style-type: decimal">
<li>The functions <strong>theme()</strong> and <strong>element_rect()</strong> are used for changing the plot panel background color :</li>
</ol>
<pre class="r"><code>p + theme(panel.background = element_rect(fill, colour, size, 
                                          linetype, color))</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>fill</strong> : the fill color for the rectangle</li>
<li><strong>colour</strong>, <strong>color</strong> : border color</li>
<li><strong>size</strong> : border size</li>
</ul>
</div>
<p><br/></p>
<ol start="2" style="list-style-type: decimal">
<li>The appearance of <strong>grid lines</strong> can be changed using the function <strong>element_line()</strong> as follow :</li>
</ol>
<pre class="r"><code># change major and minor grid lines
p + theme(
  panel.grid.major = element_line(colour, size, linetype,
                                   lineend, color),
  panel.grid.minor = element_line(colour, size, linetype,
                                   lineend, color)
  )</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>colour</strong>, <strong>color</strong> : line color</li>
<li><strong>size</strong> : line size</li>
<li><strong>linetype</strong> : line type. <strong>Line type</strong> can be specified using either text (“blank”, “solid”, “dashed”, “dotted”, “dotdash”, “longdash”, “twodash”) or number (0, 1, 2, 3, 4, 5, 6). Note that linetype = “solid” is identical to linetype=1. The available line types in R are described here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software">Line types in R software</a></li>
<li><strong>lineend</strong> : line end. Possible values for line end are : “round”, “butt” or “square”</li>
</ul>
</div>
<p><br/></p>
<p>The R code below illustrates how to modify the appearance of the plot panel background and grid lines :</p>
<pre class="r"><code># Change the colors of plot panel background to lightblue
# and the color of grid lines to white
p + theme(
  panel.background = element_rect(fill = "lightblue",
                                colour = "lightblue",
                                size = 0.5, linetype = "solid"),
  panel.grid.major = element_line(size = 0.5, linetype = 'solid',
                                colour = "white"), 
  panel.grid.minor = element_line(size = 0.25, linetype = 'solid',
                                colour = "white")
  )</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-change-background-colors-grid-lines-1.png" alt="ggplot2 background color, grid lines, R programming" width="192" />
<p class="caption">
ggplot2 background color, grid lines, R programming
</p>
</div>
</div>
<div id="remove-plot-panel-borders-and-grid-lines" class="section level2">
<h2>Remove plot panel borders and grid lines</h2>
<p>It is possible to hide plot panel borders and grid lines with the function <strong>element_blank()</strong> as follow :</p>
<pre class="r"><code># Remove panel borders and grid lines
p + theme(panel.border = element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank())
# Hide panel borders and grid lines
# But change axis line
p + theme(panel.border = element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          axis.line = element_line(size = 0.5, linetype = "solid",
                                   colour = "black"))</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-remove-panel-border-grid-lines-1.png" alt="ggplot2 background color, remove plot panel border, remove grid lines, R programming" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-remove-panel-border-grid-lines-2.png" alt="ggplot2 background color, remove plot panel border, remove grid lines, R programming" width="192" />
<p class="caption">
ggplot2 background color, remove plot panel border, remove grid lines, R programming
</p>
</div>
</div>
<div id="change-the-plot-background-color-not-the-panel" class="section level2">
<h2>Change the plot background color (not the panel)</h2>
<pre class="r"><code>p + theme(plot.background = element_rect(fill = "darkblue"))</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-change-plot-background-color-1.png" alt="ggplot2 background color, R programming" width="192" />
<p class="caption">
ggplot2 background color, R programming
</p>
</div>
</div>
</div>
<div id="use-a-custom-theme" class="section level1">
<h1>Use a custom theme</h1>
<p>You can change the entire appearance of a plot by using a custom theme. Jeffrey Arnold has implemented the library <strong>ggthemes</strong> containing several custom themes.</p>
<p>To use these themes install and load ggthemes package as follow :</p>
<pre class="r"><code>install.packages("ggthemes") # Install 
library(ggthemes) # Load</code></pre>
<p><strong>ggthemes</strong> package provides many custom themes and scales for ggplot.</p>
<div id="theme_tufte-a-minimalist-theme" class="section level2">
<h2>theme_tufte : a minimalist theme</h2>
<pre class="r"><code># scatter plot
ggplot(mtcars, aes(wt, mpg)) +
  geom_point() + geom_rangeframe() + 
  theme_tufte()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-tufte-1.png" alt="ggplot2 theme_tufte, R statistical software" width="240" />
<p class="caption">
ggplot2 theme_tufte, R statistical software
</p>
</div>
</div>
<div id="theme_economist-theme-based-on-the-plots-in-the-economist-magazine" class="section level2">
<h2>theme_economist : theme based on the plots in the economist magazine</h2>
<pre class="r"><code>p <- ggplot(iris, aes(Sepal.Length, Sepal.Width, colour = Species))+
  geom_point()
# Use economist color scales
p + theme_economist() + 
  scale_color_economist()+
  ggtitle("Iris data sets")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-economist-1.png" alt="ggplot2 theme_economist, R statistical software" width="384" />
<p class="caption">
ggplot2 theme_economist, R statistical software
</p>
</div>
<p><span class="warning">Note that, the function <strong>scale_fill_economist()</strong> are also available.</span></p>
</div>
<div id="theme_stata-theme-based-on-stata-graph-schemes." class="section level2">
<h2>theme_stata: theme based on Stata graph schemes.</h2>
<pre class="r"><code>p + theme_stata() + scale_color_stata() +
  ggtitle("Iris data")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-stata-1.png" alt="ggplot2 theme_stata, R statistical software" width="384" />
<p class="caption">
ggplot2 theme_stata, R statistical software
</p>
</div>
<p>The stata theme color scales can be used as follow :</p>
<pre class="r"><code>scale_fill_stata(scheme = "s2color", ...)
scale_color_stata(scheme = "s2color", ...)</code></pre>
<p>The allowed values for the argument <em>scheme</em> are one of “s2color”, “s1rcolor”, “s1color”, or “mono”.</p>
</div>
<div id="theme_wsj-theme-based-on-plots-in-the-wall-street-journal" class="section level2">
<h2>theme_wsj: theme based on plots in the Wall Street Journal</h2>
<pre class="r"><code>p + theme_wsj()+ scale_colour_wsj("colors6")+
  ggtitle("Iris data")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-wsj-1.png" alt="ggplot2 theme_wsj, R statistical software" width="384" />
<p class="caption">
ggplot2 theme_wsj, R statistical software
</p>
</div>
<p>The Wall Street Journal color and fill scales are :</p>
<pre class="r"><code>scale_color_wsj(palette = "colors6", ...)
scale_fill_wsj(palette = "colors6", ...)</code></pre>
<p>The color palette to use can be one of “rgby”, “red_green”, “black_green”, “dem_rep”, “colors6”.</p>
</div>
<div id="theme_calc-theme-based-on-libreoffice-calc" class="section level2">
<h2>theme_calc : theme based on LibreOffice Calc</h2>
<p>These themes are based on the defaults in Google Docs and LibreOffice Calc, respectively.</p>
<pre class="r"><code>p + theme_calc()+ scale_colour_calc()+
  ggtitle("Iris data")</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-calc-1.png" alt="ggplot2 theme_calc, R statistical software" width="480" />
<p class="caption">
ggplot2 theme_calc, R statistical software
</p>
</div>
</div>
<div id="theme_hc-theme-based-on-highcharts-js" class="section level2">
<h2>theme_hc : theme based on Highcharts JS</h2>
<pre class="r"><code>p + theme_hc()+ scale_colour_hc()</code></pre>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-theme-background-color-theme-hc-1.png" alt="ggplot2 theme_hc, R statistical software" width="384" />
<p class="caption">
ggplot2 theme_hc, R statistical software
</p>
</div>
</div>
</div>
<div id="create-a-custom-theme" class="section level1">
<h1>Create a custom theme</h1>
<ol style="list-style-type: decimal">
<li>You can change the theme for the current R session using the function theme_set() as follow :</li>
</ol>
<pre class="r"><code>theme_set(theme_gray(base_size = 20))</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>You can extract and modify the R code of theme_gray :</li>
</ol>
<pre class="r"><code>theme_gray
function (base_size = 11, base_family = "") 
{
 half_line <- base_size/2
theme(
  line = element_line(colour = "black", size = 0.5, 
                      linetype = 1, lineend = "butt"), 
  rect = element_rect(fill = "white", colour = "black",
                      size = 0.5, linetype = 1),
  text = element_text(family = base_family, face = "plain",
                      colour = "black", size = base_size,
                      lineheight = 0.9,  hjust = 0.5,
                      vjust = 0.5, angle = 0, 
                      margin = margin(), debug = FALSE), 
  
  axis.line = element_blank(), 
  axis.text = element_text(size = rel(0.8), colour = "grey30"),
  axis.text.x = element_text(margin = margin(t = 0.8*half_line/2), 
                             vjust = 1), 
  axis.text.y = element_text(margin = margin(r = 0.8*half_line/2),
                             hjust = 1),
  axis.ticks = element_line(colour = "grey20"), 
  axis.ticks.length = unit(half_line/2, "pt"), 
  axis.title.x = element_text(margin = margin(t = 0.8 * half_line,
                                          b = 0.8 * half_line/2)),
  axis.title.y = element_text(angle = 90, 
                              margin = margin(r = 0.8 * half_line,
                                          l = 0.8 * half_line/2)),
  
  legend.background = element_rect(colour = NA), 
  legend.margin = unit(0.2, "cm"), 
  legend.key = element_rect(fill = "grey95", colour = "white"),
  legend.key.size = unit(1.2, "lines"), 
  legend.key.height = NULL,
  legend.key.width = NULL, 
  legend.text = element_text(size = rel(0.8)),
  legend.text.align = NULL,
  legend.title = element_text(hjust = 0), 
  legend.title.align = NULL, 
  legend.position = "right", 
  legend.direction = NULL,
  legend.justification = "center", 
  legend.box = NULL, 
  
  panel.background = element_rect(fill = "grey92", colour = NA),
  panel.border = element_blank(), 
  panel.grid.major = element_line(colour = "white"), 
  panel.grid.minor = element_line(colour = "white", size = 0.25), 
  panel.margin = unit(half_line, "pt"), panel.margin.x = NULL, 
  panel.margin.y = NULL, panel.ontop = FALSE, 
  
  strip.background = element_rect(fill = "grey85", colour = NA),
  strip.text = element_text(colour = "grey10", size = rel(0.8)),
  strip.text.x = element_text(margin = margin(t = half_line,
                                              b = half_line)), 
  strip.text.y = element_text(angle = -90, 
                              margin = margin(l = half_line, 
                                              r = half_line)),
  strip.switch.pad.grid = unit(0.1, "cm"),
  strip.switch.pad.wrap = unit(0.1, "cm"), 
  
  plot.background = element_rect(colour = "white"), 
  plot.title = element_text(size = rel(1.2), 
                            margin = margin(b = half_line * 1.2)),
  plot.margin = margin(half_line, half_line, half_line, half_line),
  complete = TRUE)
}</code></pre>
<p><span class="success">Note that, the function <strong>rel()</strong> modifies the size relative to the base size</span></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4) and <strong>ggplot2</strong> (ver. 2.1.0) </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:49:38 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[ggplot2 line plot : Quick start guide - R software and data visualization]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-line-plot-quick-start-guide-r-software-and-data-visualization</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-line-plot-quick-start-guide-r-software-and-data-visualization</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#basic-line-plots">Basic line plots</a><ul>
<li><a href="#data">Data</a></li>
<li><a href="#create-line-plots-with-points">Create line plots with points</a></li>
</ul></li>
<li><a href="#line-plot-with-multiple-groups">Line plot with multiple groups</a><ul>
<li><a href="#data-1">Data</a></li>
<li><a href="#create-line-plots">Create line plots</a></li>
<li><a href="#change-line-types-by-groups">Change line types by groups</a></li>
<li><a href="#change-line-colors-by-groups">Change line colors by groups</a></li>
</ul></li>
<li><a href="#change-the-legend-position">Change the legend position</a></li>
<li><a href="#line-plot-with-a-numeric-x-axis">Line plot with a numeric x-axis</a></li>
<li><a href="#line-plot-with-dates-on-x-axis">Line plot with dates on x-axis</a></li>
<li><a href="#line-graph-with-error-bars">Line graph with error bars</a></li>
<li><a href="#customized-line-graphs">Customized line graphs</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>This <strong>R tutorial</strong> describes how to create <strong>line plots</strong> using <strong>R software</strong> and <strong>ggplot2</strong> package.</p>
<p>In a line graph, observations are ordered by x value and connected.</p>
<p>The functions <strong>geom_line()</strong>, <strong>geom_step()</strong>, or <strong>geom_path()</strong> can be used.</p>
<p>x value (for x axis) can be :</p>
<ul>
<li>date : for a time series data</li>
<li>texts</li>
<li>discrete numeric values</li>
<li>continuous numeric values</li>
</ul>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-logo-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="384" /></p>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="basic-line-plots" class="section level1">
<h1>Basic line plots</h1>
<div id="data" class="section level2">
<h2>Data</h2>
<p>Data derived from <em>ToothGrowth</em> data sets are used. ToothGrowth describes the effect of Vitamin C on tooth growth in Guinea pigs.</p>
<pre class="r"><code>df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5))
head(df)</code></pre>
<pre><code>##   dose  len
## 1 D0.5  4.2
## 2   D1 10.0
## 3   D2 29.5</code></pre>
<ul>
<li><em>len</em> : Tooth length
</li>
<li><em>dose</em> : Dose in milligrams (0.5, 1, 2)</li>
</ul>
</div>
<div id="create-line-plots-with-points" class="section level2">
<h2>Create line plots with points</h2>
<pre class="r"><code>library(ggplot2)
# Basic line plot with points
ggplot(data=df, aes(x=dose, y=len, group=1)) +
  geom_line()+
  geom_point()
# Change the line type
ggplot(data=df, aes(x=dose, y=len, group=1)) +
  geom_line(linetype = "dashed")+
  geom_point()
# Change the color
ggplot(data=df, aes(x=dose, y=len, group=1)) +
  geom_line(color="red")+
  geom_point()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-basic-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-basic-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-basic-data-visualization-3.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /></p>
<p>Read more on line types : <a href="https://www.sthda.com/english/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software">ggplot2 line types</a></p>
<p>You can add an arrow to the line using the <em>grid</em> package :</p>
<pre class="r"><code>library(grid)
# Add an arrow
ggplot(data=df, aes(x=dose, y=len, group=1)) +
  geom_line(arrow = arrow())+
  geom_point()
# Add a closed arrow to the end of the line
myarrow=arrow(angle = 15, ends = "both", type = "closed")
ggplot(data=df, aes(x=dose, y=len, group=1)) +
  geom_line(arrow=myarrow)+
  geom_point()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-add-arrow-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-add-arrow-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /></p>
<p>Observations can be also connected using the functions <strong>geom_step()</strong> or <strong>geom_path()</strong> :</p>
<pre class="r"><code>ggplot(data=df, aes(x=dose, y=len, group=1)) +
  geom_step()+
  geom_point()
ggplot(data=df, aes(x=dose, y=len, group=1)) +
  geom_path()+
  geom_point()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-geom-step-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-geom-step-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /></p>
<br/>
<div class="block">
<ul>
<li><strong>geom_line</strong> : Connecting observations, ordered by x value</li>
<li><strong>geom_path()</strong> : Observations are connected in original order</li>
<li><strong>geom_step</strong> : Connecting observations by stairs</li>
</ul>
</div>
<p><br/></p>
</div>
</div>
<div id="line-plot-with-multiple-groups" class="section level1">
<h1>Line plot with multiple groups</h1>
<div id="data-1" class="section level2">
<h2>Data</h2>
<p>Data derived from <em>ToothGrowth</em> data sets are used. ToothGrowth describes the effect of Vitamin C on tooth growth in Guinea pigs. Three dose levels of Vitamin C (0.5, 1, and 2 mg) with each of two delivery methods [orange juice (OJ) or ascorbic acid (VC)] are used :</p>
<pre class="r"><code>df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                dose=rep(c("D0.5", "D1", "D2"),2),
                len=c(6.8, 15, 33, 4.2, 10, 29.5))
head(df2)</code></pre>
<pre><code>##   supp dose  len
## 1   VC D0.5  6.8
## 2   VC   D1 15.0
## 3   VC   D2 33.0
## 4   OJ D0.5  4.2
## 5   OJ   D1 10.0
## 6   OJ   D2 29.5</code></pre>
<ul>
<li><em>len</em> : Tooth length
</li>
<li><em>dose</em> : Dose in milligrams (0.5, 1, 2)</li>
<li><em>supp</em> : Supplement type (VC or OJ)</li>
</ul>
</div>
<div id="create-line-plots" class="section level2">
<h2>Create line plots</h2>
<p>In the graphs below, line types, colors and sizes are the same for the two groups :</p>
<pre class="r"><code># Line plot with multiple groups
ggplot(data=df2, aes(x=dose, y=len, group=supp)) +
  geom_line()+
  geom_point()
# Change line types
ggplot(data=df2, aes(x=dose, y=len, group=supp)) +
  geom_line(linetype="dashed", color="blue", size=1.2)+
  geom_point(color="red", size=3)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-multiple-groups-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-multiple-groups-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /></p>
</div>
<div id="change-line-types-by-groups" class="section level2">
<h2>Change line types by groups</h2>
<p>In the graphs below, line types and point shapes are controlled automatically by the levels of the variable <em>supp</em> :</p>
<pre class="r"><code># Change line types by groups (supp)
ggplot(df2, aes(x=dose, y=len, group=supp)) +
  geom_line(aes(linetype=supp))+
  geom_point()
# Change line types and point shapes
ggplot(df2, aes(x=dose, y=len, group=supp)) +
  geom_line(aes(linetype=supp))+
  geom_point(aes(shape=supp))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-multiple-groups-change-line-type-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-multiple-groups-change-line-type-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /></p>
<p>It is also possible to change manually the line types using the function <strong>scale_linetype_manual()</strong>.</p>
<pre class="r"><code># Set line types manually
ggplot(df2, aes(x=dose, y=len, group=supp)) +
  geom_line(aes(linetype=supp))+
  geom_point()+
  scale_linetype_manual(values=c("twodash", "dotted"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-multiple-groups-manual-scale-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="288" /></p>
<p>You can read more on line types here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software">ggplot2 line types</a></p>
<p><span class="warning">If you want to change also point shapes, read this article : <a href="https://www.sthda.com/english/english/wiki/ggplot2-point-shapes">ggplot2 point shapes</a></span></p>
</div>
<div id="change-line-colors-by-groups" class="section level2">
<h2>Change line colors by groups</h2>
<p>Line colors are controlled automatically by the levels of the variable <em>supp</em> :</p>
<pre class="r"><code>p<-ggplot(df2, aes(x=dose, y=len, group=supp)) +
  geom_line(aes(color=supp))+
  geom_point(aes(color=supp))
p</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-change-line-color-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /></p>
<p>It is also possible to <em>change manually line colors</em> using the functions :</p>
<ul>
<li><em>scale_color_manual()</em> : to use custom colors</li>
<li><em>scale_color_brewer()</em> : to use color palettes from <em>RColorBrewer</em> package</li>
<li><em>scale_color_grey()</em> : to use grey color palettes</li>
</ul>
<pre class="r"><code># Use custom color palettes
p+scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))
# Use brewer color palettes
p+scale_color_brewer(palette="Dark2")
# Use grey scale
p + scale_color_grey() + theme_classic()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-group-line-manual-color-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-group-line-manual-color-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-group-line-manual-color-data-visualization-3.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /></p>
<p>Read more on ggplot2 colors here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually">ggplot2 colors</a></p>
</div>
</div>
<div id="change-the-legend-position" class="section level1">
<h1>Change the legend position</h1>
<pre class="r"><code>p <- p + scale_color_brewer(palette="Paired")+
  theme_minimal()
p + theme(legend.position="top")
p + theme(legend.position="bottom")
# Remove legend
p + theme(legend.position="none")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-legend-position-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-legend-position-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-legend-position-data-visualization-3.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /></p>
<p><span class="success">The allowed values for the arguments <strong>legend.position</strong> are : “left”,“top”, “right”, “bottom”.</span></p>
<p>Read more on ggplot legend : <a href="https://www.sthda.com/english/english/wiki/ggplot2-legend-easy-steps-to-change-the-position-and-the-appearance-of-a-graph-legend-in-r-software">ggplot2 legend</a></p>
</div>
<div id="line-plot-with-a-numeric-x-axis" class="section level1">
<h1>Line plot with a numeric x-axis</h1>
<p>If the variable on x-axis is numeric, it can be useful to treat it as a continuous or a factor variable depending on what you want to do :</p>
<pre class="r"><code># Create some data
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                dose=rep(c("0.5", "1", "2"),2),
                len=c(6.8, 15, 33, 4.2, 10, 29.5))
head(df2)</code></pre>
<pre><code>##   supp dose  len
## 1   VC  0.5  6.8
## 2   VC    1 15.0
## 3   VC    2 33.0
## 4   OJ  0.5  4.2
## 5   OJ    1 10.0
## 6   OJ    2 29.5</code></pre>
<pre class="r"><code># x axis treated as continuous variable
df2$dose <- as.numeric(as.vector(df2$dose))
ggplot(data=df2, aes(x=dose, y=len, group=supp, color=supp)) +
  geom_line() + geom_point()+
  scale_color_brewer(palette="Paired")+
  theme_minimal()
# Axis treated as discrete variable
df2$dose<-as.factor(df2$dose)
ggplot(data=df2, aes(x=dose, y=len, group=supp, color=supp)) +
  geom_line() + geom_point()+
  scale_color_brewer(palette="Paired")+
  theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-numeric-x-axis-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-numeric-x-axis-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="240" /></p>
</div>
<div id="line-plot-with-dates-on-x-axis" class="section level1">
<h1>Line plot with dates on x-axis</h1>
<p><em>economics</em> time series data sets are used :</p>
<pre class="r"><code>head(economics)</code></pre>
<pre><code>##         date   pce    pop psavert uempmed unemploy
## 1 1967-06-30 507.8 198712     9.8     4.5     2944
## 2 1967-07-31 510.9 198911     9.8     4.7     2945
## 3 1967-08-31 516.7 199113     9.0     4.6     2958
## 4 1967-09-30 513.3 199311     9.8     4.9     3143
## 5 1967-10-31 518.5 199498     9.7     4.7     3066
## 6 1967-11-30 526.2 199657     9.4     4.8     3018</code></pre>
<p>Plots :</p>
<pre class="r"><code># Basic line plot
ggplot(data=economics, aes(x=date, y=pop))+
  geom_line()
# Plot a subset of the data
ggplot(data=subset(economics, date > as.Date("2006-1-1")), 
       aes(x=date, y=pop))+geom_line()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-time-serie-data-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-time-serie-data-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /></p>
<p>Change line size :</p>
<pre class="r"><code># Change line size
ggplot(data=economics, aes(x=date, y=pop, size=unemploy/pop))+
  geom_line()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-time-serie-data-line-size-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="384" /></p>
</div>
<div id="line-graph-with-error-bars" class="section level1">
<h1>Line graph with error bars</h1>
<p>The function below will be used to calculate the mean and the standard deviation, for the variable of interest, in each group :</p>
<pre class="r"><code>#+++++++++++++++++++++++++
# Function to calculate the mean and the standard deviation
  # for each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of a column containing the variable
  #to be summariezed
# groupnames : vector of column names to be used as
  # grouping variables
data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      sd = sd(x[[col]], na.rm=TRUE))
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- rename(data_sum, c("mean" = varname))
 return(data_sum)
}</code></pre>
<p>Summarize the data :</p>
<pre class="r"><code>df3 <- data_summary(ToothGrowth, varname="len", 
                    groupnames=c("supp", "dose"))
head(df3)</code></pre>
<pre><code>##   supp dose   len       sd
## 1   OJ  0.5 13.23 4.459709
## 2   OJ  1.0 22.70 3.910953
## 3   OJ  2.0 26.06 2.655058
## 4   VC  0.5  7.98 2.746634
## 5   VC  1.0 16.77 2.515309
## 6   VC  2.0 26.14 4.797731</code></pre>
<p>The function <strong>geom_errorbar()</strong> can be used to produce a line graph with error bars :</p>
<pre class="r"><code># Standard deviation of the mean
ggplot(df3, aes(x=dose, y=len, group=supp, color=supp)) + 
    geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.1) +
    geom_line() + geom_point()+
   scale_color_brewer(palette="Paired")+theme_minimal()
# Use position_dodge to move overlapped errorbars horizontally
ggplot(df3, aes(x=dose, y=len, group=supp, color=supp)) + 
    geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.1, 
    position=position_dodge(0.05)) +
    geom_line() + geom_point()+
   scale_color_brewer(palette="Paired")+theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-with-error-bar-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-with-error-bar-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /></p>
</div>
<div id="customized-line-graphs" class="section level1">
<h1>Customized line graphs</h1>
<pre class="r"><code># Simple line plot
# Change point shapes and line types by groups
ggplot(df3, aes(x=dose, y=len, group = supp, shape=supp, linetype=supp))+ 
    geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.1, 
    position=position_dodge(0.05)) +
    geom_line() +
    geom_point()+
    labs(title="Plot of lengthby dose",x="Dose (mg)", y = "Length")+
    theme_classic()
# Change color by groups
# Add error bars
p <- ggplot(df3, aes(x=dose, y=len, group = supp, color=supp))+ 
    geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.1, 
    position=position_dodge(0.05)) +
    geom_line(aes(linetype=supp)) + 
    geom_point(aes(shape=supp))+
    labs(title="Plot of lengthby dose",x="Dose (mg)", y = "Length")+
    theme_classic()
p + theme_classic() + scale_color_manual(values=c('#999999','#E69F00'))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-customized-line-graph-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-customized-line-graph-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /></p>
<p>Change colors manually :</p>
<pre class="r"><code>p + scale_color_brewer(palette="Paired") + theme_minimal()
# Greens
p + scale_color_brewer(palette="Greens") + theme_minimal()
# Reds
p + scale_color_brewer(palette="Reds") + theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-customized-plot-change-color-data-visualization-1.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-customized-plot-change-color-data-visualization-2.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-plot-customized-plot-change-color-data-visualization-3.png" title="ggplot2 line plot - R software and data visualization" alt="ggplot2 line plot - R software and data visualization" width="259.2" /></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>ggplot2</strong> (ver. 1.0.0) </span></p>
</div>
<script>jQuery(document).ready(function () {
  jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:48:46 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[ggplot2 point shapes]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-point-shapes</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-point-shapes</guid>
			<description><![CDATA[<!-- START HTML -->

            
  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#point-shapes-in-r">Point shapes in R</a></li>
<li><a href="#create-some-data">Create some data</a></li>
<li><a href="#basic-scatter-plots">Basic scatter plots</a></li>
<li><a href="#scatter-plots-with-multiple-groups">Scatter plots with multiple groups</a><ul>
<li><a href="#change-the-point-shapes-colors-and-sizes-automatically">Change the point shapes, colors and sizes automatically</a></li>
<li><a href="#change-point-shapes-colors-and-sizes-manually">Change point shapes, colors and sizes manually :</a></li>
</ul></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>This <strong>R tutorial</strong> describes how to change the <strong>point shapes</strong> of a graph generated using <strong>R software</strong> and <strong>ggplot2</strong> package.</p>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="point-shapes-in-r" class="section level1">
<h1>Point shapes in R</h1>
<p>The different <strong>points shapes</strong> commonly used in <strong>R</strong> are illustrated in the figure below :</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/images/points-symbols.png" style="width:250px" alt ="r point shape"/></p>
</div>
<div id="create-some-data" class="section level1">
<h1>Create some data</h1>
<p><em>mtcars</em> data is used in the following examples.</p>
<pre class="r"><code>df <- mtcars[, c("mpg", "cyl", "wt")]
df$cyl <- as.factor(df$cyl)
head(df)</code></pre>
<pre><code>##                    mpg cyl    wt
## Mazda RX4         21.0   6 2.620
## Mazda RX4 Wag     21.0   6 2.875
## Datsun 710        22.8   4 2.320
## Hornet 4 Drive    21.4   6 3.215
## Hornet Sportabout 18.7   8 3.440
## Valiant           18.1   6 3.460</code></pre>
<p><span class="warning">Make sure to convert the column <em>cyl</em> from a numeric to a factor variable.</span></p>
</div>
<div id="basic-scatter-plots" class="section level1">
<h1>Basic scatter plots</h1>
<p>Create a scatter plot and change point shapes using the argument <strong>shape</strong> :</p>
<pre class="r"><code>library(ggplot2)
# Basic scatter plot
ggplot(df, aes(x=wt, y=mpg)) +
  geom_point()
# Change the point shape
ggplot(df, aes(x=wt, y=mpg)) +
  geom_point(shape=18)
# change shape, color, fill, size
ggplot(df, aes(x=wt, y=mpg)) +
  geom_point(shape=23, fill="blue", color="darkred", size=3)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-point-shape-basic-scatter-plot-1.png" title="ggplot2 point shapes in R software" alt="ggplot2 point shapes in R software" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-point-shape-basic-scatter-plot-2.png" title="ggplot2 point shapes in R software" alt="ggplot2 point shapes in R software" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-point-shape-basic-scatter-plot-3.png" title="ggplot2 point shapes in R software" alt="ggplot2 point shapes in R software" width="240" /></p>
<p><span class="warning">Note that, the argument <em>fill</em> can be used only for the point shapes 21 to 25</span></p>
</div>
<div id="scatter-plots-with-multiple-groups" class="section level1">
<h1>Scatter plots with multiple groups</h1>
<div id="change-the-point-shapes-colors-and-sizes-automatically" class="section level2">
<h2>Change the point shapes, colors and sizes automatically</h2>
<p>In the R code below, point shapes, colors and sizes are controlled automatically by the variable <em>cyl</em> :</p>
<pre class="r"><code>library(ggplot2)
# Scatter plot with multiple groups
# shape depends on cyl
ggplot(df, aes(x=wt, y=mpg, group=cyl)) +
  geom_point(aes(shape=cyl))
# Change point shapes and colors
ggplot(df, aes(x=wt, y=mpg, group=cyl)) +
  geom_point(aes(shape=cyl, color=cyl))
# change point shapes,  colors and sizes
ggplot(df, aes(x=wt, y=mpg, group=cyl)) +
  geom_point(aes(shape=cyl, color=cyl, size=cyl))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-point-shape-scatter-plot-multiple-groups-1.png" title="ggplot2 point shapes in R software" alt="ggplot2 point shapes in R software" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-point-shape-scatter-plot-multiple-groups-2.png" title="ggplot2 point shapes in R software" alt="ggplot2 point shapes in R software" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-point-shape-scatter-plot-multiple-groups-3.png" title="ggplot2 point shapes in R software" alt="ggplot2 point shapes in R software" width="259.2" /></p>
</div>
<div id="change-point-shapes-colors-and-sizes-manually" class="section level2">
<h2>Change point shapes, colors and sizes manually :</h2>
<p>The functions below can be used :</p>
<ul>
<li>scale_shape_manual() : to change point shapes</li>
<li>scale_color_manual() : to change point colors</li>
<li>scale_size_manual() : to change the size of points</li>
</ul>
<pre class="r"><code># Change colors and shapes manually
ggplot(df, aes(x=wt, y=mpg, group=cyl)) +
  geom_point(aes(shape=cyl, color=cyl), size=2)+
  scale_shape_manual(values=c(3, 16, 17))+
  scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
  theme(legend.position="top")
# Change the point size manually
ggplot(df, aes(x=wt, y=mpg, group=cyl)) +
  geom_point(aes(shape=cyl, color=cyl, size=cyl))+
  scale_shape_manual(values=c(3, 16, 17))+
  scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
  scale_size_manual(values=c(2,3,4))+
  theme(legend.position="top")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-point-shape-scatter-plot-multiple-groups-manual-scale-1.png" title="ggplot2 point shapes in R software" alt="ggplot2 point shapes in R software" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-point-shape-scatter-plot-multiple-groups-manual-scale-2.png" title="ggplot2 point shapes in R software" alt="ggplot2 point shapes in R software" width="240" /></p>
</div>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>ggplot2</strong> (ver. 1.0.0) </span></p>
</div>
<script>jQuery(document).ready(function () {
  jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:47:45 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[ggplot2 add straight lines to a plot : horizontal, vertical and regression lines]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines</guid>
			<description><![CDATA[<!-- START HTML -->

            
  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#geom_hline-add-horizontal-lines">geom_hline : Add horizontal lines</a></li>
<li><a href="#geom_vline-add-vertical-lines">geom_vline : Add vertical lines</a></li>
<li><a href="#geom_abline-add-regression-lines">geom_abline : Add regression lines</a></li>
<li><a href="#geom_segment-add-a-line-segment">geom_segment : Add a line segment</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/> This <strong>tutorial</strong> describes how to add one or more <strong>straight lines</strong> to a <strong>graph</strong> generated using <strong>R software</strong> and <strong>ggplot2</strong> package.</p>
<p>The R functions below can be used :</p>
<ul>
<li><strong>geom_hline()</strong> for horizontal lines</li>
<li><strong>geom_abline()</strong> for regression lines</li>
<li><strong>geom_vline()</strong> for vertical lines</li>
<li><strong>geom_segment()</strong> to add segments</li>
</ul>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="geom_hline-add-horizontal-lines" class="section level1">
<h1>geom_hline : Add horizontal lines</h1>
<p>A simplified format of the function <strong>geom_hline()</strong> is :</p>
<pre class="r"><code>geom_hline(yintercept, linetype, color, size)</code></pre>
<p>It draws a horizontal line on the current plot at the specified ‘y’ coordinates :</p>
<pre class="r"><code>library(ggplot2)
# Simple scatter plot
sp <- ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()
# Add horizontal line at y = 2O
sp + geom_hline(yintercept=20)
# Change line type and color
sp + geom_hline(yintercept=20, linetype="dashed", color = "red")
# Change line size
sp + geom_hline(yintercept=20, linetype="dashed", 
                color = "red", size=2)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-horizontal-line-1.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-horizontal-line-2.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-horizontal-line-3.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /></p>
<p>Read more on line types here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software">Line types in R</a></p>
</div>
<div id="geom_vline-add-vertical-lines" class="section level1">
<h1>geom_vline : Add vertical lines</h1>
<p>A simplified format of the function <strong>geom_vline()</strong> is :</p>
<pre class="r"><code>geom_vline(xintercept, linetype, color, size)</code></pre>
<p>It draws a vertical line on the current plot at the specified ‘x’ coordinates :</p>
<pre class="r"><code>library(ggplot2)
# Add a vertical line at x = 3
sp + geom_vline(xintercept = 3)
# Change line type, color and size
sp + geom_vline(xintercept = 3, linetype="dotted", 
                color = "blue", size=1.5)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-vertical-line-1.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-vertical-line-2.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /></p>
</div>
<div id="geom_abline-add-regression-lines" class="section level1">
<h1>geom_abline : Add regression lines</h1>
<p>A simplified format of the function <strong>geom_abline()</strong> is :</p>
<pre class="r"><code>geom_abline(intercept, slope, linetype, color, size)</code></pre>
<p>The function <strong>lm()</strong> is used to fit linear models.</p>
<pre class="r"><code># Fit regression line
require(stats)
reg<-lm(mpg ~ wt, data = mtcars)
reg</code></pre>
<pre><code>## 
## Call:
## lm(formula = mpg ~ wt, data = mtcars)
## 
## Coefficients:
## (Intercept)           wt  
##      37.285       -5.344</code></pre>
<pre class="r"><code>coeff=coefficients(reg)
# Equation of the line : 
eq = paste0("y = ", round(coeff[2],1), "*x + ", round(coeff[1],1))
# Plot
sp + geom_abline(intercept = 37, slope = -5)+
  ggtitle(eq)
# Change line type, color and size
sp + geom_abline(intercept = 37, slope = -5, color="red", 
                 linetype="dashed", size=1.5)+
  ggtitle(eq)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-regresion-line-abline-1.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-regresion-line-abline-2.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /></p>
<p><span class="warning">Note that, the function <strong>stat_smooth()</strong> can be used for fitting smooth models to data.</span></p>
<pre class="r"><code>sp + stat_smooth(method="lm", se=FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-stat-smooth-1.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /></p>
</div>
<div id="geom_segment-add-a-line-segment" class="section level1">
<h1>geom_segment : Add a line segment</h1>
<p>A simplified format of the function <strong>geom_segment()</strong> is :</p>
<pre class="r"><code>geom_segment(aes(x, y, xend, yend))</code></pre>
<p>It’s possible to use it as follow :</p>
<pre class="r"><code># Add a vertical line segment
sp + geom_segment(aes(x = 4, y = 15, xend = 4, yend = 27))
# Add horizontal line segment
sp + geom_segment(aes(x = 2, y = 15, xend = 3, yend = 15))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-add-segment-1.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-add-segment-2.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /></p>
<p><span class="warning">Note that, you can add an arrow at the end of the segment. <em>grid</em> package is required</span></p>
<pre class="r"><code>library(grid)
sp + geom_segment(aes(x = 5, y = 30, xend = 3.5, yend = 25),
                  arrow = arrow(length = unit(0.5, "cm")))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-add-straight-lines-add-segment-arrow-1.png" title="add straight lines to a plot using R statistical software and ggplot2" alt="add straight lines to a plot using R statistical software and ggplot2" width="192" /></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning">This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>ggplot2</strong> (ver. )</span></p>
</div>
<script>jQuery(document).ready(function () {
  jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:46:34 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[ggplot2 line types : How to change line types of a graph in R software?]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#line-types-in-r">Line types in R</a></li>
<li><a href="#basic-line-plots">Basic line plots</a><ul>
<li><a href="#generate-some-data">Generate some data</a></li>
<li><a href="#create-line-plots-and-change-line-types">Create line plots and change line types</a></li>
</ul></li>
<li><a href="#line-plot-with-multiple-groups">Line plot with multiple groups</a><ul>
<li><a href="#create-some-data">Create some data</a></li>
<li><a href="#change-globally-the-appearance-of-lines">Change globally the appearance of lines</a></li>
<li><a href="#change-automatically-the-line-types-by-groups">Change automatically the line types by groups</a></li>
<li><a href="#change-manually-the-appearance-of-lines">Change manually the appearance of lines</a></li>
</ul></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>This <strong>R tutorial</strong> describes how to change <strong>line types</strong> of a graph generated using <strong>ggplot2</strong> package.</p>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="line-types-in-r" class="section level1">
<h1>Line types in R</h1>
<p>The different line types available in <strong>R software</strong> are : <strong>“blank”, “solid”, “dashed”, “dotted”, “dotdash”, “longdash”, “twodash”</strong>.</p>
<p><span class="warning">Note that, line types can be also specified using numbers : <strong>0, 1, 2, 3, 4, 5, 6</strong>. 0 is for “blank”, 1 is for “solid”, 2 is for “dashed”, ….</span></p>
<p>A graph of the different line types is shown below :</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-line-type-1.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="384" /></p>
</div>
<div id="basic-line-plots" class="section level1">
<h1>Basic line plots</h1>
<div id="generate-some-data" class="section level2">
<h2>Generate some data</h2>
<pre class="r"><code>df <- data.frame(time=c("breakfeast", "Lunch", "Dinner"),
                bill=c(10, 30, 15))
head(df)</code></pre>
<pre><code>##         time bill
## 1 breakfeast   10
## 2      Lunch   30
## 3     Dinner   15</code></pre>
</div>
<div id="create-line-plots-and-change-line-types" class="section level2">
<h2>Create line plots and change line types</h2>
<p>The argument <strong>linetype</strong> is used to change the line type :</p>
<pre class="r"><code>library(ggplot2)
# Basic line plot with points
ggplot(data=df, aes(x=time, y=bill, group=1)) +
  geom_line()+
  geom_point()
# Change the line type
ggplot(data=df, aes(x=time, y=bill, group=1)) +
  geom_line(linetype = "dashed")+
  geom_point()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-example-1.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-example-2.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /></p>
</div>
</div>
<div id="line-plot-with-multiple-groups" class="section level1">
<h1>Line plot with multiple groups</h1>
<div id="create-some-data" class="section level2">
<h2>Create some data</h2>
<pre class="r"><code>df2 <- data.frame(sex = rep(c("Female", "Male"), each=3),
                  time=c("breakfeast", "Lunch", "Dinner"),
                  bill=c(10, 30, 15, 13, 40, 17) )
head(df2)</code></pre>
<pre><code>##      sex       time bill
## 1 Female breakfeast   10
## 2 Female      Lunch   30
## 3 Female     Dinner   15
## 4   Male breakfeast   13
## 5   Male      Lunch   40
## 6   Male     Dinner   17</code></pre>
</div>
<div id="change-globally-the-appearance-of-lines" class="section level2">
<h2>Change globally the appearance of lines</h2>
<p>In the graphs below, line types, colors and sizes are the same for the two groups :</p>
<pre class="r"><code>library(ggplot2)
# Line plot with multiple groups
ggplot(data=df2, aes(x=time, y=bill, group=sex)) +
  geom_line()+
  geom_point()
# Change line types
ggplot(data=df2, aes(x=time, y=bill, group=sex)) +
  geom_line(linetype="dashed")+
  geom_point()
# Change line colors and sizes
ggplot(data=df2, aes(x=time, y=bill, group=sex)) +
  geom_line(linetype="dotted", color="red", size=2)+
  geom_point(color="blue", size=3)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-multiple-groups-1.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-multiple-groups-2.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-multiple-groups-3.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /></p>
</div>
<div id="change-automatically-the-line-types-by-groups" class="section level2">
<h2>Change automatically the line types by groups</h2>
<p>In the graphs below, line types, colors and sizes are changed automatically by the levels of the variable <em>sex</em> :</p>
<pre class="r"><code># Change line types by groups (sex)
ggplot(df2, aes(x=time, y=bill, group=sex)) +
  geom_line(aes(linetype=sex))+
  geom_point()+
  theme(legend.position="top")
# Change line types + colors
ggplot(df2, aes(x=time, y=bill, group=sex)) +
  geom_line(aes(linetype=sex, color=sex))+
  geom_point(aes(color=sex))+
  theme(legend.position="top")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-multiple-groups-change-line-type-1.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-multiple-groups-change-line-type-2.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /></p>
</div>
<div id="change-manually-the-appearance-of-lines" class="section level2">
<h2>Change manually the appearance of lines</h2>
<p>The functions below can be used :</p>
<ul>
<li>scale_linetype_manual() : to change line types</li>
<li>scale_color_manual() : to change line colors</li>
<li>scale_size_manual() : to change the size of lines</li>
</ul>
<pre class="r"><code># Set line types manually
ggplot(df2, aes(x=time, y=bill, group=sex)) +
  geom_line(aes(linetype=sex))+
  geom_point()+
  scale_linetype_manual(values=c("twodash", "dotted"))+
  theme(legend.position="top")
# Change line colors and sizes
ggplot(df2, aes(x=time, y=bill, group=sex)) +
  geom_line(aes(linetype=sex, color=sex, size=sex))+
  geom_point()+
  scale_linetype_manual(values=c("twodash", "dotted"))+
  scale_color_manual(values=c('#999999','#E69F00'))+
  scale_size_manual(values=c(1, 1.5))+
  theme(legend.position="top")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-multiple-groups-manual-scale-1.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-line-type-multiple-groups-manual-scale-2.png" title="ggplot2 line type, R software" alt="ggplot2 line type, R software" width="240" /></p>
</div>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>ggplot2</strong> (ver. 1.0.0) </span></p>
</div>
<script>jQuery(document).ready(function () {
  jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:45:20 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[ggplot2 axis scales and transformations]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-axis-scales-and-transformations</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-axis-scales-and-transformations</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#prepare-the-data">Prepare the data</a></li>
<li><a href="#example-of-plots">Example of plots</a></li>
<li><a href="#change-x-and-y-axis-limits">Change x and y axis limits</a><ul>
<li><a href="#use-xlim-and-ylim-functions">Use xlim() and ylim() functions</a></li>
<li><a href="#use-expand_limts-function">Use expand_limts() function</a></li>
<li><a href="#use-scale_xx-functions">Use scale_xx() functions</a></li>
</ul></li>
<li><a href="#axis-transformations">Axis transformations</a><ul>
<li><a href="#log-and-sqrt-transformations">Log and sqrt transformations</a></li>
<li><a href="#format-axis-tick-mark-labels">Format axis tick mark labels</a></li>
<li><a href="#display-log-tick-marks">Display log tick marks</a></li>
</ul></li>
<li><a href="#format-date-axes">Format date axes</a><ul>
<li><a href="#example-of-data">Example of data</a></li>
<li><a href="#create-some-time-serie-data">Create some time serie data</a></li>
<li><a href="#plot-with-dates">Plot with dates</a></li>
<li><a href="#format-axis-tick-mark-labels-1">Format axis tick mark labels</a></li>
<li><a href="#date-axis-limits">Date axis limits</a></li>
</ul></li>
<li><a href="#go-further">Go further</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>This <strong>R tutorial</strong> describes how to modify <strong>x and y axis limits</strong> (minimum and maximum values) using <strong>ggplot2</strong> package. <strong>Axis transformations</strong> (<strong>log scale</strong>, sqrt, …) and date axis are also covered in this article.</p>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="prepare-the-data" class="section level1">
<h1>Prepare the data</h1>
<p>ToothGrowth data is used in the following examples :</p>
<pre class="r"><code># Convert dose column dose from a numeric to a factor variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth)</code></pre>
<pre><code>##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5</code></pre>
<p><span class="warning">Make sure that <em>dose</em> column is converted as a factor using the above R script.</span></p>
</div>
<div id="example-of-plots" class="section level1">
<h1>Example of plots</h1>
<pre class="r"><code>library(ggplot2)
# Box plot 
bp <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
bp
# scatter plot
sp<-ggplot(cars, aes(x = speed, y = dist)) + geom_point()
sp</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-example-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-example-2.png" width="240" /></p>
</div>
<div id="change-x-and-y-axis-limits" class="section level1">
<h1>Change x and y axis limits</h1>
<p>There are different functions to set axis limits :</p>
<ul>
<li>xlim() and ylim()</li>
<li>expand_limits()</li>
<li>scale_x_continuous() and scale_y_continuous()</li>
</ul>
<div id="use-xlim-and-ylim-functions" class="section level2">
<h2>Use xlim() and ylim() functions</h2>
<p>To change the range of a continuous axis, the functions <strong>xlim()</strong> and <strong>ylim()</strong> can be used as follow :</p>
<pre class="r"><code># x axis limits
sp + xlim(min, max)
# y axis limits
sp + ylim(min, max)</code></pre>
<p><span class="success">min and max are the minimum and the maximum values of each axis.</span></p>
<pre class="r"><code># Box plot : change y axis range
bp + ylim(0,50)
# scatter plots : change x and y limits
sp + xlim(5, 40)+ylim(0, 150)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-axis-limits-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-axis-limits-2.png" width="192" /></p>
</div>
<div id="use-expand_limts-function" class="section level2">
<h2>Use expand_limts() function</h2>
<div class="warning">
<p>Note that, the function <strong>expand_limits()</strong> can be used to :</p>
<ul>
<li>quickly set the intercept of x and y axes at (0,0)</li>
<li>change the limits of x and y axes</li>
</ul>
</div>
<pre class="r"><code># set the intercept of x and y axis at (0,0)
sp + expand_limits(x=0, y=0)
# change the axis limits
sp + expand_limits(x=c(0,30), y=c(0, 150))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-expand-limits-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-expand-limits-2.png" width="192" /></p>
</div>
<div id="use-scale_xx-functions" class="section level2">
<h2>Use scale_xx() functions</h2>
<p>It is also possible to use the functions <strong>scale_x_continuous()</strong> and <strong>scale_y_continuous()</strong> to change x and y axis limits, respectively.</p>
<p>The simplified formats of the functions are :</p>
<pre class="r"><code>scale_x_continuous(name, breaks, labels, limits, trans)
scale_y_continuous(name, breaks, labels, limits, trans)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>name</strong> : x or y axis labels</li>
<li><strong>breaks</strong> : to control the breaks in the guide (axis ticks, grid lines, …). Among the possible values, there are :
<ul>
<li><em>NULL</em> : hide all breaks</li>
<li><strong>waiver()</strong> : the default break computation</li>
<li>a <strong>character</strong> or <strong>numeric</strong> vector specifying the breaks to display</li>
</ul></li>
<li><strong>labels</strong> : labels of axis tick marks. Allowed values are :
<ul>
<li><strong>NULL</strong> for no labels</li>
<li><strong>waiver()</strong> for the default labels</li>
<li><strong>character vector</strong> to be used for break labels</li>
</ul></li>
<li><strong>limits</strong> : a numeric vector specifying x or y axis limits (min, max)</li>
<li><strong>trans</strong> for axis transformations. Possible values are “log2”, “log10”, …</li>
</ul>
</div>
<p><br/></p>
<p>The functions <em>scale_x_continuous()</em> and <em>scale_y_continuous()</em> can be used as follow :</p>
<pre class="r"><code># Change x and y axis labels, and limits
sp + scale_x_continuous(name="Speed of cars", limits=c(0, 30)) +
  scale_y_continuous(name="Stopping distance", limits=c(0, 150))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-scale-continuous-1.png" width="192" /></p>
</div>
</div>
<div id="axis-transformations" class="section level1">
<h1>Axis transformations</h1>
<div id="log-and-sqrt-transformations" class="section level2">
<h2>Log and sqrt transformations</h2>
<p>Built in functions for axis transformations are :</p>
<ul>
<li>scale_x_log10(), scale_y_log10() : for log10 transformation</li>
<li>scale_x_sqrt(), scale_y_sqrt() : for sqrt transformation</li>
<li>scale_x_reverse(), scale_y_reverse() : to reverse coordinates</li>
<li>coord_trans(x =“log10”, y=“log10”) : possible values for x and y are “log2”, “log10”, “sqrt”, …</li>
<li>scale_x_continuous(trans=‘log2’), scale_y_continuous(trans=‘log2’) : another allowed value for the argument <em>trans</em> is ‘log10’</li>
</ul>
<p>These functions can be used as follow :</p>
<pre class="r"><code># Default scatter plot
sp <- ggplot(cars, aes(x = speed, y = dist)) + geom_point()
sp
# Log transformation using scale_xx()
# possible values for trans : 'log2', 'log10','sqrt'
sp + scale_x_continuous(trans='log2') +
  scale_y_continuous(trans='log2')
# Sqrt transformation
sp + scale_y_sqrt()
# Reverse coordinates
sp + scale_y_reverse() </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-axis-transformations-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-axis-transformations-2.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-axis-transformations-3.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-axis-transformations-4.png" width="192" /></p>
<p><span class="warning">The function <strong>coord_trans()</strong> can be used also for the axis transformation</span></p>
<pre class="r"><code># Possible values for x and y : "log2", "log10", "sqrt", ...
sp + coord_trans(x="log2", y="log2")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-coord-trans-1.png" width="192" /></p>
</div>
<div id="format-axis-tick-mark-labels" class="section level2">
<h2>Format axis tick mark labels</h2>
<p><span class="success">Axis tick marks can be set to show exponents. The <strong>scales</strong> package is required to access break formatting functions.</span></p>
<pre class="r"><code># Log2 scaling of the y axis (with visually-equal spacing)
library(scales)
sp + scale_y_continuous(trans = log2_trans())
# show exponents
sp + scale_y_continuous(trans = log2_trans(),
    breaks = trans_breaks("log2", function(x) 2^x),
    labels = trans_format("log2", math_format(2^.x)))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-log-scale-show-exponents-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-log-scale-show-exponents-2.png" width="192" /></p>
<p><span class="success">Note that many transformation functions are available using the <strong>scales</strong> package : log10_trans(), sqrt_trans(), etc. Use help(trans_new) for a full list.</span></p>
<p><strong>Format axis tick mark labels</strong> :</p>
<pre class="r"><code>library(scales)
# Percent
sp + scale_y_continuous(labels = percent)
# dollar
sp + scale_y_continuous(labels = dollar)
# scientific
sp + scale_y_continuous(labels = scientific)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-format-axis-tick-mark-labels-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-format-axis-tick-mark-labels-2.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-format-axis-tick-mark-labels-3.png" width="192" /></p>
</div>
<div id="display-log-tick-marks" class="section level2">
<h2>Display log tick marks</h2>
<p>It is possible to add log tick marks using the function <strong>annotation_logticks()</strong>.</p>
<p><span class="success">Note that, these tick marks make sense only for base 10</span></p>
<p>The <em>Animals</em> data sets, from the package <em>MASS</em>, are used :</p>
<pre class="r"><code>library(MASS)
head(Animals)</code></pre>
<pre><code>##                     body brain
## Mountain beaver     1.35   8.1
## Cow               465.00 423.0
## Grey wolf          36.33 119.5
## Goat               27.66 115.0
## Guinea pig          1.04   5.5
## Dipliodocus     11700.00  50.0</code></pre>
<p>The function <strong>annotation_logticks()</strong> can be used as follow :</p>
<pre class="r"><code>library(MASS) # to access Animals data sets
library(scales) # to access break formatting functions
# x and y axis are transformed and formatted
p2 <- ggplot(Animals, aes(x = body, y = brain)) + geom_point() +
     scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
              labels = trans_format("log10", math_format(10^.x))) +
     scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
              labels = trans_format("log10", math_format(10^.x))) +
     theme_bw()
# log-log plot without log tick marks
p2
# Show log tick marks
p2 + annotation_logticks()  </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-annotation-logticks-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-annotation-logticks-2.png" width="259.2" /></p>
<p><span class="warning">Note that, default log ticks are on bottom and left.</span></p>
<p>To specify the sides of the log ticks :</p>
<pre class="r"><code># Log ticks on left and right
p2 + annotation_logticks(sides="lr")
# All sides
p2+annotation_logticks(sides="trbl")</code></pre>
<p>Allowed values for the argument <em>sides</em> are :</p>
<ul>
<li>t : for top</li>
<li>r : for right</li>
<li>b : for bottom</li>
<li>l : for left</li>
<li>the combination of t, r, b and l</li>
</ul>
</div>
</div>
<div id="format-date-axes" class="section level1">
<h1>Format date axes</h1>
<p>The functions <strong>scale_x_date()</strong> and <strong>scale_y_date()</strong> are used.</p>
<div id="example-of-data" class="section level2">
<h2>Example of data</h2>
</div>
<div id="create-some-time-serie-data" class="section level2">
<h2>Create some time serie data</h2>
<pre class="r"><code>df <- data.frame(
  date = seq(Sys.Date(), len=100, by="1 day")[sample(100, 50)],
  price = runif(50)
)
df <- df[order(df$date), ]
head(df)</code></pre>
<pre><code>##          date      price
## 33 2016-09-21 0.07245190
## 3  2016-09-23 0.51772443
## 23 2016-09-25 0.05758921
## 43 2016-09-26 0.99389551
## 45 2016-09-27 0.94858770
## 29 2016-09-28 0.82420890</code></pre>
</div>
<div id="plot-with-dates" class="section level2">
<h2>Plot with dates</h2>
<pre class="r"><code># Plot with date
dp <- ggplot(data=df, aes(x=date, y=price)) + geom_line()
dp</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-date-axis-1.png" width="259.2" /></p>
</div>
<div id="format-axis-tick-mark-labels-1" class="section level2">
<h2>Format axis tick mark labels</h2>
<p>Load the package <em>scales</em> to access break formatting functions.</p>
<pre class="r"><code>library(scales)
# Format : month/day
dp + scale_x_date(labels = date_format("%m/%d")) +
  theme(axis.text.x = element_text(angle=45))
# Format : Week
dp + scale_x_date(labels = date_format("%W"))
# Months only
dp + scale_x_date(breaks = date_breaks("months"),
  labels = date_format("%b"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-date-axis-format-ticks-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-date-axis-format-ticks-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-date-axis-format-ticks-3.png" width="259.2" /></p>
<p><span class="warning">Note that, since ggplot2 v2.0.0, date and datetime scales now have date_breaks, date_minor_breaks and date_labels arguments so that you never need to use the long scales::date_breaks() or scales::date_format().</span></p>
</div>
<div id="date-axis-limits" class="section level2">
<h2>Date axis limits</h2>
<p>US economic time series data sets (from ggplot2 package) are used :</p>
<pre class="r"><code>head(economics)</code></pre>
<pre><code>##         date   pce    pop psavert uempmed unemploy
## 1 1967-07-01 507.4 198712    12.5     4.5     2944
## 2 1967-08-01 510.5 198911    12.5     4.7     2945
## 3 1967-09-01 516.3 199113    11.7     4.6     2958
## 4 1967-10-01 512.9 199311    12.5     4.9     3143
## 5 1967-11-01 518.1 199498    12.5     4.7     3066
## 6 1967-12-01 525.8 199657    12.1     4.8     3018</code></pre>
<p>Create the plot of psavert by date :</p>
<ul>
<li>date : Month of data collection</li>
<li>psavert : personal savings rate</li>
</ul>
<pre class="r"><code># Plot with dates
dp <- ggplot(data=economics, aes(x=date, y=psavert)) + geom_line()
dp
# Axis limits c(min, max)
min <- as.Date("2002-1-1")
max <- max(economics$date)
dp+ scale_x_date(limits = c(min, max))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-date-axis-limits-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-axis-scale-date-axis-limits-2.png" width="259.2" /></p>
</div>
</div>
<div id="go-further" class="section level1">
<h1>Go further</h1>
<p>See also the function <strong>scale_x_datetime()</strong> and <strong>scale_y_datetime()</strong> to plot a data containing date and time.</p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4) and <strong>ggplot2</strong> (ver. ) </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:44:38 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[ggplot2 scatter plots : Quick start guide - R software and data visualization]]></title>
			<link>https://www.sthda.com/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization</link>
			<guid>https://www.sthda.com/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">
<div id="TOC">
<ul>
<li><a href="#prepare-the-data">Prepare the data</a></li>
<li><a href="#basic-scatter-plots">Basic scatter plots</a></li>
<li><a href="#label-points-in-the-scatter-plot">Label points in the scatter plot</a><ul>
<li><a href="#add-regression-lines">Add regression lines</a></li>
<li><a href="#change-the-appearance-of-points-and-lines">Change the appearance of points and lines</a></li>
</ul></li>
<li><a href="#scatter-plots-with-multiple-groups">Scatter plots with multiple groups</a><ul>
<li><a href="#change-the-point-colorshapesize-automatically">Change the point color/shape/size automatically</a></li>
<li><a href="#add-regression-lines-1">Add regression lines</a></li>
<li><a href="#change-the-point-colorshapesize-manually">Change the point color/shape/size manually</a></li>
</ul></li>
<li><a href="#add-marginal-rugs-to-a-scatter-plot">Add marginal rugs to a scatter plot</a></li>
<li><a href="#scatter-plots-with-the-2d-density-estimation">Scatter plots with the 2d density estimation</a></li>
<li><a href="#scatter-plots-with-ellipses">Scatter plots with ellipses</a></li>
<li><a href="#scatter-plots-with-rectangular-bins">Scatter plots with rectangular bins</a></li>
<li><a href="#scatter-plot-with-marginal-density-distribution-plot">Scatter plot with marginal density distribution plot</a></li>
<li><a href="#customized-scatter-plots">Customized scatter plots</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>
<p><br/></p>
<p>This article describes how create a <strong>scatter plot</strong> using <strong>R software</strong> and <strong>ggplot2</strong> package. The function <strong>geom_point()</strong> is used.</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-logo-data-visualization-1.png" width="384" /></p>

<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>Related Book:</p>
        <a href = "https://www.datanovia.com/en/udft" target="_blank">
          <img src = "https://www.datanovia.com/en/wp-content/uploads/dn-tutorials/affiliate-marketing/images/ggplot2-book.png" /><br/>
     GGPlot2 Essentials for Great Data Visualization in R
      </a>
</div>
<div class="spacer"></div>

<div id="prepare-the-data" class="section level1">
<h1>Prepare the data</h1>
<p><em>mtcars</em> data sets are used in the examples below.</p>
<pre class="r"><code># Convert cyl column from a numeric to a factor variable
mtcars$cyl <- as.factor(mtcars$cyl)
head(mtcars)</code></pre>
<pre><code>##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1</code></pre>
</div>
<div id="basic-scatter-plots" class="section level1">
<h1>Basic scatter plots</h1>
<p>Simple scatter plots are created using the R code below. The color, the size and the shape of points can be changed using the function <strong>geom_point()</strong> as follow :</p>
<pre class="r"><code>geom_point(size, color, shape)</code></pre>
<pre class="r"><code>library(ggplot2)
# Basic scatter plot
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
# Change the point size, and shape
ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point(size=2, shape=23)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-basic-graph-data-visualization-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-basic-graph-data-visualization-2.png" width="259.2" /></p>
<p><span class="warning">Note that, the size of the points can be controlled by the values of a continuous variable as in the example below.</span></p>
<pre class="r"><code># Change the point size
ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_point(aes(size=qsec))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-control-size-continuous-variable-data-visualization-1.png" width="288" /></p>
<p>Read more on point shapes : <a href="https://www.sthda.com/english/english/wiki/ggplot2-point-shapes">ggplot2 point shapes</a></p>
</div>
<div id="label-points-in-the-scatter-plot" class="section level1">
<h1>Label points in the scatter plot</h1>
<p>The function <strong>geom_text()</strong> can be used :</p>
<pre class="r"><code>ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point() + 
  geom_text(label=rownames(mtcars))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-add-text-labels-data-visualization-1.png" width="336" /></p>
<p>Read more on text annotations : <a href="https://www.sthda.com/english/english/wiki/ggplot2-texts-add-text-annotations-to-a-graph-in-r-software">ggplot2 - add texts to a plot</a></p>
<div id="add-regression-lines" class="section level2">
<h2>Add regression lines</h2>
<p>The functions below can be used to add regression lines to a scatter plot :</p>
<ul>
<li><strong>geom_smooth()</strong> and <strong>stat_smooth()</strong></li>
<li><strong>geom_abline()</strong></li>
</ul>
<p><em>geom_abline()</em> has been already described at this link : <a href="https://www.sthda.com/english/english/wiki/ggplot2-add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines">ggplot2 add straight lines to a plot</a>.</p>
<p>Only the function <strong>geom_smooth()</strong> is covered in this section.</p>
<p>A simplified format is :</p>
<pre class="r"><code>geom_smooth(method="auto", se=TRUE, fullrange=FALSE, level=0.95)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>method</strong> : smoothing method to be used. Possible values are lm, glm, gam, loess, rlm.
<ul>
<li><strong>method = “loess”</strong>: This is the default value for small number of observations. It computes a smooth local regression. You can read more about <strong>loess</strong> using the R code <strong>?loess</strong>.</li>
<li><strong>method =“lm”</strong>: It fits a <strong>linear model</strong>. Note that, it’s also possible to indicate the formula as <strong>formula = y ~ poly(x, 3)</strong> to specify a degree 3 polynomial.</li>
</ul></li>
<li><strong>se</strong> : logical value. If TRUE, confidence interval is displayed around smooth.</li>
<li><strong>fullrange</strong> : logical value. If TRUE, the fit spans the full range of the plot</li>
<li><strong>level</strong> : level of confidence interval to use. Default value is 0.95</li>
</ul>
</div>
<p><br/></p>
<pre class="r"><code># Add the regression line
ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_point()+
  geom_smooth(method=lm)
# Remove the confidence interval
ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_point()+
  geom_smooth(method=lm, se=FALSE)
# Loess method
ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_point()+
  geom_smooth()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-regression-lines-data-visualization-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-regression-lines-data-visualization-2.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-regression-lines-data-visualization-3.png" width="192" /></p>
</div>
<div id="change-the-appearance-of-points-and-lines" class="section level2">
<h2>Change the appearance of points and lines</h2>
<p>This section describes how to change :</p>
<ul>
<li>the color and the shape of points</li>
<li>the line type and color of the regression line</li>
<li>the fill color of the confidence interval</li>
</ul>
<pre class="r"><code># Change the point colors and shapes
# Change the line type and color
ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_point(shape=18, color="blue")+
  geom_smooth(method=lm, se=FALSE, linetype="dashed",
             color="darkred")
# Change the confidence interval fill color
ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_point(shape=18, color="blue")+
  geom_smooth(method=lm,  linetype="dashed",
             color="darkred", fill="blue")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-point-shape-line-type-regression-line-data-visualization-1.png" width="192" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-point-shape-line-type-regression-line-data-visualization-2.png" width="192" /></p>
<p><span class="warning">Note that a transparent color is used, by default, for the confidence band. This can be changed by using the argument <em>alpha</em> : <em>geom_smooth(fill=“blue”, alpha=1)</em></span></p>
<p>Read more on point shapes : <a href="https://www.sthda.com/english/english/wiki/ggplot2-point-shapes">ggplot2 point shapes</a></p>
<p>Read more on line types : <a href="https://www.sthda.com/english/english/wiki/ggplot2-line-types-how-to-change-line-types-of-a-graph-in-r-software">ggplot2 line types</a></p>
</div>
</div>
<div id="scatter-plots-with-multiple-groups" class="section level1">
<h1>Scatter plots with multiple groups</h1>
<p>This section describes how to change point colors and shapes automatically and manually.</p>
<div id="change-the-point-colorshapesize-automatically" class="section level2">
<h2>Change the point color/shape/size automatically</h2>
<p>In the R code below, point shapes, colors and sizes are controlled by the levels of the factor variable <em>cyl</em> :</p>
<pre class="r"><code># Change point shapes by the levels of cyl
ggplot(mtcars, aes(x=wt, y=mpg, shape=cyl)) +
  geom_point()
# Change point shapes and colors
ggplot(mtcars, aes(x=wt, y=mpg, shape=cyl, color=cyl)) +
  geom_point()
# Change point shapes, colors and sizes
ggplot(mtcars, aes(x=wt, y=mpg, shape=cyl, color=cyl, size=cyl)) +
  geom_point()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-change-shape-size-color-by-group-automatically-data-visualization-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-change-shape-size-color-by-group-automatically-data-visualization-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-change-shape-size-color-by-group-automatically-data-visualization-3.png" width="259.2" /></p>
</div>
<div id="add-regression-lines-1" class="section level2">
<h2>Add regression lines</h2>
<p><strong>Regression lines</strong> can be added as follow :</p>
<pre class="r"><code># Add regression lines
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl)) +
  geom_point() + 
  geom_smooth(method=lm)
# Remove confidence intervals
# Extend the regression lines
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl)) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-groups-regression-lines-data-visualization-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-groups-regression-lines-data-visualization-2.png" width="259.2" /></p>
<p><span class="warning">Note that, you can also change the line type of the regression lines by using the aesthetic <em>linetype = cyl</em>. </span></p>
<p>The fill color of confidence bands can be changed as follow :</p>
<pre class="r"><code>ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl)) +
  geom_point() + 
  geom_smooth(method=lm, aes(fill=cyl))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-groups-regression-lines-confidence-band-fill-color-1.png" width="336" /></p>
</div>
<div id="change-the-point-colorshapesize-manually" class="section level2">
<h2>Change the point color/shape/size manually</h2>
<p>The functions below are used :</p>
<ul>
<li><em>scale_shape_manual()</em> for point shapes</li>
<li><em>scale_color_manual()</em> for point colors</li>
<li><em>scale_size_manual()</em> for point sizes</li>
</ul>
<pre class="r"><code># Change point shapes and colors manually
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl)) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+
  scale_shape_manual(values=c(3, 16, 17))+ 
  scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
  theme(legend.position="top")
  
# Change the point sizes manually
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl))+
  geom_point(aes(size=cyl)) + 
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+
  scale_shape_manual(values=c(3, 16, 17))+ 
  scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
  scale_size_manual(values=c(2,3,4))+
  theme(legend.position="top")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-change-shape-size-color-by-group-manually-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-change-shape-size-color-by-group-manually-2.png" width="240" /></p>
<p>It is also possible to <em>change manually point and line colors</em> using the functions :</p>
<ul>
<li><em>scale_color_brewer()</em> : to use color palettes from <em>RColorBrewer</em> package</li>
<li><em>scale_color_grey()</em> : to use grey color palettes</li>
</ul>
<pre class="r"><code>p <- ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl)) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+
  theme_classic()
# Use brewer color palettes
p+scale_color_brewer(palette="Dark2")
# Use grey scale
p + scale_color_grey()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-manual-color-data-visualization-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-manual-color-data-visualization-2.png" width="259.2" /></p>
<p>Read more on ggplot2 colors here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually">ggplot2 colors</a></p>
</div>
</div>
<div id="add-marginal-rugs-to-a-scatter-plot" class="section level1">
<h1>Add marginal rugs to a scatter plot</h1>
<p>The function <strong>geom_rug()</strong> can be used :</p>
<pre class="r"><code>geom_rug(sides ="bl")</code></pre>
<p><strong>sides</strong> : a string that controls which sides of the plot the rugs appear on. Allowed value is a string containing any of “trbl”, for top, right, bottom, and left.</p>
<pre class="r"><code># Add marginal rugs
ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point() + geom_rug()
# Change colors
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl)) +
  geom_point() + geom_rug()
# Add marginal rugs using faithful data
ggplot(faithful, aes(x=eruptions, y=waiting)) +
  geom_point() + geom_rug()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-add-rugs-data-visualization-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-add-rugs-data-visualization-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-add-rugs-data-visualization-3.png" width="259.2" /></p>
</div>
<div id="scatter-plots-with-the-2d-density-estimation" class="section level1">
<h1>Scatter plots with the 2d density estimation</h1>
<p>The functions <strong>geom_density_2d()</strong> or <strong>stat_density_2d()</strong> can be used :</p>
<pre class="r"><code># Scatter plot with the 2d density estimation
sp <- ggplot(faithful, aes(x=eruptions, y=waiting)) +
  geom_point()
sp + geom_density_2d()
# Gradient color
sp + stat_density_2d(aes(fill = ..level..), geom="polygon")
# Change the gradient color
sp + stat_density_2d(aes(fill = ..level..), geom="polygon")+
  scale_fill_gradient(low="blue", high="red")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-geom-density-2d-data-visualization-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-geom-density-2d-data-visualization-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-geom-density-2d-data-visualization-3.png" width="259.2" /></p>
<p>Read more on ggplot2 colors here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually">ggplot2 colors</a></p>
</div>
<div id="scatter-plots-with-ellipses" class="section level1">
<h1>Scatter plots with ellipses</h1>
<p>The function <strong>stat_ellipse()</strong> can be used as follow:</p>
<pre class="r"><code># One ellipse arround all points
ggplot(faithful, aes(waiting, eruptions))+
  geom_point()+
  stat_ellipse()
# Ellipse by groups
p <- ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3))+
  geom_point()
p + stat_ellipse()
# Change the type of ellipses: possible values are "t", "norm", "euclid"
p + stat_ellipse(type = "norm")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-ellipse-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-ellipse-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-ellipse-3.png" width="259.2" /></p>
</div>
<div id="scatter-plots-with-rectangular-bins" class="section level1">
<h1>Scatter plots with rectangular bins</h1>
<p>The number of observations is counted in each bins and displayed using any of the functions below :</p>
<ul>
<li><strong>geom_bin2d()</strong> for adding a heatmap of 2d bin counts</li>
<li><strong>stat_bin_2d()</strong> for counting the number of observation in rectangular bins</li>
<li><strong>stat_summary_2d()</strong> to apply function for 2D rectangular bins</li>
</ul>
<p>The simplified formats of these functions are :</p>
<pre class="r"><code>plot + geom_bin2d(...)
plot+stat_bin_2d(geom=NULL, bins=30)
plot + stat_summary_2d(geom = NULL, bins = 30, fun = mean)</code></pre>
<ul>
<li><strong>geom</strong> : geometrical object to display the data</li>
<li><strong>bins</strong> : Number of bins in both vertical and horizontal directions. The default value is 30</li>
<li><strong>fun</strong> : function for summary</li>
</ul>
<p>The data sets <em>diamonds</em> from ggplot2 package is used :</p>
<pre class="r"><code>head(diamonds)</code></pre>
<pre><code>##   carat       cut color clarity depth table price    x    y    z
## 1  0.23     Ideal     E     SI2  61.5    55   326 3.95 3.98 2.43
## 2  0.21   Premium     E     SI1  59.8    61   326 3.89 3.84 2.31
## 3  0.23      Good     E     VS1  56.9    65   327 4.05 4.07 2.31
## 4  0.29   Premium     I     VS2  62.4    58   334 4.20 4.23 2.63
## 5  0.31      Good     J     SI2  63.3    58   335 4.34 4.35 2.75
## 6  0.24 Very Good     J    VVS2  62.8    57   336 3.94 3.96 2.48</code></pre>
<pre class="r"><code># Plot
p <- ggplot(diamonds, aes(carat, price))
p + geom_bin2d()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-bin2d-rectangular-bins-data-visualization-1.png" width="384" /></p>
<p>Change the number of bins :</p>
<pre class="r"><code># Change the number of bins
p + geom_bin2d(bins=10)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-bin2d-rectangular-bins_2-data-visualization-1.png" width="384" /></p>
<p>Or specify the width of bins :</p>
<pre class="r"><code># Or specify the width of bins
p + geom_bin2d(binwidth=c(1, 1000))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-bin2d-rectangular-bins_3-data-visualization-1.png" width="384" /></p>
</div>
<div id="scatter-plot-with-marginal-density-distribution-plot" class="section level1">
<h1>Scatter plot with marginal density distribution plot</h1>
<p><strong>Step 1/3. Create some data :</strong></p>
<pre class="r"><code>set.seed(1234)
x <- c(rnorm(500, mean = -1), rnorm(500, mean = 1.5))
y <- c(rnorm(500, mean = 1), rnorm(500, mean = 1.7))
group <- as.factor(rep(c(1,2), each=500))
df <- data.frame(x, y, group)
head(df)</code></pre>
<pre><code>##             x          y group
## 1 -2.20706575 -0.2053334     1
## 2 -0.72257076  1.3014667     1
## 3  0.08444118 -0.5391452     1
## 4 -3.34569770  1.6353707     1
## 5 -0.57087531  1.7029518     1
## 6 -0.49394411 -0.9058829     1</code></pre>
<p><strong>Step 2/3. Create the plots : </strong></p>
<pre class="r"><code># scatter plot of x and y variables
# color by groups
scatterPlot <- ggplot(df,aes(x, y, color=group)) + 
  geom_point() + 
  scale_color_manual(values = c('#999999','#E69F00')) + 
  theme(legend.position=c(0,1), legend.justification=c(0,1))
scatterPlot
# Marginal density plot of x (top panel)
xdensity <- ggplot(df, aes(x, fill=group)) + 
  geom_density(alpha=.5) + 
  scale_fill_manual(values = c('#999999','#E69F00')) + 
  theme(legend.position = "none")
xdensity
# Marginal density plot of y (right panel)
ydensity <- ggplot(df, aes(y, fill=group)) + 
  geom_density(alpha=.5) + 
  scale_fill_manual(values = c('#999999','#E69F00')) + 
  theme(legend.position = "none")
ydensity</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-with-marginal-density-distribution-data-visualization-1.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-with-marginal-density-distribution-data-visualization-2.png" width="240" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-with-marginal-density-distribution-data-visualization-3.png" width="240" /></p>
<p>Create a blank placeholder plot :</p>
<pre class="r"><code>blankPlot <- ggplot()+geom_blank(aes(1,1))+
  theme(plot.background = element_blank(), 
   panel.grid.major = element_blank(),
   panel.grid.minor = element_blank(), 
   panel.border = element_blank(),
   panel.background = element_blank(),
   axis.title.x = element_blank(),
   axis.title.y = element_blank(),
   axis.text.x = element_blank(), 
   axis.text.y = element_blank(),
   axis.ticks = element_blank()
     )</code></pre>
<p><strong>Step 3/3. Put the plots together:</strong></p>
<p>To put multiple plots on the same page, the package <strong>gridExtra</strong> can be used. Install the package as follow :</p>
<pre class="r"><code>install.packages("gridExtra")</code></pre>
<p>Arrange ggplot2 with adapted height and width for each row and column :</p>
<pre class="r"><code>library("gridExtra")
grid.arrange(xdensity, blankPlot, scatterPlot, ydensity, 
        ncol=2, nrow=2, widths=c(4, 1.4), heights=c(1.4, 4))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-put-multiple-plot-together-data-visualization-1.png" width="480" /></p>
<p>Read more on how to arrange multiple ggplots in one page : <a href="https://www.sthda.com/english/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page-r-software-and-data-visualization">ggplot2 - Easy way to mix multiple graphs on the same page</a></p>
</div>
<div id="customized-scatter-plots" class="section level1">
<h1>Customized scatter plots</h1>
<pre class="r"><code># Basic scatter plot
ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_point()+
  geom_smooth(method=lm, color="black")+
  labs(title="Miles per gallon \n according to the weight",
       x="Weight (lb/1000)", y = "Miles/(US) gallon")+
  theme_classic()  
# Change color/shape by groups
# Remove confidence bands
p <- ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl)) + 
  geom_point()+
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+
  labs(title="Miles per gallon \n according to the weight",
       x="Weight (lb/1000)", y = "Miles/(US) gallon")
p + theme_classic()  </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-customized-scatter-plot-data-visualization-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-customized-scatter-plot-data-visualization-2.png" width="259.2" /></p>
<p>Change colors manually :</p>
<pre class="r"><code># Continuous colors
p + scale_color_brewer(palette="Paired") + theme_classic()
# Discrete colors
p + scale_color_brewer(palette="Dark2") + theme_minimal()
# Gradient colors
p + scale_color_brewer(palette="Accent") + theme_minimal()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-customized-change-color-data-visualization-1.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-customized-change-color-data-visualization-2.png" width="259.2" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/ggplot2/ggplot2-scatter-plot-customized-change-color-data-visualization-3.png" width="259.2" /></p>
<p>Read more on ggplot2 colors here : <a href="https://www.sthda.com/english/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually">ggplot2 colors</a></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.2.4) and <strong>ggplot2</strong> (ver. 2.1.0) </span></p>
</div>
<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Fri, 22 May 2020 00:43:33 +0200</pubDate>
			
		</item>
		
	</channel>
</rss>
