Cy Bu Cy Bu - 2 years ago 221
Python Question

python 3.5 matplotlib contour plot legend

Trying to add a legend to my contour plot:

Here is the relevant code part i am having problem with:

CS = plt.contourf(gg, cc, zz_miss)
lbl = CS.cl_cvalues
plt.ylabel('C = 1 / lambda')
plt.legend((lbl), loc= 'upper right')

The legend labels of the legend are correct, but why are the pertineent colors all smeared and out of place?

Answer Source

It's putting the literal polygons of your contour plot as they were markers. It's a problem.

I advise you to create a manual replacement for the color legend. Here is the modification you need to make into your code (generated synthetic data):

import matplotlib.pyplot as plt

xx,yy = np.meshgrid(range(100),range(100))
gg = np.sqrt(xx*2+yy*2)
CS = plt.contourf(gg) #, cc, zz_miss)
proxy = [plt.Rectangle((0,0),1,1,fc = pc.get_facecolor()[0]) for pc in CS.collections]

plt.legend(proxy, [str(i) for i in range(8)])
plt.ylabel('C = 1 / lambda')

, the result is this:

Manually building the color legend of contourf

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download