以下のコード:
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
p1 = [20, 35, 30, 35, 7]
p2 = [25, 32, 34, 20, 55]
p3 = [21, 361, 341, 205,151]
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
fig.set_figheight(7)
fig.set_figwidth(13)
ax.bar(labels, p1, width, label='p1')
ax.bar(labels, p2, width, bottom=p1, label='p2')
ax.bar(labels, p3, width, bottom=p2, label='p3')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
figure(num=None, figsize=(14, 7), dpi=80, facecolor='w', edgecolor='k')
plt.show()
レンダリング:
このチャートを水平に変換しようとしています-積み重ねられた各バーは水平に表示されます。
使用するコードを変更しますhbar
:
ax.hbar(labels, p1, width, label='p1')
ax.hbar(labels, p2, width, bottom=p1, label='p2')
ax.hbar(labels, p3, width, bottom=p2, label='p3')
しかし、これはエラーを引き起こします:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-39-71e7a37d2257> in <module>
10 fig.set_figwidth(13)
11
---> 12 ax.hbar(labels, p1, width, label='p1')
13 ax.hbar(labels, p2, width, bottom=p1, label='p2')
14 ax.hbar(labels, p3, width, bottom=p2, label='p3')
AttributeError: 'AxesSubplot' object has no attribute 'hbar'
積み上げ棒グラフになるようにグラフを修正する方法。横に表示できますか?
引数bottom=
をに変更することができなかったようですleft=
。一般に、プロットには2つの方法があります。明白なのは使用することでbarh
あり、あまり明白でないオプションは既存の(垂直)プロットを変換することです(この投稿bar
への回答が説明しているように):
編集/注:@ JohanCが正しく指摘したように、MVEコードには、3番目の(緑色の)バーをプロットするときに以前のすべてのバーが追加されなかったため、欠陥が含まれています。私のコードは、正しい(意図された)結果を生成するように編集されました。以下に、3番目のバーがのデータの上にのみ追加された場合の図を示しますp2
。
from matplotlib import pyplot as plt
from matplotlib import transforms
import numpy as np
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
p1 = [20, 35, 30, 35, 7]
p2 = [25, 32, 34, 20, 55]
p3 = [21, 361, 341, 205,151]
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, axs = plt.subplots(1,2)
# first of all, the base transformation of the data points is needed
base = axs[0].transData
rot = transforms.Affine2D().rotate_deg(-90)
axs[0].bar(labels, p1, width, label='p1',transform=rot + base)
axs[0].bar(labels, p2, width, bottom=p1, label='p2',transform=rot + base)
axs[0].bar(labels, p3, width, bottom=np.add(p1,p2), label='p3',transform=rot + base)
axs[1].barh(labels, p1, width, label='p1')
axs[1].barh(labels, p2, width, left=p1, label='p2')
axs[1].barh(labels, p3, width, left=np.add(p1,p2), label='p3')
for i in range(2):
axs[i].set_xlabel('Scores')
axs[i].set_title('Scores by group and gender')
axs[i].legend()
plt.show()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加