0

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.

chessosapiens
  • 3,159
  • 10
  • 36
  • 58

2 Answers2

2

Suppose you have some code to produce a histogram like this

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

You can use a legend and provide your axvline as legend handler, as well as the formatted value as legend text.

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

enter image description here

text

You can use text to place a text in the figure. By default, the coordinates are data coordinates, but you can specify a transform to switch e.g. to axes coordinates.

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

enter image description here

annotate

You can use annotate to produce a text somewhere in the figure. The advantage compared to text is that you may (a) use an additional arrow to point to an object, and (b) that you may specify the coordinate system in terms of a simple string, instead of a transform.

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

enter image description here

AnchoredText

You can use an AnchoredText from offsetbox:

from matplotlib.offsetbox import AnchoredText
a = AnchoredText("d={}".format(d), loc=1, pad=0.4, borderpad=0.5)
plt.gca().add_artist(a)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

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

Community
  • 1
  • 1
Scott Boston
  • 147,308
  • 15
  • 139
  • 187