Python中的数密度轮廓

5 投票
4 回答
10639 浏览
提问于 2025-04-16 21:34

我正在尝试用Python重现这个图,但一直没成功:

这里输入图片描述

这是一个简单的数字密度等高线图,目前是在SuperMongo中制作的。我想用Python来替代它,但我得到的结果最接近的是:

这里输入图片描述

这是通过使用hexbin()函数得到的。请问我该如何让Python绘制的图看起来更像SuperMongo的那个呢?因为我的积分不够,不能直接上传图片,抱歉只能发链接。感谢你的帮助!

4 个回答

0

很遗憾,我无法查看你的图片。你是指像这个一样的东西吗?这是由MathGL做的,它是一个GPL许可证的绘图库,也有Python接口。你可以使用任意的数据数组作为输入(包括numpy的数据)。

2

你有没有看看 matplotlib的等高线图

6

这是一个来自另一位使用SuperMongo和Python的朋友的简单轮廓图示例:

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()

这个代码可以生成一个漂亮的轮廓图。

轮廓函数提供了很多有趣的调整选项,比如我们可以手动设置轮廓的级别:

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()

这样就能生成这个图:调整级别的轮廓图

最后,在SM中可以在线性和对数尺度上绘制轮廓图,所以我花了一些时间研究如何在matplotlib中做到这一点。下面是一个例子,其中y轴的点需要在对数尺度上绘制,而x轴的点仍然在线性尺度上:

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()

这个代码生成的图看起来和线性图非常相似,但有一个漂亮的垂直对数轴,这正是我们想要的效果:带有对数轴的轮廓图

撰写回答