@MS13 (鈴木 理道)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

【R】ggplot2によるヒートマップ図と折れ線グラフの重ね合わせる方法

Q&A

Closed

■前提・実現したいこと
Rのggplot2ライブラリを利用して以下のデータで作成したヒートマップ図と折れ線グラフを重ね合わせた図を作成したいです。
以下のdf_sのvariable列とdf_tpのprice列が同じ単位の値でそれらを縦軸として重ね合わせた図を作成したいのですがうまく行きません。
試したことに記載の部分までできているのですが、左側にdf_sのvariable列の尺度を表示させてうまく上下の空白をなくす方法を教えていだだきたいです。

【ヒートマップ図を作成するためのデータ】

> head(df_s)
                  time variable  value
1 2020-01-01T20:40:00Z    109.0 0.4483
2 2020-01-02T20:40:00Z    109.0 0.3204
3 2020-01-01T20:40:00Z   108.95 0.3267
4 2020-01-02T20:40:00Z   108.95 0.3596
5 2020-01-01T20:40:00Z    108.9 0.5764
6 2020-01-02T20:40:00Z    108.9 0.5557

> sapply(df_s,class)
       time    variable       value 
"character"    "factor"   "numeric" 

【折れ線グラフを作成するためのデータ】

> df_tp
                  time   price
1 2020-01-01T20:40:00Z 108.628
2 2020-01-02T20:40:00Z 108.526

> sapply(df_tp,class)
       time       price 
"character"   "numeric" 

■発生している問題・エラーメッセージ
ただ以下のggplot2のコードを実行するとヒートマップ図と折れ線グラフが重ならない物ができてしまいます。

ggplot(data = df_s, aes(x = time, y = variable)) +
+   theme_gray(base_family = "HiraKakuPro-W3") +
+   geom_tile(aes(fill = value)) +
+       scale_fill_gradientn(colours = c("yellow", "red")) +
+       geom_text(aes(label = value)) + scale_y_discrete(name="", limits = rev(levels(df_s$variable))) + geom_line(data = df_tp, aes(x = time, y = price, group = 1), color = "red")

スクリーンショット 2020-08-13 22.47.25.png

■試したこと
df_tpのprice列のデータ型がnumeric型で、ds_sのvariable列のデータ型がfactor型なのがいけないのかと思い、ds_sのvariable列のデータ型をnumeric型に変更してみで上記のコードを実行したのですが今度は左側のprice,variable列の値が出なくなってしまいました。
左側にdf_sのvariable列の尺度を表示させてうまく上下の空白をなくす方法を教えていだだきたいです。

> df_s$variable <- as.numeric(as.character(df_s$variable))
> head(df_s)
                  time variable  value
1 2020-01-01T20:40:00Z   109.00 0.4483
2 2020-01-02T20:40:00Z   109.00 0.3204
3 2020-01-01T20:40:00Z   108.95 0.3267
4 2020-01-02T20:40:00Z   108.95 0.3596
5 2020-01-01T20:40:00Z   108.90 0.5764
6 2020-01-02T20:40:00Z   108.90 0.5557
> sapply(df_s,class)
       time    variable       value 
"character"   "numeric"   "numeric"

> ggplot(data = df_s, aes(x = time, y = variable)) +
     theme_gray(base_family = "HiraKakuPro-W3") +
     geom_tile(aes(fill = value)) +
      scale_fill_gradientn(colours = c("yellow", "red")) +
      geom_text(aes(label = value)) + scale_y_discrete(name="", limits = rev(levels(df_s$variable))) + geom_line(data = df_tp, aes(x = time, y = price, group = 1), color = "red")

スクリーンショット 2020-08-13 23.00.31.png

0 likes

2Answer

手元で確認できないので申し訳ないのですが、もしかしたらgeom_tileの代わりにgeom_rasterを使えばうまくいくかもしれません。

0Like

Your answer might help someone💌