子图堆叠条形图

3

我有三个堆积条形图,已经正确显示,但我想将它们并排显示(而不是三个不同的图表(一个在另一个下面))。

当前显示三个图表的代码如下(其中axX_Group是包含我的数据的数据框)。

ax1_Group.plot(kind='barh', stacked=True, figsize=(6,15), title='Makes and Years (Pre 2000)')
ax2_Group.plot(kind='barh', stacked=True, figsize=(6,20), title='Makes and Years (2000-2009)')
ax3_Group.plot(kind='barh', stacked=True, figsize=(6,20), title='Makes and Years (2010+)')

我知道我需要使用subplot函数在一个图上绘制多个图形,但似乎无法弄清如何正确分配当前图形。

我的主要问题是,我找到的所有示例都使用subplot函数来分配图形的位置(我理解),但然后将图形作为X和Y的函数绘制,如下所示:

 figure = plt.figure()
 ax1 = figure.add_subplot(311)
 ax2 = figure.add_subplot(312)
 ax3 = figure.add_subplot(313)

 ax1.plot(x1,y1)
 ax2.plot(x2,y2)
 ax3.plot(x3,y3)

我需要弄清楚如何使用ax1.plot(X,Y)部分,以便我可以调用.plot(堆积条形图)。

    ax1_Group.plot(kind='barh', stacked=True, figsize=(6,15), title='Makes and Years (Pre 2000)')

所以我已经做到了这一步,但它没有起作用:

fig = plt.figure()
ax1_Group = fig.add_subplot(131)
ax2_Group = fig.add_subplot(132)
ax3_Group = fig.add_subplot(133)
ax1_Group.plot(ax1_Group.plot(kind='barh', stacked=True, figsize=(6,15), title='Breakdown of Makes and Years (Pre 2000)'))
ax2_Group.plot(ax2_Group.plot(kind='barh', stacked=True, figsize=(6,20), title='Breakdown of Makes and Years (2000-2009)'))
ax3_Group.plot(ax3_Group.plot(kind='barh', stacked=True, figsize=(6,20), title='Breakdown of Makes and Years (2010+)'))

我尝试了很多方法,但仍无法理解。非常感谢您的帮助。


添加关键字 subplots=True 是否能实现你想要的效果(如 http://pandas.pydata.org/pandas-docs/stable/visualization.html#subplots)?如果不能,有没有可能包含一个精确描述你想要的草图?另外,由于你提到了 dataframe,我假设你正在使用 Pandas?值得加上标签。最坏的情况是,你可以使用类似 x1, y1 = ax1_Group.values 的方法提取数据,并按照第二个示例进行绘制。 - Ed Smith
2个回答

1
您可以使用以下代码:

plt.figure()
ax1 = plt.subplot(131)
ax1_Group.plot(ax1_Group.plot(ax = ax1, kind='barh', stacked=True, figsize=(6,15), title='Breakdown of Makes and Years (Pre 2000)'))

ax2 = plt.subplot(132)
ax2_Group.plot(ax2_Group.plot(ax = ax2, kind='barh', stacked=True, figsize=(6,20), title='Breakdown of Makes and Years (2000-2009)'))

ax3 = plt.subplot(133)
ax3_Group.plot(ax3_Group.plot(ax = ax3, kind='barh', stacked=True, figsize=(6,20), title='Breakdown of Makes and Years (2010+)'))

请为原帖作者和未来的读者解释以下代码 - Parfait

0

我认为你问题的答案在这里,基本上说,

ax = ax1_Group.plot(kind='barh', 
                    stacked=True, 
                    figsize=(6,15), 
                    title='Makes and Years (Pre 2000)')
ax2_Group.plot(ax=ax, 
               kind='barh', 
               stacked=True, 
               title='Makes and Years (2000-2009)')
ax3_Group.plot(ax=ax, 
               kind='barh', 
               stacked=True, 
               title='Makes and Years (2010+)')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接