我想使用 matplotlib 绘制一些矩形轮廓。问题是,我需要大量的矩形,所以绘制矩形的“正常”方式非常慢。我使用 How to speed up plot... 解决了这个问题。问题是,我无法再使用 fill=None
绘制矩形的边缘。或edgecolor=...
和facecolor=None
.
查看我的代码的玩具示例:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
def plot_rectangle_from_area(area, color):
"""Plot a rectangle for a given area with color"""
return Rectangle(xy=(area["min_x"], area["min_y"]), width=area["max_x"] - area["min_x"],
height=area["max_y"] - area["min_y"],
fill=None) # linewidth=0, edgecolor=color, facecolor=None, zorder=100, alpha=0,
sample_areas = [{"min_x": -1, "max_x": 0.4, "min_y": 0.7, "max_y": 1},
{"min_x": 0.5, "max_x": 1, "min_y": 0.1, "max_y": 0.5}]
rectangles = []
fig, ax = plt.subplots()
# ... print some contour via meshgrid
if sample_areas:
for area_i in sample_areas:
rectangles.append(plot_rectangle_from_area(area_i, color="r"))
# ... some more cases
# Append the rectangles all at once instead of on their own, see:
# https://stackoverflow.com/questions/33905305/how-to-speed-up-the-plot-of-a-large-number-of-rectangles-with-matplotlib
ax.add_collection(PatchCollection(rectangles))
# ... legend, save, grid, ...
plt.show()
首先,我为所有矩形创建一个数组,附加到它并使用 PatchCollection 来绘制它 1 。下面的示例执行完全相同的操作,只是没有 PatchCollection 并且工作正常。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
def plot_rectangle_from_area(area, color):
"""Plot a rectangle from given area"""
return Rectangle(xy=(area["min_x"], area["min_y"]), width=area["max_x"] - area["min_x"],
height=area["max_y"] - area["min_y"],
fill=None) # linewidth=0, edgecolor=color, facecolor=None, zorder=100, alpha=0,
sample_areas = [{"min_x": -1, "max_x": 0.4, "min_y": 0.7, "max_y": 1},
{"min_x": 0.5, "max_x": 1, "min_y": 0.1, "max_y": 0.5}]
fig, ax = plt.subplots()
if sample_areas:
for area_i in sample_areas:
ax.add_patch(plot_rectangle_from_area(area_i, color="r"))
plt.show()
这是我用这两个代码创建的一些图。左边是使用慢速方法得到的期望结果,右边是我使用 PatchCollection 得到的结果:
我尝试了填充、边缘颜色、面部颜色的多种组合,甚至还尝试了 here 中 zorder 的建议。 .
是否可以使用“快速”方式创建矩形并仅显示边框?
最佳答案
是的 - 查看 PatchCollection 的文档,有一个名为 match_original
的参数,当 True
时,该参数将设置面片的属性以匹配原始矩形的属性。
所以只需更改
ax.add_collection(PatchCollection(rectangles))
到
ax.add_collection(PatchCollection(rectangles, match_original=True))
关于python - Matplotlib 绘制数百个矩形轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58833030/