python - Matplotlib: Multiple legends for contour plot for multiple contour variables -


i need make multiple contours plots of several variables on same page. can matlab (see below matlab code). cannot matplotlib show multiple legends. appreciated.

python code:

import numpy np matplotlib import cm cm matplotlib import pyplot plt  delta = 0.25 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) x, y = np.meshgrid(x, y) z1 = x*np.exp(-x**2-y**2) z2 = y*np.exp(-x**2-y**2)  plt.figure() cs = plt.contour(x, y, z1, colors='k') plt.clabel(cs, inline=1, fontsize=10) cs = plt.contour(x, y, z2, colors='r') plt.clabel(cs, inline=1, fontsize=10) plt.legend(['case 1', 'case 2'])  plt.show() 

matlab code:

[x,y] = meshgrid(-2:.2:2,-2:.2:3); z1 = x.*exp(-x.^2-y.^2); z2 = y.*exp(-x.^2-y.^2);  [c,h] = contour(x,y,z1, 'color', 'k'); set(h,'showtext','on','textstep',get(h,'levelstep')*2); hold on  [c,h] = contour(x,y,z2, 'color', 'r'); set(h,'showtext','on','textstep',get(h,'levelstep')*2);  fn = {'case 1', 'case 2'};  legend(fn,'location','northwest'); 

it if showed desired output matlab. example, want multiple legends? or mean 1 legend muliple items?

since contour plots (can) have different style each level, not obvious how want plot in legend. started, can access each individual line examining cs.collections array.

so example:

delta = 0.25 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) x, y = np.meshgrid(x, y) z1 = x*np.exp(-x**2-y**2) z2 = y*np.exp(-x**2-y**2)  fig, ax = plt.subplots()  cs1 = ax.contour(x, y, z1, colors='k') ax.clabel(cs1, inline=1, fontsize=10)  cs2 = ax.contour(x, y, z2, colors='r') ax.clabel(cs2, inline=1, fontsize=10)  lines = [ cs1.collections[0], cs1.collections[-1], cs2.collections[0], cs2.collections[-1]] labels = ['cs1_neg','cs1_pos','cs2_neg','cs2_pos']  plt.legend(lines, labels) 

results in:

enter image description here

perhaps plt.legend(cs2.legend_elements()[0], cs2.legend_elements()[1]), can useful you.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -