Home > database >  Histogram from Pycharm
Histogram from Pycharm

Time:09-21

I'm trying to plot a histogram using Pycharm, but I get an error message: ValueError: bins must increase monotonically, when an array

import matplotlib.pyplot as plt

x = [19.5, 23.5, 31.5, 35.5, 39.5, 39.5, 43.5, 47.5]
y = [58.1, 23.3, 9.3, 4.7, 2.3, 0.0, 2.3, 0.0]

plt.hist(x, y)

plt.show()

CodePudding user response:

Your y values must increase monotonically. The second plt.hist argument is bin, in case of a sequence it defines the bin edges. For example,

x = [19.5, 23.5, 31.5, 35.5, 39.55, 39.6, 43.5, 47.5]
y = [20,30,40,50]
plt.hist(x, y)
plt.show()

will show three bars, showing you how many x numbers there are between 20 and 30, between 30 and 40, and between 40 and 50.

CodePudding user response:

I fully agree with AndrzejO. A convenient way to adjust the bins to make the histogram "nice" and highlight what you want is to generate the bins with numpy function linespace in the following way

import numpy as np
import matplotlib.pyplot as plt   

x = [19.5, 23.5, 31.5, 35.5, 39.55, 39.6, 43.5, 47.5]

plt.hist(x, bins=np.linspace(15,50, 10))
plt.show()

And with the last number in linespace that is 10 now you choose the number of bins you want, given the start bin at 15 and the end at 50.

  • Related