Skip to main content
 首页 » 编程设计

python之如何从许多单独的函数中绘制密度图

2024年12月31日14exmyth

假设函数很简单

def linear(x,n): 
    return n+x 

要尝试的参数范围是

import numpy as np 
parameters = np.random.normal(0, 1, 1000) 

绘制所有函数域的最佳方法是什么?

直接的是

import matplotlib.pyplot as plt 
for n in parameters: plt.plot(x,linear(x,n)) 

但是,当参数很多时(比如1e5),这是不可行的。我认为执行此操作的正确方法可能是沿着 2D 密度图或 2D 直方图的线条,但我不确定如何将它们应用于我的问题。

更复杂的是:上面尝试的每个模型都有自己的“优度拟合估计值”,例如 $\chi^2$。在获得将模型密度显示为颜色代码的图后,我想按 $\chi^2$ 值对其进行颜色编码。同样,我是在征求想法或经验。

非常欢迎任何建议!

请您参考如下方法:

对于您的示例,您可以根据参数 n 对数据进行装箱,并相应地重新装箱函数输出。我在下面提供了一个简单的例子。如果对 n 的函数依赖更复杂,那么(重新)binning 模式也可能变得更复杂。但这要视具体情况而定。如果参数值 n 的分布不均匀(如您的示例所示),则可能会考虑使用固定宽度的 bin 而不是运行平均值。但同样,这是一个品味问题。

from timeit import timeit 
import matplotlib 
from matplotlib.colors import Normalize 
import matplotlib.pyplot as plt 
import numpy as np 
 
def linear(x,n): 
    return n+x 
 
N = 1000 
x = np.linspace(0, 1, N) 
n = np.random.normal(0, 1, N) 
 
cmap = matplotlib.cm.get_cmap('plasma') 
norm = Normalize(vmin=n.min(), vmax=n.max()) 
 
def p3(): 
    n2, x2 = np.meshgrid(n, x) 
    f = linear(x2, n2) 
    # Now comes the "histogram" step. It involves taking the average over neighboring samples. 
    # Since data can be distributed non-linearly this might not be the desired behavior but 
    # similarly it is possible to specify an array of bins and use this for the binning. 
    sort = np.argsort(n) 
    n2 = n2[:, sort] 
    f = f[:, sort] 
    rebin = 10 
    n2 = n2.reshape(n2.shape[0], -1, rebin).mean(axis=-1)  # Average over 10 samples. 
    f = f.reshape(f.shape[0], -1, rebin).mean(axis=-1) 
    x2 = x2[:, ::rebin]  # No average required here, values are the same along second axis. 
    plt.figure() 
    plt.title('Using histogram method and pcolor') 
    plt.pcolor(x2, f, n2, cmap=cmap, norm=Normalize(vmin=n2.min(), vmax=n2.max())) 
 
p3() 
plt.show() 

我还检查了单独的线图和散点图。散点图减少了对 API 的调用次数,但尽管实际调用的时间相似,但我发现 Canvas 更新花费的时间明显更长(在后台线程中;例如,保存为 png 时类似)。

def p1(): 
    plt.figure() 
    plt.title('Plotting individual functions') 
    for nn in n: 
        plt.plot(x, linear(x, nn), '-', color=cmap(norm(nn))) 
 
def p2(): 
    n2, x2 = np.meshgrid(n, x) 
    f = linear(x2, n2) 
    plt.figure() 
    plt.title('Using scatter') 
    plt.scatter(x2.ravel(), f.ravel(), color=cmap(norm(n2.ravel()))) 
 
print('p1: ', timeit('p1()', setup='from __main__ import p1', number=1)) 
print('p2: ', timeit('p2()', setup='from __main__ import p2', number=1)) 
plt.show()