下面的代码:
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=
。通常,有两种绘制方法。显而易见的是使用barh
,不太明显的选择是转换现有的(垂直)bar
-plot(对此帖子的回答进行了解释):
编辑/注释:正如@ JohanC正确指出的那样,MVE代码包含一个缺陷,因为它在绘制第三个(绿色)条时并未添加所有先前的条。我的代码经过编辑以产生正确的(预期的)结果。如果仅在的数据上方添加第三条,则在其下方显示该图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] 删除。
我来说两句