Matplotlib:用于多个轮廓变量的轮廓图的多个图例 [英] Matplotlib: Multiple legends for contour plot for multiple contour variables
问题描述
我需要在同一页面上绘制多个变量的多个轮廓图.我可以使用MATLAB进行此操作(有关MATLAB代码,请参见下文).我无法让matplotlib显示多个图例.任何帮助将不胜感激.
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). I cannot get matplotlib to show multiple legends. Any help would be much appreciated.
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代码:
[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');
推荐答案
如果您显示了Matlab所需的输出,将会很有帮助.例如,您真的想要多个图例吗?或者,您实际上是说带有多个物品的1个图例吗?
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?
由于等高线图(可以)在每个级别上具有不同的样式,因此您不希望在图例中对其进行绘制就不那么明显了.但是,为了开始,您可以通过检查CS.collections数组来访问每一行.
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.
例如:
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)
结果:
也许像plt.legend(CS2.legend_elements()[0], CS2.legend_elements()[1])
之类的东西也可能对您有用.
Perhaps something like plt.legend(CS2.legend_elements()[0], CS2.legend_elements()[1])
, can also be useful for you.
这篇关于Matplotlib:用于多个轮廓变量的轮廓图的多个图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!