(バージョン情報)
python・・・3.9.7
numpy・・・1.20.3
pandas・・・1.3.4
matplotlib・・・3.4.3
(やりたいこと)
・以下のようなフォーマットのデータをもとに、USDJPY(為替レート)を左軸、index1、index2を右軸にプロットした2軸グラフを書きたい。
utc_datetime instrument close index1 index2
0 2022-08-01 00:00:00+00:00 USDJPY 133.366 0.008349 0.018714
1 2022-08-01 00:01:00+00:00 USDJPY 133.341 0.008417 0.018710
2 2022-08-01 00:02:00+00:00 USDJPY 133.355 0.008485 0.018707
・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・
「土日抜き」の分単位のデータが20営業日分、つまり1440×20=28800レコードあります。
(悩み)
週末はデータがないにもかかわらず、matplotlibで描画すると金曜日の一番最後のデータと月曜日の一番最初のデータを勝手に直線で結んでしまう。
(やってみたこと)
①df[“utc_datetime”]を以下のコマンドで文字列化。
df["str_date"] = df["utc_datetime"].dt.strftime("%Y/%m/%d %H:%M")
②以下のコマンドで、x軸ラベルを2880間隔にする。
ax1.xaxis.set_major_locator(ticker.MultipleLocator(2880))
(結果)
下記のコマンドを走らせた結果、
・10分以上たっても反応を返さなくなった。(15分経ってようやく描画)
・軸目盛が2880間隔にならず、x軸が全データ表示によりつぶれている。
・グラフ領域がグレーで塗りつぶされてしまった。
・どこが悪かったのか、アドバイスをいただけると幸甚です。
(失敗コード)
2軸グラフ設定
fig = plt.figure(figsize=(8, 6))
ax1 = fig.add_subplot(1, 1, 1)
ax2 = ax1.twinx()
x, y軸データ
x = df["str_date"]
y1 = df["close"]
y2 = df[ df.columns[num1] ]
y3 = df[ df.columns[num2] ]
色と凡例
c1, c2, c3 = "tab:blue", "tab:orange", "tab:green" # 各プロットの色
l1, l2, l3 = currency, "index1", "index2" # 各ラベル
1つ目のグラフを描画
g_title = currency + " vs index " + " (" + country + ")"
ax1.xaxis.set_major_locator(ticker.MultipleLocator(2880))
ax1.set_title(g_title) # グラフタイトル
ax1.grid() # 罫線
ax1.xaxis.set_tick_params(rotation = 90)
ax1.plot(x, y1, color = c1,label=l1)
h1, l1 = ax1.get_legend_handles_labels()
2つ目のグラフを描画
ax2.plot(x, y2, color = c2, label = l2, linewidth = 0.5)
ax2.plot(x, y3, color = c3, label = l3, linewidth = 0.5)
plt.fill_between(x, y2, y3, facecolor = "gray", alpha = 0.3)
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2)
plt.show()

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/11/14 08:29
2022/11/14 08:54
2022/11/15 01:03
2022/11/15 02:12
2022/11/15 07:01
2022/11/15 14:07