【问题标题】:how t add p value as legend into axes in matplotlib如何将 p 值作为图例添加到 matplotlib 中的轴中
【发布时间】:2017-04-11 16:53:07
【问题描述】:

我有以下代码:

def plot_diff_dist(ax, simulations, real_difference, bins=20):
    p=pvalue(simulations, real_difference)
    ax.hist(simulations, bins=bins )
    ax.axvline(real_difference, color='r', linewidth=5)

稍后 plot_diff_dist 将与在不同轴上绘制直方图的其他函数一起调用,我需要将 p 作为图例添加到它生成的每个直方图。所以我需要更改此函数以将 p 作为图例附加到每个直方图。

【问题讨论】:

    标签: python pandas matplotlib data-visualization p-value


    【解决方案1】:

    假设您有一些代码可以生成这样的直方图

    import matplotlib.pyplot as plt
    import numpy as np; np.random.seed(0)
    
    x = np.random.poisson(3, size=100)
    p = 5.
    plt.hist(x, bins=range(10))
    l = plt.axvline(p, color="crimson")
    

    传说

    您可以使用 legend 并提供您的 axvline 作为图例处理程序,以及作为图例文本的格式化值。

    plt.legend([l], ["p={}".format(p)], loc=1)
    

    文字

    您可以使用text 在图中放置文本。默认情况下,坐标是数据坐标,但您可以指定一个转换来切换,例如到轴坐标。

    plt.text(.96,.94,"p={}".format(p), bbox={'facecolor':'w','pad':5},
             ha="right", va="top", transform=plt.gca().transAxes )
    

    注释

    您可以使用annotate 在图中某处生成文本。与text 相比的优势在于,您可以 (a) 使用额外的箭头指向对象,以及 (b) 您可以用简单的字符串而不是变换来指定坐标系。

    plt.annotate("p={}".format(p), xy=(p, 15), xytext=(.96,.94), 
                xycoords="data", textcoords="axes fraction",
                bbox={'facecolor':'w','pad':5}, ha="right", va="top",
                arrowprops=dict(facecolor='black', shrink=0.05, width=1))
    

    锚定文本

    您可以使用来自 offsetbox 的AnchoredText

    from matplotlib.offsetbox import AnchoredText
    a = AnchoredText("d={}".format(d), loc=1, pad=0.4, borderpad=0.5)
    plt.gca().add_artist(a)
    

    【讨论】:

      【解决方案2】:

      您可以从 SO post. 尝试此解决方案

      from matplotlib.patches import Rectangle
      
      df = pd.DataFrame({'x':np.random.normal(2500,size=1000)})
      
      ax = df.plot.hist()
      ax.axvline(2501,color='r', linewidth=2)
      extra = Rectangle((0, 0), 100, 100, fc="w", fill=False, edgecolor='none', linewidth=0)
      ax.legend([extra],('p = 1.2',"x")).2',"x"))
      

      编辑:将 P 显示为变量:

      from matplotlib.patches import Rectangle
      df = pd.DataFrame({'x':np.random.normal(2500,size=1000)})
      ax = df.plot.hist()
      p=1.2
      ax.axvline(2501,color='r', linewidth=2)
      extra = Rectangle((0, 0), 100, 100, fc="w", fill=False, edgecolor='none', linewidth=0)
      ax.legend([extra],('p = {}'.format(p),"x"))
      

      【讨论】:

      • 谢谢,在我的问题中 p 是一个变量,我如何更改您的代码以接受变量作为 p?它不是字符串
      猜你喜欢
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      相关资源
      最近更新 更多