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
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 .
Use figtext()
:
plt.hist(var)
plt.figtext(1.0, 0.2, var.describe())
Use bbox_inches='tight'
to also save the text into a picture:
plt.savefig('fig1.png', bbox_inches='tight')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With