首页 > 解决方案 > plt.hist() 创建的补丁对象不会被绘制

问题描述

让我先说一下我对 matplotlib 的理解是有限的——我主要只是使用plot(),hist()show()来自 pyplot。我对补丁对象是什么有基本的了解,但是(显然)没有正确理解如何使用它们。

当我运行以下代码时(从标准在线示例复制):

import numpy as np
import matplotlib
from matplotlib.patches import Circle, Wedge, Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

resolution = 50  # the number of vertices
N = 3
x = np.random.rand(N)
y = np.random.rand(N)
radii = 0.1*np.random.rand(N)
patches = []
for x1, y1, r in zip(x, y, radii):
    circle = Circle((x1, y1), r)
    patches.append(circle)

x = np.random.rand(N)
y = np.random.rand(N)
radii = 0.1*np.random.rand(N)
theta1 = 360.0*np.random.rand(N)
theta2 = 360.0*np.random.rand(N)
for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2):
    wedge = Wedge((x1, y1), r, t1, t2)
    patches.append(wedge)

# Some limiting conditions on Wedge
patches += [
    Wedge((.3, .7), .1, 0, 360),             # Full circle
    Wedge((.7, .8), .2, 0, 360, width=0.05),  # Full ring
    Wedge((.8, .3), .2, 0, 45),              # Full sector
    Wedge((.8, .3), .2, 45, 90, width=0.10),  # Ring sector
]

for i in range(N):
    polygon = Polygon(np.random.rand(N, 2), True)
    #patches.append(polygon)

colors = 100*np.random.rand(len(patches))
p = PatchCollection(patches, alpha=0.4)
p.set_array(np.array(colors))
ax.add_collection(p)
fig.colorbar(p, ax=ax)

plt.show()

它按预期运行,创建并显示各种随机补丁:生成随机补丁的代码示例输出。

我也知道,当我plt.hist()用来创建和显示直方图时,我可以将创建的补丁对象保存到列表中,如下所示:

import numpy as np
import matplotlib.pyplot as plt

data = [np.random.normal(1) for i in range(10000)]
num_bins = 50

n, bins, patches = plt.hist(data, num_bins)
plt.show()

这使我可以绘制直方图。但是如果我不想直接绘制它,而是想patches从第一个代码块将这个列表传递给绘图功能(例如,在使用了诸如set_height()进行一些更改之类的函数之后),我只会得到一个空图.

print(str(len(patches)))通过使用or之类的东西print(str(patches[10].get_height())),我可以确认补丁对象确实已创建,并且似乎具有所有适当的属性。那么,为什么我在尝试绘制它们时看不到任何东西,使用我知道适用于不同补丁列表的代码?

(这个问题最初是关于我想对这些补丁对象做的一件非常具体的事情——感谢ImportanceOfBeingErnest的有用评论,我现在已经以不同的方式解决了我的问题。我现在已经修改了我的问题,只针对底层问题。)

标签: pythonmatplotlibhistogram

解决方案


推荐阅读