代码之家  ›  专栏  ›  技术社区  ›  Joel

使用python中的“小提琴绘图”样式绘图制作一组函数

  •  0
  • Joel  · 技术社区  · 7 年前

    假设我想把函数可视化 f[n] = e^{-(x-n)^2}/n 对于 n=1...10 注意,这些不是概率分布。

    (实际上不是我想要的情节,但足够接近)。

    我想用小提琴的情节来演示一下( https://matplotlib.org/gallery/statistics/violinplot.html )每个人在哪里 n 我有一条垂直线,我在垂直线的两侧绘制函数。

    但小提琴图似乎只用于显示数据样本的位置。所以所有的工具都需要我给它一个数据集。我想要绘制的数据不是那种类型的——它是一个实际已知的函数。

    [如果你想了解更多情况,这与我之前的一个问题有关- https://stats.stackexchange.com/questions/403359/visualizing-2d-data-when-one-dimension-is-discrete-and-the-other-continuous] .

    0 回复  |  直到 7 年前
        1
  •  1
  •   ImportanceOfBeingErnest    7 年前

    问题有点宽泛,所以这可能不是你真正想要的。但据我所知,你只需要在这个位置画出你的函数 f(x,n) 在不同的位置 n 还有 x 在垂直轴上。

    import numpy as np
    import matplotlib.pyplot as plt
    
    f = lambda x, n: np.exp(-(x-n)**2)/n
    
    x = np.linspace(-2,12,101)
    ns = np.arange(1,11)
    
    for n in ns:
        plt.fill_betweenx(x, -f(x,n)+n, f(x,n)+n, color="C0", alpha=0.5)
    
    plt.xlabel("n")
    plt.ylabel("x")
    plt.xticks(ns)        
    plt.show() 
    

    enter image description here

        2
  •  0
  •   Quang Hoang    7 年前

    IIUC,你想要这样的东西:

    df = pd.DataFrame({n: [np.exp(-(x-n)**2)/n  for x in np.arange(-1,1,0.1)] for n in range(1,11)})
    
    fig, ax = plt.subplots(1,1, figsize=(10,10))
    ax.violinplot(df.T)
    plt.show()
    

    输出:

    enter image description here