<p>来自一位超级Python患者的简单等高线图示例:</p>
<pre><code>import numpy as np
from matplotlib.colors import LogNorm
from matplotlib import pyplot as plt
plt.interactive(True)
fig=plt.figure(1)
plt.clf()
# generate input data; you already have that
x1 = np.random.normal(0,10,100000)
y1 = np.random.normal(0,7,100000)/10.
x2 = np.random.normal(-15,7,100000)
y2 = np.random.normal(-10,10,100000)/10.
x=np.concatenate([x1,x2])
y=np.concatenate([y1,y2])
# calculate the 2D density of the data given
counts,xbins,ybins=np.histogram2d(x,y,bins=100,normed=LogNorm())
# make the contour plot
plt.contour(counts.transpose(),extent=[xbins.min(),xbins.max(),
ybins.min(),ybins.max()],linewidths=3,colors='black',
linestyles='solid')
plt.show()
</code></pre>
<p>产生一个很好的等高线图。</p>
<p>轮廓函数提供了许多奇特的调整,例如,让我们手动设置级别:</p>
<pre><code>plt.clf()
mylevels=[1.e-4, 1.e-3, 1.e-2]
plt.contour(counts.transpose(),mylevels,extent=[xbins.min(),xbins.max(),
ybins.min(),ybins.max()],linewidths=3,colors='black',
linestyles='solid')
plt.show()
</code></pre>
<p>生成此绘图:<a href="https://i.stack.imgur.com/sMch8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sMch8.png" alt="contour plot with adjusted levels"/></a></p>
<p>最后,在SM中,可以在线性和对数刻度上绘制等高线图,所以我花了一点时间在matplotlib中尝试如何实现这一点。下面是需要在对数刻度上绘制y点而x点仍在线性刻度上的示例:</p>
<pre><code>plt.clf()
# this is our new data which ought to be plotted on the log scale
ynew=10**y
# but the binning needs to be done in linear space
counts,xbins,ybins=np.histogram2d(x,y,bins=100,normed=LogNorm())
mylevels=[1.e-4,1.e-3,1.e-2]
# and the plotting needs to be done in the data (i.e., exponential) space
plt.contour(xbins[:-1],10**ybins[:-1],counts.transpose(),mylevels,
extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()],
linewidths=3,colors='black',linestyles='solid')
plt.yscale('log')
plt.show()
</code></pre>
<p>这会产生一个与线性曲线非常相似的曲线图,但是有一个很好的垂直对数轴,这就是我们想要的:<a href="https://i.stack.imgur.com/Vu5MB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vu5MB.png" alt="contour plot with log axis"/></a></p>