Search code examples
pythonpandasmatplotlibdata-visualizationp-value

how t add p value as legend into axes in matplotlib


I have the following code :

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)

later plot_diff_dist will be called with other functions that plots histogram on different axes, i need to add p as a legend to every histogram it produces. so i need to change this function to attach p as a legend to every histogram.


Solution

  • You might try this solution from 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"))
    

    Edit: Show P as a variable:

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

    enter image description here