<?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>【bar graph】タグの記事一覧｜ドクターフント(Dr. Hund)</title>
	<atom:link href="https://brain-storm.space/tag/bar-graph/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:21:30 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.2</generator>

<image>
	<url>https://brain-storm.space/wp-content/uploads/2021/04/cropped-3d0209af428738b78799159b4ce75ad9-32x32.png</url>
	<title>【bar graph】タグの記事一覧｜ドクターフント(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"  class="wp-block-heading">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"  class="wp-block-heading">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"  class="wp-block-heading">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"  class="wp-block-heading">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"  class="wp-block-heading">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"  class="wp-block-heading">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"  class="wp-block-heading">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"  class="wp-block-heading">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>
		<item>
		<title>【R初心者向け】ggplot2で棒グラフと折れ線グラフにエラーバー(error bar)を書く</title>
		<link>https://brain-storm.space/ggplot2_errorbar/895/</link>
					<comments>https://brain-storm.space/ggplot2_errorbar/895/#respond</comments>
		
		<dc:creator><![CDATA[brainblog]]></dc:creator>
		<pubDate>Fri, 24 Mar 2023 12:20:55 +0000</pubDate>
				<category><![CDATA[論文作成・統計]]></category>
		<category><![CDATA[bar graph]]></category>
		<category><![CDATA[error bar]]></category>
		<category><![CDATA[ggplot2]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[エラーバー]]></category>
		<category><![CDATA[棒グラフ]]></category>
		<guid isPermaLink="false">https://brain-storm.space/?p=895</guid>

					<description><![CDATA[棒グラフや折れ線グラフなどについている#8221;T#8221;が上下についているものがエラーバーです。エラーバーは標準誤差や標準偏差を示しています。 Rのggplot2を使えば簡単にできます。ステップバイステップで]]></description>
										<content:encoded><![CDATA[
<p>棒グラフや折れ線グラフなどについている&#8221;T&#8221;が上下についているものがエラーバーです。エラーバーは標準誤差や標準偏差を示しています。</p>



<p>Rの<span class="marker">ggplot2を使えば簡単にできます</span>。ステップバイステップで書いていきます。</p>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset1 animation-fade rtoc_open default" data-id="895" 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">データの準備する</a></li><li class="rtoc-item"><a href="#rtoc-2">データの平均、標準偏差、標準誤差を算出する</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-3">dplyrのgroup_byとsummarise_allを使う</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4">棒グラフでエラーバーを描く</a></li><li class="rtoc-item"><a href="#rtoc-5">折れ線グラフでエラーバーを描く</a></li><li class="rtoc-item"><a href="#rtoc-6">グループ化されたデータでのエラーバーを加える</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-7">グループ化された棒グラフにエラーバーを追加する</a></li><li class="rtoc-item"><a href="#rtoc-8">グループ化された折れ線グラフでのエラーバーを書く</a></li></ul></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">データの準備する</h2>



<p>tidyverseを利用します。自分のデータを使う場合には読み飛ばしてください。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
# 作業ディレクトリのセット
setwd(&quot;~/Rpractice/&quot;)

# tidyverseの起動
library(tidyverse)

# ランダムデータの生成
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;)

#データの変形(横から縦へ)
df.long &lt;- pivot_longer(df, cols = A:C, 
                        names_to = &quot;Categories&quot;, 
                        values_to = &quot;Values&quot;)
</pre></div>


<p>これでこのようなデータができました。</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>棒グラフと折れ線グラフにエラーバーを加えるには、平均値と標準誤差(または標準偏差)が必要です。pivot_longerで縦長データにしています。</p>



https://brain-storm.space/tidyr_gather_pivot_longer/784/



<h2 id="rtoc-2"  class="wp-block-heading">データの平均、標準偏差、標準誤差を算出する</h2>



<p>エラーバーのためには平均(mean)、標準偏差(sd)、標準誤差(se)を算出します。すでにこれらのデータがある場合にはここも読み飛ばしてください。</p>



<p>その算出方法も慣れれば簡単です！tidyverseに入っているdplyrを使っていきましょう。</p>



<h3 id="rtoc-3"  class="wp-block-heading">dplyrのgroup_byとsummarise_allを使う</h3>



<p>(summariseはアメリカ英語でsummarizeでもOKです)</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>これはもう少し簡素化できます。どちらを使っても大丈夫です。</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>ではaのデータをみてみます。</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>このような分布になりました。データはランダムで生成しましたので、同じ手順をなぞってもこの数値は若干変化します。</p>



<h2 id="rtoc-4"  class="wp-block-heading">棒グラフでエラーバーを描く</h2>



<p>計算をしたデータを使って棒グラフをかきます。<span class="marker">エラーバーはgeom_errorbarで指定します</span>。まずはgeom_errorbarでyminとymaxのみを指定して、グラフをみてみましょう。</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>横幅が広すぎますね。<span class="marker">これをwidthで調整します。</span>バーグラフ、エラーバーともに狭くしてみます。</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>幅は出力する画像の大きさに合わせて適宜調整をするといいです。</p>



<h2 id="rtoc-5"  class="wp-block-heading">折れ線グラフでエラーバーを描く</h2>



<p>折れ線グラフも上と同じ要領です。折れ線グラフを描いて、geom_errorbarを付け足します。</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"  class="wp-block-heading">グループ化されたデータでのエラーバーを加える</h2>



<p>グループ化したデータを生成してみます。</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;# IDを追加する
data &lt;- df.long %&gt;% 
  tibble::rownames_to_column(var = &quot;ID&quot;)

# IDを文字列から数値へ変換する
data$ID &lt;- as.numeric(data$ID)

# IDが75以下を1, 76以上を0と割り当てて、group列を作る
data &lt;- mutate(data, group = ifelse(ID &lt; 76, 1, 0))

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

# group列の数値を文字列に変換する
b$group &lt;- as.character(b$group)

# 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>これでグループ化されました。このデータでエラーバーの入った棒グラフを描いてみましょう。</p>



<h3 id="rtoc-7"  class="wp-block-heading">グループ化された棒グラフにエラーバーを追加する</h3>



<p>position = &#8220;dodge&#8221;をするとこのような棒グラフができます。</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>これにエラーバーを加えていきます。</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>真ん中に寄ってしまいました。この位置は<span class="marker">position = position_dodge()で調整できます</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>これでいい棒グラフができました！</p>



<h3 id="rtoc-8"  class="wp-block-heading">グループ化された折れ線グラフでのエラーバーを書く</h3>



<p>折れ線グラフも同じようにできます。</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>エラーバーが前面に出ていて重なっているので見にくくなっています。まず<span class="marker">エラーバーを後ろに持って</span><span class="marker">い</span><span class="marker">きます。</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>エラーバーが重なりは<span class="marker">左右にずらす</span>ことで解消ができます。さきほどの<span class="marker">position_dodgeを使います</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;, 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>これで折れ線グラフのエラーバーを加えることができました。お役に立ちましたら幸いです。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://brain-storm.space/ggplot2_errorbar/895/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【ggplot2】Rで棒グラフを作成する</title>
		<link>https://brain-storm.space/bargraph/1025/</link>
					<comments>https://brain-storm.space/bargraph/1025/#respond</comments>
		
		<dc:creator><![CDATA[brainblog]]></dc:creator>
		<pubDate>Thu, 01 Jul 2021 04:33:36 +0000</pubDate>
				<category><![CDATA[論文作成・統計]]></category>
		<category><![CDATA[bar graph]]></category>
		<category><![CDATA[ggplot2]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[rstats]]></category>
		<guid isPermaLink="false">https://brain-storm.space/?p=1025</guid>

					<description><![CDATA[最もよく使われる棒グラフですが、その中でもいくつか使い分けが必要です。そのいくつかの種類の棒グラフの描き方を紹介します。 Contents データの準備棒グラフはgeom_bar()を使う色を付けるグループ化された棒グラ]]></description>
										<content:encoded><![CDATA[
<p>最もよく使われる棒グラフですが、その中でもいくつか使い分けが必要です。そのいくつかの種類の棒グラフの描き方を紹介します。</p>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset1 animation-fade rtoc_open default" data-id="1025" 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">データの準備</a></li><li class="rtoc-item"><a href="#rtoc-2">棒グラフはgeom_bar()を使う</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-3">色を付ける</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4">グループ化された棒グラフを作図する</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-5">積み上げ棒グラフ</a></li><li class="rtoc-item"><a href="#rtoc-6">グループ別の棒グラフ</a></li><li class="rtoc-item"><a href="#rtoc-7">幅を調整する</a></li><li class="rtoc-item"><a href="#rtoc-8">100％積み上げ棒グラフ</a></li><li class="rtoc-item"><a href="#rtoc-9">横向き棒グラフ</a></li><li class="rtoc-item"><a href="#rtoc-10">凡例の順番を入れ替える</a></li><li class="rtoc-item"><a href="#rtoc-11">色を変える</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-12">エラーバーをつける</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-13">縦棒グラフ＋エラーバー</a></li><li class="rtoc-item"><a href="#rtoc-14">横棒グラフ＋エラーバー</a></li></ul></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">データの準備</h2>



<p>まずはデータの準備をします。デモ用のデータとして最もよく使われるiris(アヤメ)データセットを今回も使います。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
# 作業ディレクトリ
setwd(&quot;~/Rpractice/&quot;)

# tidyverseの起動
library(tidyverse)

#irisデータをaに格納
a &lt;- iris

#データの確認
&gt; head(a)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
&gt; 
</pre></div>


<p>それではこのirisデータを用いていくつかの棒グラフをつくっていきます。</p>



<h2 id="rtoc-2"  class="wp-block-heading">棒グラフはgeom_bar()を使う</h2>



<p>それではgeom_bar()を使っていきます。まずはアヤメデータの先頭にあるSepal.Lengthの値を使っていきます。</p>



<p>横軸にアヤメの種類(Species)、縦軸にSepal.Lengthをとります。値をy軸に取るときにはgeom_bar(stat = &#8220;identity&#8221;)とidentityを指定します。その他にはcountとbinを取ることが出来ます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a, aes(Species, Sepal.Length))+
  geom_bar(stat = &quot;identity&quot;)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph1-1024x1024.jpg" alt="" class="wp-image-1026" width="512" height="512"/></figure>



<div class="wp-block-jin-gb-block-box concept-box2">
<p>グラフを作成したら何が縦軸の値をとっているのか、しっかり確認することが必要です。元のデータと対比し、自分の出したい値が作図されているか確認しましょう。上の例では積み上げになっています。</p>
</div>



<h3 id="rtoc-3"  class="wp-block-heading">色を付ける</h3>



<p>塗りつぶしにはaesの中でfillを指定します。枠の色を指定したいときはcolourで指定します</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a, aes(Species, Sepal.Length, fill = Species))+
  geom_bar(stat = &quot;identity&quot;)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph2-1024x1024.jpg" alt="" class="wp-image-1027" width="512" height="512"/></figure>



<p>個数を出したいときはgeom_bar(stat = &#8220;count&#8221;)と指定します。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a, aes(x = Species, fill = Species))+
  geom_bar(stat = &quot;count&quot;)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph3-1024x1024.jpg" alt="" class="wp-image-1028" width="512" height="512"/></figure>



<h2 id="rtoc-4"  class="wp-block-heading">グループ化された棒グラフを作図する</h2>



<p>まず最初に平均値を計算します。合わせて、SDやSEも計算をしておくとエラーバーを付け加えることができます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
# 縦長のグラフ
a.long &lt;- pivot_longer(a, col = Sepal.Length:Petal.Width,
                         names_to = &quot;iris.attr&quot;, 
                       values_to = &quot;measures&quot;)

# グループごとの平均値などの計算
a.sum &lt;- group_by(a.long, iris.attr, Species) %&gt;% 
  summarize_all(list(mean = mean,
                     max = max,
                     sd = sd, 
                     se = ~sd/sqrt(length(.))))

</pre></div>


<h3 id="rtoc-5"  class="wp-block-heading">積み上げ棒グラフ</h3>



<p>geom_barでpositionを指定しなければ積み上げ棒グラフになります。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y = mean,　fill = Species))+
  geom_bar(stat = &quot;identity&quot;)

</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph3.5-1-1024x819.jpg" alt="" class="wp-image-1032" width="512" height="410"/></figure>



<h3 id="rtoc-6"  class="wp-block-heading">グループ別の棒グラフ</h3>



<p>それぞれグループを横に並べた棒グラフはgeom_barでposition = &#8220;dodge&#8221;と指定します。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y = mean,　fill = Species))+
  geom_bar(stat = &quot;identity&quot;, 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/07/bargraph4-1-1024x819.jpg" alt="" class="wp-image-1030" width="512" height="410"/></figure>



<h3 id="rtoc-7"  class="wp-block-heading">幅を調整する</h3>



<p>横幅についてはwidthで調整をします。width = 0.5にしてみます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.long, aes(x = iris.attr, y =measures, fill = Species))+
  geom_bar(stat = &quot;identity&quot;, position = &quot;dodge&quot; , width = 0.5)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph3.8-1024x819.jpg" alt="" class="wp-image-1039" width="512" height="410"/></figure>



<h3 id="rtoc-8"  class="wp-block-heading">100％積み上げ棒グラフ</h3>



<p>実際の数値ではなく、割合で比較したい時に有用です。</p>



<p>geom_bar(position = &#8220;fill&#8221;)とすることで100％積み上げ棒グラフを作図できます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y = mean,　fill = Species))+
  geom_bar(stat = &quot;identity&quot;, position = &quot;fill&quot;)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph5-1024x819.jpg" alt="" class="wp-image-1033" width="512" height="410"/></figure>



<h3 id="rtoc-9"  class="wp-block-heading">横向き棒グラフ</h3>



<p>横向きにするときにはcood_flip()を追加します。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y =mean,　fill = Species))+
  geom_bar(stat = &quot;identity&quot;, position = &quot;dodge&quot;) +
  coord_flip()
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph6-1024x819.jpg" alt="" class="wp-image-1034" width="512" height="410"/></figure>



<h3 id="rtoc-10"  class="wp-block-heading">凡例の順番を入れ替える</h3>



<p>棒グラフの並びと凡例の並びが合わないときにはguides(fill = guide_legend(reverse = TRUE))を指定します。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y =mean,　fill = Species))+
  geom_bar(stat = &quot;identity&quot;, position = &quot;dodge&quot;) +
  coord_flip()+
  guides(fill = guide_legend(reverse = TRUE))
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph7-1024x819.jpg" alt="" class="wp-image-1036" width="512" height="410"/></figure>



<h3 id="rtoc-11"  class="wp-block-heading">色を変える</h3>



<p>色を変える方法は色々とありますが、scale_fill_brewerで簡単にセット化されたものを使ってみます。</p>



<p>scale_fill_brewer(palette = &#8220;Set1&#8221;)と指定します。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y = mean, fill = Species))+
  geom_bar(stat = &quot;identity&quot;, position = &quot;dodge&quot; , width = 0.9)+
  scale_fill_brewer(palette = &quot;Set1&quot;)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph8-1024x819.jpg" alt="" class="wp-image-1037" width="512" height="410"/></figure>



<p>さらにscale_fill_brewer(palette = &#8220;Set2&#8221;)で色を変えてみます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y = mean, fill = Species))+
  geom_bar(stat = &quot;identity&quot;, position = &quot;dodge&quot; , width = 0.9)+
  scale_fill_brewer(palette = &quot;Set2&quot;)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph9-1024x819.jpg" alt="" class="wp-image-1038" width="512" height="410"/></figure>



<h2 id="rtoc-12"  class="wp-block-heading">エラーバーをつける</h2>



<p>最後にエラーバーをつけます。</p>



<p>エラーバーをの付け方については、次のリンクで詳しく説明をしています。</p>



https://brain-storm.space/ggplot2_errorbar/895/



<h3 id="rtoc-13"  class="wp-block-heading">縦棒グラフ＋エラーバー</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y = mean, fill = Species))+
  geom_bar(stat = &quot;identity&quot;, position = &quot;dodge&quot; , width = 0.9)+
  scale_fill_brewer(palette = &quot;Set1&quot;)+
    geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                  position = position_dodge(0.9), width = .2)
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph10-1024x819.jpg" alt="" class="wp-image-1040" width="512" height="410"/></figure>



<h3 id="rtoc-14"  class="wp-block-heading">横棒グラフ＋エラーバー</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(a.sum, aes(x = iris.attr, y = mean, fill = Species))+
  geom_bar(stat = &quot;identity&quot;, position = &quot;dodge&quot; , width = 0.9)+
  scale_fill_brewer(palette = &quot;Set1&quot;)+
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                position = position_dodge(0.9), width = .2)+
  guides(fill = guide_legend(reverse = TRUE))+
  coord_flip()

</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://brain-storm.space/wp-content/uploads/2021/07/bargraph11-1024x819.jpg" alt="" class="wp-image-1041" width="512" height="410"/></figure>



<p>お役に立ちましたら幸いです。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://brain-storm.space/bargraph/1025/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
