【问题标题】:Subplot Stacked Bar Graphs子图堆积条形图
【发布时间】:2015-10-06 11:00:12
【问题描述】:

我有三个堆叠的条形图,我可以正确显示它们,但我想并排显示它们(而不是三个不同的图表(一个在另一个之下))。

分别显示三个图表的当前代码是(其中 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(stacked bar chart)

    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 是否符合您的要求(如pandas.pydata.org/pandas-docs/stable/…)?如果没有,您是否有可能包含您想要的草图?另外,正如您所说的数据框,我假设您正在使用 Pandas?值得作为标签添加。在最坏的情况下,您可以使用x1, y1 = ax1_Group.values 之类的内容提取数据并按照第二个示例进行绘图。

标签: matplotlib ipython bar-chart subplot stacked-chart


【解决方案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+)'))

【讨论】:

  • 请为OP和未来的读者解释以下代码
【解决方案2】:

我认为你的问题的答案基本上是here

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+)')

【讨论】:

    猜你喜欢
    • 2017-02-26
    • 2014-02-09
    • 2016-10-13
    • 2017-10-14
    • 2020-09-14
    • 1970-01-01
    • 2019-01-14
    • 2011-09-18
    相关资源
    最近更新 更多