<?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>【heatmap】タグの記事一覧｜ドクターフント(Dr. Hund)</title>
	<atom:link href="https://brain-storm.space/tag/heatmap/feed/" rel="self" type="application/rss+xml" />
	<link>https://brain-storm.space</link>
	<description>脳や研究について発信するブログです。This site is for research and statistics.</description>
	<lastBuildDate>Mon, 13 Dec 2021 13:21:54 +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>【heatmap】タグの記事一覧｜ドクターフント(Dr. Hund)</title>
	<link>https://brain-storm.space</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【R】ggplot2で相関行列ヒートマップを描く</title>
		<link>https://brain-storm.space/corrheatmap/942/</link>
					<comments>https://brain-storm.space/corrheatmap/942/#respond</comments>
		
		<dc:creator><![CDATA[brainblog]]></dc:creator>
		<pubDate>Tue, 22 Jun 2021 08:09:26 +0000</pubDate>
				<category><![CDATA[論文作成・統計]]></category>
		<category><![CDATA[ggplot2]]></category>
		<category><![CDATA[heatmap]]></category>
		<category><![CDATA[R]]></category>
		<guid isPermaLink="false">https://brain-storm.space/?p=942</guid>

					<description><![CDATA[相関行列の相関係数を表にすることも多いと思います。しかし視覚に訴求する強力なツールとしてRで図を作成することができます。 それの一つが相関行列です。 Rではいくつものパッケージがあるので、そちらを使うこともできますが、シ]]></description>
										<content:encoded><![CDATA[
<p>相関行列の相関係数を表にすることも多いと思います。しかし視覚に訴求する強力なツールとしてRで図を作成することができます。</p>



<p><span class="marker">それの一つが相関行列です。</span></p>



<p>Rではいくつものパッケージがあるので、そちらを使うこともできますが、シンプルにggplot2を使った方法を紹介します。</p>



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame2 preset1 animation-fade rtoc_open default" data-id="942" 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><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-2">mtcarsとは</a></li><li class="rtoc-item"><a href="#rtoc-3">相関行列の生成</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4">geom_tileを使って相関行列のヒートマップを描く</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-5">geoｍ_tile()を使う</a></li><li class="rtoc-item"><a href="#rtoc-6">scale_fill_gradientで色の変更をする</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-7">ヒートマップの中に数値を表示する</a></li><li class="rtoc-item"><a href="#rtoc-8">軸ラベルの順番を変える</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-9">y軸を反転させる</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-10">三角行列で表示をしたい時</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-11">上三角行列</a></li><li class="rtoc-item"><a href="#rtoc-12">下三角行列</a></li></ul></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">データの準備をします</h2>



<p>相関行列を使います。デモのためにこの記事ではmtcarsのデータを使ってみます。</p>



<div class="wp-block-jin-gb-block-border jin-sen"><div class="jin-sen-dashed" style="border-width:3px;border-color:#f48789"></div></div>



<h3 id="rtoc-2"  class="wp-block-heading">mtcarsとは</h3>



<div class="wp-block-jin-gb-block-box concept-box5">
<p>mtcarsは1974年にMotor Trends US Magazineという雑誌から抽出された、各車種における燃費などの車性能が入ったデータです。</p>



<p>mpg:燃費、cyl:気筒数、disp:排気量などのデータが入っています。</p>
</div>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
&gt; mtcars
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
&gt; 
</pre></div>


<div class="wp-block-jin-gb-block-border jin-sen"><div class="jin-sen-dashed" style="border-width:3px;border-color:#f48789"></div></div>



<h3 id="rtoc-3"  class="wp-block-heading">相関行列の生成</h3>



<p>相関行列を生成してみます。</p>



<p>mtcarsのデータからSpearmanの順位相関係数をみてみます。またggplot2で使いやすいようにデータを変形していきます。相関はcorで計算をしており、その中のmethodでspearmanと指定しています。</p>



<p>縦のデータへの変換はpivot_longerを用いています。pivot_longerは次の記事に詳しい説明があります。</p>



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


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
# tidyverseの起動
library(tidyverse)

#mtcars
a &lt;- mtcars

#相関行列(Spearman)
cormat &lt;- cor(a, method = &quot;spearman&quot;)

#データフレーム化
df &lt;- data.frame(cormat) %&gt;% 

#列名の抽出
tibble::rownames_to_column(var = &quot;Y&quot;)

#縦のデータへ
df.long &lt;- pivot_longer(df, 
                            cols = mpg:carb,
                            names_to = &quot;X&quot;, 
                            values_to = &quot;rho&quot;)

#データの確認
&gt; head(df.long)
# A tibble: 6 x 3
  Y     X        rho
  &lt;fct&gt; &lt;fct&gt;  &lt;dbl&gt;
1 mpg   mpg    1    
2 mpg   cyl   -0.911
3 mpg   disp  -0.909
4 mpg   hp    -0.895
5 mpg   drat   0.651
6 mpg   wt    -0.886
&gt; 


</pre></div>


<p>以上のようなデータになりました。自分のデータで相関行列があればそれを縦のデータに変換して利用することができます。</p>



<h2 id="rtoc-4"  class="wp-block-heading">geom_tileを使って相関行列のヒートマップを描く</h2>



<p>geom_tile()を使うことで視覚化することができます。</p>



<p>次のようになります。</p>



<h3 id="rtoc-5"  class="wp-block-heading">geoｍ_tile()を使う</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(df.long, aes(x = X, y = Y, fill = rho)) + 
  geom_tile()
</pre></div>


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



<h3 id="rtoc-6"  class="wp-block-heading">scale_fill_gradientで色の変更をする</h3>



<p>色を変更してみます。よく見るのは値の高いところが赤、低いところが青ですよね？</p>



<p>scale_fill_gradient2を使ってみます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
ggplot(df.long, aes(x = X, y = Y, fill = rho)) + 
  geom_tile(color = &quot;white&quot;) + 
  scale_fill_gradient2(low = &quot;blue&quot;, high = &quot;red&quot;, mid = &quot;white&quot;, 
                       midpoint = 0, limit = c(-1, 1), 
                       name = &quot;Rho&quot;, space = &quot;Lab&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/cormat2-1024x819.jpg" alt="" class="wp-image-975" width="512" height="410"/></figure>



<p> これで出来ました！</p>



<p>ところでここに数値を入れたい人もいるかもしれません。</p>



<h2 id="rtoc-7"  class="wp-block-heading">ヒートマップの中に数値を表示する</h2>



<p>数値を入れるにはgeom_text()で出来ます！</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
df.long %&gt;% 
  ggplot(aes(x = X, y = Y, fill = rho)) + 
  geom_tile(color = &quot;white&quot;) + 
  scale_fill_gradient2(low = &quot;blue&quot;, high = &quot;red&quot;, mid = &quot;white&quot;, 
                       midpoint = 0, limit = c(-1, 1), name = &quot;Rho&quot;, space = &quot;Lab&quot;)+
  geom_text(aes(label = sprintf(&quot;%0.2f&quot;, rho)),
            color = &quot;black&quot;, size = 2.5)
</pre></div>


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



<h2 id="rtoc-8"  class="wp-block-heading">軸ラベルの順番を変える</h2>



<p>軸ラベルがアルファベット順になっていることに気がついたでしょうか。</p>



<p>これが不便に感じるときがあります。そういうときはfactor(data, levels = )で軸ラベルの順番を指定すれば解決です。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
lbs &lt;- df&#91;,1]
df.long$X &lt;- factor(df.long$X, levels = lbs)
df.long$Y &lt;- factor(df.long$Y, levels = lbs)

df.long %&gt;% 
  ggplot(aes(x = X, y = Y, fill = rho)) + 
  geom_tile(color = &quot;white&quot;) + 
  scale_fill_gradient2(low = &quot;blue&quot;, high = &quot;red&quot;, mid = &quot;white&quot;, 
                       midpoint = 0, limit = c(-1, 1), name = &quot;Rho&quot;, space = &quot;Lab&quot;)+
  geom_text(aes(label = sprintf(&quot;%0.2f&quot;, rho)),
            color = &quot;black&quot;, size = 2.5)
</pre></div>


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



<p>順番はdata &lt;- factor(data, levels = c(&#8220;mpg&#8221;, &#8220;cyl&#8221;, &#8220;disp&#8221;, &#8230;.))というように一つ一つ指定することもできます。</p>



<h3 id="rtoc-9"  class="wp-block-heading">y軸を反転させる</h3>



<p>上のグラフは左下からラベルが並んでいます。y軸は上からはじまって欲しい場合があります。</p>



<p>そういうときはy軸の並びを反転させます。</p>



<p>scale_y_discrete(limits = rev(levels( )))で反転できます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
df.long %&gt;% 
  ggplot(aes(x = X, y = Y, fill = rho)) + 
  geom_tile(color = &quot;white&quot;) + 
  scale_fill_gradient2(low = &quot;blue&quot;, high = &quot;red&quot;, mid = &quot;white&quot;, 
                       midpoint = 0, limit = c(-1, 1), name = &quot;Rho&quot;, space = &quot;Lab&quot;)+
  geom_text(aes(label = sprintf(&quot;%0.2f&quot;, rho)),
            color = &quot;black&quot;, size = 2.5)+
  scale_y_discrete(limits = rev(levels(df.long$Y)))
</pre></div>


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



<h2 id="rtoc-10"  class="wp-block-heading">三角行列で表示をしたい時</h2>



<p>上の図では対角線で対称になっていますが、余計な情報だと思うかもしれません。それであれば三角行列にしてみます。</p>



<p>ただし、ggplotで三角行列にするというより、データ自体を三角行列になるようにしていきます。</p>



<h3 id="rtoc-11"  class="wp-block-heading">上三角行列</h3>



<p> 上三角行列にするには下の部分をNAにして、その部分を空欄にします。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
# 上三角行列にするためのfunction
# 下にはNAを代入する
get_upper_tri &lt;- function(cormat){
  cormat&#91;lower.tri(cormat)]&lt;- NA
  return(cormat)
}

# 実際のデータに適応
upper_tri &lt;- get_upper_tri(cormat)

# データの変形
df_upper_tri &lt;- data.frame(upper_tri) %&gt;% 
  tibble::rownames_to_column(var = &quot;Y&quot;)

df_upper_tri.long &lt;- pivot_longer(df_upper_tri, 
                        cols = mpg:carb,
                        names_to = &quot;X&quot;, 
                        values_to = &quot;rho&quot;)

# ラベルの並び替え
lbs2 &lt;- df_upper_tri&#91;,1]
df_upper_tri.long$X &lt;- factor(df_upper_tri.long$X, levels = lbs2)
df_upper_tri.long$Y &lt;- factor(df_upper_tri.long$Y, levels = lbs2)

# 作図
df_upper_tri.long %&gt;% 
  ggplot(aes(x = X, y = Y, fill = rho)) + 
  geom_tile(color = &quot;white&quot;) + 
  scale_fill_gradient2(low = &quot;blue&quot;, high = &quot;red&quot;, mid = &quot;white&quot;, 
                       midpoint = 0, limit = c(-1, 1), 
                       name = &quot;Rho&quot;, space = &quot;Lab&quot;,
                       na.value = &quot;white&quot;)+
  geom_text(aes(label = ifelse(is.na(rho) | rho %in% &quot;&quot;,NA, sprintf(&quot;%0.2f&quot;, rho))),
            color = &quot;black&quot;, size = 4.5)+
  scale_y_discrete(limits = rev(levels(df_upper_tri.long$Y)))+
  theme_classic()

</pre></div>


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



<h3 id="rtoc-12"  class="wp-block-heading">下三角行列</h3>



<p>下三角も同様に出来ます。</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: r; title: Code example; notranslate">
# 下三角行列にするためのfunction
# 上にはNAを代入する
get_lower_tri &lt;- function(cormat){
  cormat&#91;upper.tri(cormat)]&lt;- NA
  return(cormat)
}

# 実際のデータに適応
lower_tri &lt;- get_lower_tri(cormat)

# データの変形
df_lower_tri &lt;- data.frame(lower_tri) %&gt;% 
  tibble::rownames_to_column(var = &quot;Y&quot;)

df_lower_tri.long &lt;- pivot_longer(df_lower_tri, 
                                  cols = mpg:carb,
                                  names_to = &quot;X&quot;, 
                                  values_to = &quot;rho&quot;)

# ラベルの並び替え
lbs3 &lt;- df_lower_tri&#91;,1]
df_lower_tri.long$X &lt;- factor(df_lower_tri.long$X, levels = lbs3)
df_lower_tri.long$Y &lt;- factor(df_lower_tri.long$Y, levels = lbs3)

# 作図
df_lower_tri.long %&gt;% 
  ggplot(aes(x = X, y = Y, fill = rho)) + 
  geom_tile(color = &quot;white&quot;) + 
  scale_fill_gradient2(low = &quot;blue&quot;, high = &quot;red&quot;, mid = &quot;white&quot;, 
                       midpoint = 0, limit = c(-1, 1), 
                       name = &quot;Rho&quot;, space = &quot;Lab&quot;,
                       na.value = &quot;white&quot;)+
  geom_text(aes(label = ifelse(is.na(rho) | rho %in% &quot;&quot;,NA, sprintf(&quot;%0.2f&quot;, rho))),
            color = &quot;black&quot;, size = 2.5)+
  scale_y_discrete(limits = rev(levels(df_lower_tri.long$Y)))+
  theme_classic()

</pre></div>


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



<p>ifelseの使い方が初心者には難しいかもしれませんが、慣れれば特定の閾値以下は表示しない、などのテクニックなども使えます。</p>



<p>便利なグラフなので、覚えて損はありません。お役に立ちましたら幸いです。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://brain-storm.space/corrheatmap/942/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
