0
$\begingroup$

I have a small piece of code that print values gotten from a csv file into a histogram. This is all done using matplotlib library

dev_x= X     #this is where my integers are stored 
plt.hist(dev_x, bins=7)     

#var=np.var(dev_x)
#print(np.mean(dev_x))
#plt.axhline(var)

plt.xlabel('Values')
plt.ylabel('Quatity')
plt.title('Graph')

When the following lines are commented, I get the result enter image description here

However, when I uncomment these lines

var=np.var(dev_x)
print(np.mean(dev_x))
plt.axhline(var)

I get only this graph

enter image description here

The code aims to show the histagram of the data and then the mean and the variance horizontal .

$\endgroup$

1 Answer 1

1
$\begingroup$

The problem is that you are plotting two things of different scale on the same axis. Your variance appears to be 6*10^9 while your counts are in the hundreds. Therefore the bins are so small you can no longer see them.

You should probably use an vline instead of an hline to get the line on the x-axis

plt.axvline(var)

Here is a sample:

import seaborn as sns
import matplotlib.pyplot as plt
diamonds = sns.load_dataset('diamonds')
plt.hist(diamonds['carat'])
plt.axvline(np.var(diamonds['carat']), color='red')
plt.show()

enter image description here


If you really want to do this on the y axis you should use a second y axis.

Change this

plt.axhline(var)

to this

ax2 = plt.gca().twinx()
ax2.axhline(var)

Check the documentation for more info

Otherwise consider using multiple plots since it might be really confusing to have a line with a different scale on a histogram.

$\endgroup$
4
  • $\begingroup$ if I use this plt.axvline(var) I only get the line and not the plotting of the other values $\endgroup$
    – E199504
    Feb 3, 2020 at 10:31
  • $\begingroup$ I added a sample to the post. It appears to me that your variance value is really large (not surprising since it is the square of the std). Therefore the line is so far right that the you can no longer see the bins of the histogram. Consider using the standard deviation (np.std) instead of the variance: en.wikipedia.org/wiki/Standard_deviation $\endgroup$
    – rhedak
    Feb 3, 2020 at 23:25
  • $\begingroup$ what is the difference between variance and standard deviation (np.std) and why should I use the second of one ? $\endgroup$
    – E199504
    Feb 4, 2020 at 23:22
  • $\begingroup$ The standard deviation is the root of the variance. It is usually used when analyzing data over the variance since the scale of the variance is usually quite different from the data's distribution (as in your example). read the wikipedia article linked above for more information $\endgroup$
    – rhedak
    Feb 4, 2020 at 23:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.