Matplotlibで複数のラベルを持つ棒グラフをプロットする方法は?
Matplotlibで複数のラベルを持つ棒グラフをプロットするには、次の手順を実行できます-
-
men_means、men_std、women_means、のデータセットを作成します およびwomen_std 。
-
numpyを使用してインデックスデータポイントを作成します。
-
幅を初期化します バーの。
-
subplots()を使用する 図とサブプロットのセットを作成する方法。
-
rects1を作成します およびrects2 bar()を使用して長方形をバーします メソッド。
-
set_ylabel()、を使用します set_title() 、 set_xticks() およびset_xticklabels() メソッド。
-
プロットに凡例を配置します。
-
autolabel()を使用して、棒グラフに複数のラベルを追加します メソッド。
-
図を表示するには、 show()を使用します メソッド。
例
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
ind = np.arange(len(men_means)) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()
def autolabel(rects, xpos='center'):
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0, 'right': 1, 'left': -1}
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(offset[xpos]*3, 3), # use 3 points offset
textcoords="offset points", # in both directions
ha=ha[xpos], va='bottom')
autolabel(rects1, "left")
autolabel(rects2, "right")
plt.show() 出力
-
Matplotlibで複数のX軸またはY軸をプロットするにはどうすればよいですか?
複数のX軸またはY軸をプロットするには、 twinx()を使用できます。 またはtwiny() メソッドでは、次の手順を実行できます- subplots()の使用 メソッド、図とサブプロットのセットを作成します。 [1、2、3、4、5]のデータポイントを左側のY軸スケールにプロットします。 twinx()の使用 この方法では、X軸は共有されているが、Y軸は独立しているax2の双子の軸を作成します。 [11、12、31、41、15]のデータポイントを右側のY軸スケールに青色でプロットします。 tight_layout()の使用 方法として、サブプロット間および
-
カラーバーMatplotlibを使用してPythonで2D行列をプロットする方法は?
Pythonでカラーバーを使用して2D行列をプロットするには、numpyを使用して2D配列行列を作成し、その行列を imshow()で使用します。 メソッド。 ステップ data2Dを作成します numpyを使用しています。 imshow()を使用する データを画像として、つまり2Dの通常のラスターに表示する方法。 ScalarMappableインスタンスのカラーバーを作成する*mappable * colorbar()を使用する メソッドとimshow() スカラーマッピング可能な画像。 図を表示するには、 show()を使用します メソッド。 例 imp