【问题标题】:Python - Plot 2 Plots togetherPython - 将 2 个绘图一起绘制
【发布时间】:2019-03-02 10:39:09
【问题描述】:

我有两个单独的图表,我想在同一个图上显示它们。

这是我的情节 1 代码

ax1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
ax1.plot.bar(rot =0)
plt.xlabel("Cat Names")
plt.ylabel("Measures")
plt.title("Title 1")
plt.show()

这是我的情节2代码,

ax2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()
ax1.plot.bar(rot =0)
plt.xlabel("Cat Names")
plt.ylabel("Measures")
plt.title("Title 2")
plt.show()

现在,这会一个接一个地显示在不同的图表(图像)中。我怎样才能在同一张图表中显示这一点 - 在同一张图表中显示在另一个下方(图片)。

请帮我解决这个问题。

这就是我正在尝试的,

fig, axes = plt.subplots(nrows=2)
df1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
ax1 = df1.plot.bar(rot =0)
df2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()
ax2 = df2.plot.bar(rot =0)
ax1.plt.bar(rot=0, ax=axes[0])
ax2.plt.bar(rot=0, ax=axes[1])
plt.show()

它对我不起作用。

【问题讨论】:

  • 到底是怎么回事?
  • 它说'AxesSubplot'对象没有属性'plt'
  • 哦,我明白了。我有一个错字。让我编辑我的帖子。

标签: python matplotlib


【解决方案1】:

您的变量命名有点不合常规。 ax 通常用于 matplotlib Axes 对象。这里有一个数据框。

无论如何,您应该设置一个具有两个轴的图形。 plt.subplots 是一种简单的方法。它将返回图形和包含您创建的所有轴的数组。您甚至可以使用sharexsharey 将轴设置为两者相等。在每个数据框的绘图调用中使用轴对象:

df1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
df2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()

fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)
df1.plot.bar(rot=0, ax=axes[0])
df2.plot.bar(rot=0, ax=axes[1])
axes[0].set_title('Title 0')
axes[1].set_title('Title 1')
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2013-02-10
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    相关资源
    最近更新 更多