python - 我添加到图表中的补丁在 alpha=1 时不是不透明的。为什么?

标签 python matplotlib

我想在图形上添加一个矩形。通过我找到的所有文档,默认情况下矩形应该是不透明的,透明度由 alpha 参数控制。但是,即使 alpha = 1,我也无法让矩形显示为不透明。我是做错了什么,还是我需要了解有关图形与补丁交互方式的其他信息?

这是一个玩具示例:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from pylab import *

x = np.arange(10)
y = x
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)

rect = patches.Rectangle( ( 2,3 ), 2, 2, alpha = 1, ec = "gray", fc = "CornflowerBlue", visible = True)
ax.add_patch(rect)

plt.show()

最佳答案

来自documentation :

Within an axes, the order that the various lines, markers, text, collections, etc appear is determined by the matplotlib.artist.Artist.set_zorder() property. The default order is patches, lines, text, with collections of lines and collections of patches appearing at the same level as regular lines and patches, respectively.

因此默认情况下,补丁将绘制在线条下方。您可以通过指定矩形的 zorder 来更改顺序:

# note alpha is None and visible is True by default
rect = patches.Rectangle((2, 3), 2, 2, ec="gray", fc="CornflowerBlue", zorder=10)

您可以通过将 ax.plot(x, y) 更改为 lines = ax.plot(x, y) 和添加一行新代码:print lines[0].zorder。当我这样做时,该行的 zorder 为 2。因此,矩形将需要一个 zorder > 2 来遮盖该行。

关于python - 我添加到图表中的补丁在 alpha=1 时不是不透明的。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5390699/

相关文章:

python - 在 python 中解析 HTML - lxml 或 BeautifulSoup?其中哪一个更适合什么样的目的?

python - 使用 asyncio.wait 在任务异常后重试任务

python - operator[] 的 Swig 警告抑制

python - 如何将标签对齐到极坐标条形图的内边缘

python - 如何在通过将 txt 文件加载到 scipy 程序形成的图上的特定间隔内插入点?

python - 将多个 Y 轴与 Plotly 中的一个值对齐

python - 找不到记录器的处理程序

python - 使用 Flask 显示 matplotlib 图

python-3.x - Python/Pandas 按日期聚合

python - Matplotlib 查看后自动关闭绘图/图形