python - 如何将绘图添加到子图 matplotlib

标签 python pandas matplotlib

我有这样的情节

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”对象没有属性“add_subplot”。我怎样才能检查这个错误?

最佳答案

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
<小时/>

演示:

enter image description here

源代码,

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()

关于python - 如何将绘图添加到子图 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37798645/

相关文章:

python - 创建一个函数来仅使用 numpy 计算二维矩阵中行向量的所有成对余弦相似度

python - 从(.csv 或 .txt)文件 Python 中删除各种字符

python - 如何创建一个具有一个索引键列和多个值列的字典

python - "#using-proxy-artist".format(orig_handle) 带饼图(来自 CSV 的数据) Matplotlib

python - Matplotlib 小部件中的多个图

python - 通过多个正则表达式对 DataFrame 列进行排序

python - 如何找到解决这个大值递归问题的数学方法呢?

python - 更改 Python 中的排序方式(与字母数字不同)

python - 脚本很好,但不会作为导入的模块运行

python - 自定义 matplotlib 图 : chess board like table with colored cells