python - 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的有用评论,我现在已经以不同的方式解决了我的问题。我现在已经修改了我的问题,只针对底层问题。)
解决方案
推荐阅读
- php - 通过另外一个 MySQL/PHP 连接 2 个表
- c# - 无法将类型“Microsoft.Azure.Documents.Document”隐式转换为“System.Web.Http.IHttpActionResult”。
- scala - 如何在 DataFrame 中过滤数组的字段?
- bash - Bash:查找排除目录错误
- tfs - 在 TFS 中,如何使用自定义记录器执行测试运行?
- android - 在日志中获取firebase值但不知道如何在recylerview中添加到数组适配器中
- c# - 如何在我的表中使用逗号将小数点后的值更改为 2,532.00 到 2532。
- c# - 所有进程完成后触发 Azure Function
- android - FireBase Firestore 按 ID 列表检索多个文档
- authentication - VS 2017 ASP.NET Core Web 应用程序和个人用户帐户有效,但页面不存在