简体   繁体   English

Matplotlib:用于多个轮廓变量的轮廓图的多个图例

[英]Matplotlib: Multiple legends for contour plot for multiple contour variables

I need to make multiple contours plots of several variables on the same page. 我需要在同一页面上绘制多个变量的多个轮廓图。 I can do this with MATLAB (see below for MATLAB code). 我可以使用MATLAB进行此操作(有关MATLAB代码,请参见下文)。 I cannot get matplotlib to show multiple legends. 我无法让matplotlib显示多个图例。 Any help would be much appreciated. 任何帮助将非常感激。

Python code: Python代码:

import numpy as np
from matplotlib import cm as cm
from matplotlib import pyplot as 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: MATLAB代码:

[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 would help if you showed your desired output from Matlab. 如果您显示了Matlab所需的输出,这将有所帮助。 For example, do you really want multiple legends? 例如,您真的想要多个图例吗? Or do you actually mean 1 legend with muliple items? 或者,您实际上是指1个带有多个物品的图例吗?

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. 但是,为了开始,您可以通过检查CS.collections数组来访问每一行。

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. 也许像plt.legend(CS2.legend_elements()[0], CS2.legend_elements()[1])也可能对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM