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)     



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

However, when I uncomment these lines


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 .


1 Answer 1


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


Here is a sample:

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

enter image description here

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

Change this


to this

ax2 = plt.gca().twinx()

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.

  • $\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.