如何将 p 值作为图例添加到 matplotlib 中的轴中

how t add p value as legend into axes in matplotlib

我有以下代码:

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 作为图例附加到每个直方图。

您可以从 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"))

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

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

AnchoredText

您可以使用来自 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)