【问题标题】:How add plot to subplot matplotlib如何将情节添加到子情节 matplotlib
【发布时间】:2016-06-14 05:33:58
【问题描述】:

我有这样的情节

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:“系列”对象没有属性“add_subplot”。如何检查此错误?

【问题讨论】:

  • 您要绘制 6 个图吗?
  • @MaxU,是的,我想将 6 个情节加到一个情节上。我有单独的,但我想把它联合起来
  • 检查链接,我在我的回答中提供了 - 我在那里做的几乎一样(我使用的是 seaborn.boxplot 而不是 barplot,你想使用)
  • 在提问时尽量提供Minimal, Complete, and Verifiable example。如果有 pandas 问题,请提供示例 inputoutput 数据集(CSV/dict/JSON/Python 代码格式的 5-7 行 作为文本,因此可以在为您编写答案时使用它)。这将有助于避免以下情况your code isn't working for meit doesn't work with my data 等。

标签: python pandas matplotlib


【解决方案1】:

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 个情节的列表中
  • @ArseniyKrupenin,使用plt.sca 设置当前坐标区实例,然后绘制数据。请检查更新的答案。
  • 它返回AttributeError: 'NoneType' object has no attribute 'set_xlabel'
  • @ArseniyKrupenin,使用axarr[0, 0].set_xlabel
  • axarr[0, 1] 打印图形不是子图,它打印到单独的图形
【解决方案2】:

result是pandas.Series类型,没有add_subplot()方法。

改用fig.add_subplot(...)

这是一个example(使用 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 的情节添加到子情节中?
  • 当我使用它时它返回AttributeError: 'NoneType' object has no attribute 'set_xlabel'
  • 我应该使用 matplotlibpandas 来做到这一点
  • @ArseniyKrupenin,好吧,然后使用matplotlibpandas ;)
  • 我不明白,我怎样才能添加ax,其中包含一个情节到一个子情节
猜你喜欢
  • 2021-04-14
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-02
  • 2019-04-25
  • 1970-01-01
相关资源
最近更新 更多