corinna
corinna

Reputation: 649

matplotlib's axvspan converts marker colors in scatter plot but not in ordinary plot

I recently noticed the following phenomen in matplotlib (using v1.3.1 with Python3.3):

Minimal code example

import matplotlib.pyplot as plt

plt.plot(range(5),5*[3],'o', color="r", label="plt.plot")
plt.scatter(range(5),5*[2], color="r", label='plt.scatter')

plt.axvspan(1.5,4.5, color='yellow', alpha=0.5)

ax=plt.gca()
ax.legend(loc=6)

plt.savefig('adjusted_colors.png')

yields a plot with partially adjusted marker colors -- sorry for being not able to show the plot here -- namely markers plotted using pyplot's scatter-function in the area spanned by axvspan. In contrast, color of markers plotted via pyplot's plot-function is not converted.

Any ideas about how to avoid marker color's adjustment in case plt.scatter is used for plotting, respectively, how to turn it on in case of using plt.plot?

Upvotes: 2

Views: 1077

Answers (1)

Ajean
Ajean

Reputation: 5659

The reason the "colors are adjusted" is not because the color actually changes, but because the scatter result (which is a PathCollection object) is being viewed through a half-transparent colored rectangle that it is underneath. The same doesn't happen to the result of plot (which is a Line2D object) because it lies above the rectangle.

Matplotlib uses an attribute called zorder when it displays artists in a figure (most everything that lives in a matplotlib plot is an artist). The defaults set the plot's zorder to 2, whereas the rectangle and the scatter both have a zorder of 1, and the rectangle defaults to existing "higher" (not sure exactly why, but it is what it is). You can force the scatter points to lie above the rectangle by specifying the zorder keyword:

 plt.scatter(range(5),5*[2], color="r", label='plt.scatter', zorder=2)

Or, if you want the opposite, do the same to move the plot points below the rectangle:

plt.plot(range(5),5*[3],'o', color="r", label="plt.plot", zorder=0)

Upvotes: 1

Related Questions