我想在图形上添加一个矩形。通过我找到的所有文档,默认情况下矩形应该是不透明的,透明度由 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/