<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>【beginner】タグの記事一覧｜ドクターフント(Dr. Hund)</title>
	<atom:link href="https://brain-storm.space/tag/beginner/feed/" rel="self" type="application/rss+xml" />
	<link>https://brain-storm.space</link>
	<description>脳や研究について発信するブログです。This site is for research and statistics.</description>
	<lastBuildDate>Fri, 24 Mar 2023 13:13:57 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.1</generator>

<image>
	<url>https://brain-storm.space/wp-content/uploads/2021/04/cropped-3d0209af428738b78799159b4ce75ad9-32x32.png</url>
	<title>【beginner】タグの記事一覧｜ドクターフント(Dr. Hund)</title>
	<link>https://brain-storm.space</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>[R for beginners] Creating Error Bars for Bar Graphs and Line Graphs in ggplot2</title>
		<link>https://brain-storm.space/error-bar-en/1291/</link>
		
		<dc:creator><![CDATA[brainblog]]></dc:creator>
		<pubDate>Fri, 24 Mar 2023 13:13:56 +0000</pubDate>
				<category><![CDATA[Statistical Analysis]]></category>
		<category><![CDATA[bar graph]]></category>
		<category><![CDATA[beginner]]></category>
		<category><![CDATA[error bar]]></category>
		<category><![CDATA[ggplot2]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[tidyverse]]></category>
		<guid isPermaLink="false">https://brain-storm.space/?p=1291</guid>

					<description><![CDATA[The #8216;T#8217; symbol on bar graphs and line graphs represents error bars that extend above and below the]]></description>
										<content:encoded><![CDATA[
<p>The &#8216;T&#8217; symbol on bar graphs and line graphs represents error bars that extend above and below the data point, indicating standard error or standard deviation. Adding error bars in R&#8217;s ggplot2 is easy. Here&#8217;s a step-by-step guide:</p>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset1 animation-fade rtoc_open default" data-id="1291" data-theme="jin-child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>Contents</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">Preparing the Data</a></li><li class="rtoc-item"><a href="#rtoc-2">Calculating the Mean, Standard Deviation, and Standard Error of the Data</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-3">Use group_by and summarise_all functions in dplyr to Calculate</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4">Drawing Error Bars in Bar Graphs</a></li><li class="rtoc-item"><a href="#rtoc-5">Drawing Error Bars on a Line Graph</a></li><li class="rtoc-item"><a href="#rtoc-6">Adding Error Bars to Grouped Data</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-7">Adding Error Bars to Grouped Bar Graphs</a></li><li class="rtoc-item"><a href="#rtoc-8">Drawing Error Bars on a Grouped Line Graph</a></li></ul></li></ol></div><h2 id="rtoc-1" >Preparing the Data</h2>



<p>We&#8217;ll be using tidyverse for this. If you have your own data, skip ahead.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
# Set working directory
setwd(&quot;~/Rpractice/&quot;)

# Load tidyverse
library(tidyverse)

# Generate random data
dat &lt;- list(
  X &lt;- rnorm(50, 30, 10),
  Y &lt;- rnorm(50, 50, 5),
  Z &lt;- rnorm(50, 40, 15)
)
df &lt;- data.frame(matrix(unlist(dat), nrow=50))
colnames(df) &lt;- c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;)

# Transform the data from wide to long
df.long &lt;- pivot_longer(df, cols = A:C, 
                        names_to = &quot;Categories&quot;, 
                        values_to = &quot;Values&quot;)
</pre></div>


<p>Now we have data that looks like this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
&gt; head(df.long)
# A tibble: 6 x 2
  Categories Values
  &lt;chr&gt;       &lt;dbl&gt;
1 A            26.8
2 B            53.7
3 C            27.3
4 A            31.0
5 B            58.7
6 C            56.2
&gt; 
</pre></div>


<p>To add error bars to bar graphs and line graphs, you need the mean and standard error (or standard deviation) of the data. We use pivot_longer to transform the data from wide to long format.&#8221;</p>



<h2 id="rtoc-2" >Calculating the Mean, Standard Deviation, and Standard Error of the Data</h2>



<p>To add error bars, we need to calculate the mean, standard deviation, and standard error. If you already have this data, you can skip this section.</p>



<p>Calculating these values is easy with the dplyr package in tidyverse.</p>



<h3 id="rtoc-3" >Use group_by and summarise_all functions in dplyr to Calculate</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
a &lt;- group_by(df.long, Categories) %&gt;% 
  summarise_all(list(mean = ~mean(.), 
                     sd = ~sd(.), 
                     se = ~sd(.)/sqrt(length(.))))

</pre></div>


<p>We can simplify this code further,</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
a &lt;- group_by(df.long, Categories) %&gt;% 
  summarise_all(list(mean = mean, 
                     sd = sd, 
                     se = ~sd/sqrt(length(.))))

</pre></div>


<p>Let&#8217;s take a look at the data for &#8216;a&#8217;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
&gt; a
# A tibble: 3 x 4
  Categories  mean    sd    se
  &lt;chr&gt;      &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
1 A           30.1  9.93 1.40 
2 B           49.2  5.00 0.708
3 C           43.9 15.5  2.20 
</pre></div>


<p>We have generated a distribution that looks like this. Since the data was generated randomly, the values may vary slightly if you follow the same steps.</p>



<h2 id="rtoc-4" >Drawing Error Bars in Bar Graphs</h2>



<p>We will use the calculated data to create a bar graph and specify the error bars using <code><span class="marker">geom_errorbar()</span></code>. First, let&#8217;s specify only <code>ymin</code> and <code>ymax</code> in <code>geom_errorbar()</code> and take a look at the graph.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a, aes(x = Categories, y = mean, fill = Categories))+
  geom_bar(stat = &quot;identity&quot;) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se))

</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar1-1024x614.jpg" alt="" class="wp-image-905" width="512" height="307"/></figure>



<p>The width is too wide. Let&#8217;s adjust it using the <code>width</code> argument. We will narrow both the bar graph and error bars.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a, aes(x = Categories, y = mean, fill = Categories))+
  geom_bar(stat = &quot;identity&quot;, width = 0.6) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                width = .1)

</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar2-1024x614.jpg" alt="" class="wp-image-906" width="512" height="307"/></figure>



<p>It&#8217;s a good to adjust the width according to the size of the output image.</p>



<h2 id="rtoc-5" >Drawing Error Bars on a Line Graph</h2>



<p>The process for adding error bars to a line graph is the same as above. First, draw the line graph and then add <code>geom_errorbar()</code>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a, aes(x = Categories, y = mean)) +
  geom_line(group = 1) +
  geom_point(size = 3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                width = .1)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar3-1024x614.jpg" alt="" class="wp-image-907" width="512" height="307"/></figure>



<h2 id="rtoc-6" >Adding Error Bars to Grouped Data</h2>



<p>Let&#8217;s generate grouped data.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
&lt;pre class=&quot;wp-block-syntaxhighlighter-code&quot;&gt;# Add ID column
data &lt;- df.long %&gt;% 
  tibble::rownames_to_column(var = &quot;ID&quot;)

# Convert ID from character to numeric
data$ID &lt;- as.numeric(data$ID)

# Assign 1 to ID &lt;= 75 and 0 to ID &gt;= 76 to create the &quot;group&quot; column
data &lt;- mutate(data, group = ifelse(ID &lt; 76, 1, 0))

# Calculate Mean, SD, and SE
b &lt;- group_by(data, group, Categories) %&gt;% 
  summarise_at(vars(Values), list(mean = ~mean(.), 
                     sd = ~sd(.), 
                     se = ~sd(.)/sqrt(length(.))))

# Convert group column values from numeric to character
b$group &lt;- as.character(b$group)

# Check the data included in b
&gt; head(b)
# A tibble: 6 x 5
# Groups:   group &lt;img class=&quot;ranking-number&quot; src=&quot;https://brain-storm.space/wp-content/themes/jin/img/rank02.png&quot; /&gt;
  group Categories  mean    sd    se
  &lt;chr&gt; &lt;chr&gt;      &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
1 0     A           31.4 11.1  2.21 
2 0     B           51.0  4.31 0.862
3 0     C           33.9 13.5  2.70 
4 1     A           29.5 10.4  2.08 
5 1     B           49.5  4.02 0.804
6 1     C           36.5 15.8  3.16 
&gt; &lt;/pre&gt;
</pre></div>


<p>Now that we have grouped data, let&#8217;s draw a bar graph with error bars.</p>



<h3 id="rtoc-7" >Adding Error Bars to Grouped Bar Graphs</h3>



<p>By specifying <code>position = "dodge"</code>, you can create a grouped bar chart like this.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(b, aes(x = Categories, y = mean, fill = group))+
  geom_bar(stat = &quot;identity&quot;, width = 0.6, position = &quot;dodge&quot;)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar4-1024x614.jpg" alt="" class="wp-image-909" width="512" height="307"/></figure>



<p>Let&#8217;s add error bars to this plot.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(b, aes(x = Categories, y = mean, fill = group))+
  geom_bar(stat = &quot;identity&quot;, width = 0.6, position = &quot;dodge&quot;)+
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
                    position = &quot;dodge&quot;, width = .1)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar5-1024x614.jpg" alt="" class="wp-image-910" width="512" height="307"/></figure>



<p>It is shifted to the center. You can adjust the position with <span class="marker"><code>position = position_dodge()</code></span>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(b, aes(x = Categories, y = mean, fill = group)) +
  geom_bar(stat = &quot;identity&quot;, width = 0.6, position = &quot;dodge&quot;) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                position = position_dodge(0.6), width = .1)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar6-1024x614.jpg" alt="" class="wp-image-911" width="512" height="307"/></figure>



<p>You&#8217;ve created a nice bar graph!</p>



<h3 id="rtoc-8" >Drawing Error Bars on a Grouped Line Graph</h3>



<p>The same can be done for a grouped line graph as well.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(b, aes(x = Categories, y = mean, group = group, color = group)) +
  geom_line() +
  geom_point(size = 3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                width = .1, color = &quot;black&quot;)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar7-1024x614.jpg" alt="" class="wp-image-913" width="512" height="307"/></figure>



<p>The error bars are on top and overlapping, making it difficult to see. Let&#8217;s move <span class="marker">the error bars to the back first</span>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(b, aes(x = Categories, y = mean, group = group, color = group)) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                width = .1, color = &quot;black&quot;) +
  geom_line() +
  geom_point(size = 3)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar8-1024x614.jpg" alt="" class="wp-image-914" width="512" height="307"/></figure>



<p>By <span class="marker">shifting the position to the left or right</span> using <code>position_dodge()</code>, overlapping of error bars can be avoided.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(b, aes(x = Categories, y = mean, group = group, color = group)) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                width = .1, color = &quot;black&quot;, position = position_dodge(.2)) +
  geom_line(position = position_dodge(.2)) +
  geom_point(size = 3, position = position_dodge(.2))

</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/06/errorbar10-1024x614.jpg" alt="" class="wp-image-915" width="512" height="307"/></figure>



<p>Now you can add error bars to line graphs. I hope this was helpful.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
