Bus errorとSegmentation faultに困ったら見るブログ

物理の研究者による日々の研究生活のメモ書きです ( python/emacs/html/Japascript/シェルスクリプト/TeX/Mac/C言語/Linux/git/tmux/R/ポケモンGO)

【matplotlib, subplot】1枚のプロットサイズを任意に変えたい + 右にヒストグラムを乗せたい

まずは過去記事で、1つのページにプロットを複数並べる方法の復習

subplotで複数枚並べる方法

今回はこっちを使う
coffee-guhaw.hateblo.jp

subplotsで複数枚並べる方法

今回はこっちは使わない
coffee-guhaw.hateblo.jp

subplotで1枚のプロットの面積を変えたい

from matplotlib import pyplot as plt
import numpy as np

nn = 2
fig = plt.figure(figsize=(18, 4.5*nn))
axes = fig.add_gridspec(nn, 4)

cmap = plt.get_cmap("tab10")

x = np.linspace(0, 2*np.pi, 500)

ax = fig.add_subplot(axes[0, 0:3])
ax.plot(x, np.sin(x), color="red")
ax.grid()

ax = fig.add_subplot(axes[0, -1])  

ax.hist(np.sin(x), bins=40, alpha=.5, log=True, orientation="horizontal")
ax.set_xlabel("log(histogram)")    
ax.grid()    

##############

ax = fig.add_subplot(axes[1, 0:3])
ax.plot(x, np.cos(x), color="red")
ax.grid()

ax = fig.add_subplot(axes[1, -1])  

ax.hist(np.cos(x), bins=40, alpha=.5, log=True, orientation="horizontal")
ax.set_xlabel("log(histogram)")    
ax.grid()    


plt.subplots_adjust(hspace=0.5, wspace=0.5)

fig.savefig("hoge.png")

みたいな感じで、下のようなプロットができる
左に時系列データ、右にそのヒストグラム

やってることの補足

fig = plt.figure(figsize=(18, 4.5*nn))

でかい図を1つ作る、その中をsubplotで小さく刻んでいく感じ

axes = fig.add_gridspec(nn, 4)

1つのfigを縦方向に2つに、横方向に4つに分割する
4つにしてるのは、あとで4つを3:1の割合で使うから

ax = fig.add_subplot(axes[0, 0:3])
ax = fig.add_subplot(axes[0, -1])
がそれ
この方法は以下にあった
Customizing Figure Layouts Using GridSpec and Other Functions — Matplotlib 3.1.0 documentation

【Matplotlib】Gridspecーグラフの柔軟な分割(3:1でもで4:1でも) - RuntaScience diary


subplotsでいうところの、

gridspec_kw={"width_ratios": [3, 1]}

と同じ
subplotでは、↑のようにそれを実現できるっぽい

ax.hist(np.sin(x), bins=40, alpha=.5, log=True, orientation="horizontal")

ヒストグラムを90度回転させてる

注意しないといけないのは、図を回転させたあとで、xlabelをつけてること
元々の図のxlabelではなくて回転させてから、xlabelをつけてるのでこんな感じになる

plt.subplots_adjust(hspace=0.5, wspace=0.5)

図の間隔はこれで調整する

ランキング参加中です

↓クリックしていただけると嬉しいです〜