如何在matplotlib的子图中添加图表

3
我有类似这样的图表。
fig = plt.figure()
desire_salary = (df[(df['inc'] <= int(salary_people))])
print desire_salary
# Create the pivot_table
result = desire_salary.pivot_table('city', 'cult', aggfunc='count')

# plot it in a separate step. this returns the matplotlib axes
ax = result.plot(kind='bar', alpha=0.75, rot=0, label="Presence / Absence of cultural centre")

ax.set_xlabel("Cultural centre")
ax.set_ylabel("Frequency")
ax.set_title('The relationship between the wage level and the presence of the cultural center')
plt.show()

我想将这个添加到subplot。我尝试了。
fig, ax = plt.subplots(2, 3)
...
ax = result.add_subplot()

但是它返回了`AttributeError: 'Series' object has no attribute 'add_subplot'`。我该如何检查这个错误?

你想要绘制6个图吗? - MaxU - stand with Ukraine
@MaxU,是的,我想把6个图合并成一个。我已经把它们分开了,但我想把它们合并在一起。 - Arseniy Krupenin
请查看我在答案中提供的链接 - 我做了几乎相同的事情(我使用的是seaborn.boxplot而不是你想要使用的barplot)。 - MaxU - stand with Ukraine
1
在提问时,请尽可能提供一个最小、完整和可验证的示例。对于_pandas_问题,请提供样本_input_和_output_数据集(CSV/dict/JSON/Python代码格式的5-7行文本),以便他人可以使用它来为您编写答案。这将有助于避免出现“你的代码对我不起作用”或“它不能处理我的数据”等情况。 - MaxU - stand with Ukraine
2个回答

7

matplotlib.pyplot 有“当前图形”和“当前坐标轴”的概念。所有绘图命令都会应用于当前坐标轴。

import matplotlib.pyplot as plt

fig, axarr = plt.subplots(2, 3)     # 6 axes, returned as a 2-d array

#1 The first subplot
plt.sca(axarr[0, 0])                # set the current axes instance to the top left
# plot your data
result.plot(kind='bar', alpha=0.75, rot=0, label="Presence / Absence of cultural centre")

#2 The second subplot
plt.sca(axarr[0, 1])                # set the current axes instance 
# plot your data

#3 The third subplot
plt.sca(axarr[0, 2])                # set the current axes instance 
# plot your data

演示:

在此输入图片描述

源代码如下:

import matplotlib.pyplot as plt
fig, axarr = plt.subplots(2, 3, sharex=True, sharey=True)     # 6 axes, returned as a 2-d array

for i in range(2):
    for j in range(3):
        plt.sca(axarr[i, j])                        # set the current axes instance 
        axarr[i, j].plot(i, j, 'ro', markersize=10) # plot 
        axarr[i, j].set_xlabel(str(tuple([i, j])))  # set x label
        axarr[i, j].get_xaxis().set_ticks([])       # hidden x axis text
        axarr[i, j].get_yaxis().set_ticks([])       # hidden y axis text

plt.show()

我在result中有一个图表,我想将它添加到包含6个图表的列表中。 - Arseniy Krupenin
它返回 AttributeError: 'NoneType' object has no attribute 'set_xlabel' - Arseniy Krupenin
当我使用 ax = 时,它不会将图形添加到图表中。 我只有标签,但是图形为空。 - Arseniy Krupenin
@ArseniyKrupenin,我刚刚添加了一个演示,请您检查一下。 - SparkAndShine
1
axarr[0, 1] 打印的图形不是子图,而是单独的图形。 - Arseniy Krupenin
显示剩余2条评论

2

result 是 pandas.Series 类型,不具备 add_subplot() 方法。

请使用 fig.add_subplot(...)

这里有一个使用 seaborn 模块的 示例

labels = df.columns.values
fig, axes = plt.subplots(nrows = 3, ncols = 4, gridspec_kw =  dict(hspace=0.3),figsize=(12,9), sharex = True, sharey=True)
targets = zip(labels, axes.flatten())
for i, (col,ax) in enumerate(targets):
    sns.boxplot(data=df, ax=ax, color='green', x=df.index.month, y=col)

您可以使用Pandas图表代替seaborn

我该如何将result中包含的图表添加到子图中? - Arseniy Krupenin
当我使用它时,它会返回AttributeError: 'NoneType'对象没有属性'set_xlabel' - Arseniy Krupenin
我应该使用 matplotlibpandas 来完成这个任务。 - Arseniy Krupenin
@ArseniyKrupenin,那就使用matplotlibpandas来完成吧 ;) - MaxU - stand with Ukraine
我不明白,如何将包含绘图的 ax 添加到其中一个子图中。 - Arseniy Krupenin
@ArseniyKrupenin,请阅读我的有关“最小化、完整化和可验证性示例”的评论,并相应地更新您的问题,这样SO社区就能为您编写一个可工作的示例。 - MaxU - stand with Ukraine

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