Matplotlib: Multiple legends for contour plot for multiple contour variables

有些话、适合烂在心里 提交于 2019-12-07 01:34:25

It would help if you showed your desired output from Matlab. For example, do you really want multiple legends? Or do you actually mean 1 legend with muliple items?

Since contour plots (can) have a different style for each level, its not obvious how you would want to plot that in a legend. But to get you started, you can access each individual line by examining the CS.collections array.

So for 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:

Perhaps something like plt.legend(CS2.legend_elements()[0], CS2.legend_elements()[1]), can also be useful for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!