I would like to add a rectangle over a graph. Through all the documentation I\'ve found, the rectangle should be opaque by default, with transparency controlled by an alpha
From the 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.
So patches will be drawn below lines by default. You can change the order by specifying the zorder of the rectangle:
# note alpha is None and visible is True by default
rect = patches.Rectangle((2, 3), 2, 2, ec="gray", fc="CornflowerBlue", zorder=10)
You can check the zorder of the line on your plot by changing ax.plot(x, y)
to lines = ax.plot(x, y)
and add a new line of code: print lines[0].zorder
. When I did this, the zorder
for the line was 2. Therefore, the rectangle will need a zorder > 2
to obscure the line.
Your choice of facecolor (CornflowerBlue) has an appearance of being semi-opaque, but in reality the color you are seeing is correct for alpha = 1. Try a different color like 'blue' instead. Matplotlib does appear to be placing the rectangular patch below the line, but I don't think that's a transparency issue.