Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add some statistics to the plot in python

So im plotting a histogram with using matplotlib.pyplot

plt.hist(var)

I'm curious if I can attach some statistics to the right of the graph created by

var.describe()

for which it is a series.

the result is like this

hist

like image 511
xTernal Avatar asked Dec 12 '15 19:12

xTernal


People also ask

How do you plot specific columns in Python?

To plot a specific column, use the selection method of the subset data tutorial in combination with the plot() method. Hence, the plot() method works on both Series and DataFrame .


2 Answers

Use figtext():

plt.hist(var)
plt.figtext(1.0, 0.2, var.describe())

enter image description here

Use bbox_inches='tight' to also save the text into a picture:

plt.savefig('fig1.png', bbox_inches='tight')
like image 139
Mike Müller Avatar answered Oct 11 '22 23:10

Mike Müller


As shown in the solution above, the text formatting messes up a little bit. To fix this, I added a workaround, where we divide the description into two figures, which are then aligned.

The helper:

def describe_helper(series):
    splits = str(series.describe()).split()
    keys, values = "", ""
    for i in range(0, len(splits), 2):
        keys += "{:8}\n".format(splits[i])
        values += "{:>8}\n".format(splits[i+1])
    return keys, values

Now plot the graph:

demo = np.random.uniform(0,10,100)
plt.hist(demo, bins=10)
plt.figtext(.95, .49, describe_helper(pd.Series(demo))[0], {'multialignment':'left'})
plt.figtext(1.05, .49, describe_helper(pd.Series(demo))[1], {'multialignment':'right'})
plt.show()

If you also want to save the figtext when saving the image refer to answer 1

like image 44
JohnDoe Avatar answered Oct 11 '22 23:10

JohnDoe