Reputation: 1437
Trying to add a legend to my contour plot:
Here is the relevant code part i am having problem with:
plt.figure()
CS = plt.contourf(gg, cc, zz_miss)
CS.clabel()
lbl = CS.cl_cvalues
plt.xlabel('gamma')
plt.ylabel('C = 1 / lambda')
plt.legend((lbl), loc= 'upper right')
plt.show()
The legend labels of the legend are correct, but why are the pertineent colors all smeared and out of place?
Upvotes: 2
Views: 5551
Reputation: 1437
Thanks.
Also, found a slightly easier one: see result
CS = plt.contourf(gg, cc, zz_miss, alpha= 1)
nm, lbl = CS.legend_elements()
plt.legend(nm, lbl, title= 'MyTitle', fontsize= 8)
plt.xlabel('gamma')
plt.ylabel('C = 1 / lambda')
here is the result:
Upvotes: 4
Reputation: 13465
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
plt.figure()
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.xlabel('gamma')
plt.ylabel('C = 1 / lambda')
plt.show()
, the result is this:
Upvotes: 3