matplotlib.pyplot.hist#
matplotlib.pyplot. hist ( x , bins = None , range = None , density = False , weights = None , cumulative = False , bottom = None , histtype = ‘bar’ , align = ‘mid’ , orientation = ‘vertical’ , rwidth = None , log = False , color = None , label = None , stacked = False , * , data = None , ** kwargs ) [source] #
Compute and plot a histogram.
This method uses numpy.histogram to bin the data in x and count the number of values in each bin, then draws the distribution either as a BarContainer or Polygon . The bins, range, density, and weights parameters are forwarded to numpy.histogram .
If the data has already been binned and counted, use bar or stairs to plot the distribution:
counts, bins = np.histogram(x) plt.stairs(counts, bins)
Alternatively, plot pre-computed bins and counts using hist() by treating each bin as a single point with a weight equal to its count:
plt.hist(bins[:-1], bins, weights=counts)
The data input x can be a singular array, a list of datasets of potentially different lengths ([x0, x1, . ]), or a 2D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form. If the input is an array, then the return value is a tuple (n, bins, patches); if the input is a sequence of arrays, then the return value is a tuple ([n0, n1, . ], bins, [patches0, patches1, . ]).
Masked arrays are not supported.
Parameters : x (n,) array or sequence of (n,) arrays
Input values, this takes either a single array or a sequence of arrays which are not required to be of the same length.
bins int or sequence or str, default: rcParams[«hist.bins»] (default: 10 )
If bins is an integer, it defines the number of equal-width bins in the range.
If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open. In other words, if bins is:
then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3) . The last bin, however, is [3, 4] , which includes 4.
If bins is a string, it is one of the binning strategies supported by numpy.histogram_bin_edges : ‘auto’, ‘fd’, ‘doane’, ‘scott’, ‘stone’, ‘rice’, ‘sturges’, or ‘sqrt’.
range tuple or None, default: None
The lower and upper range of the bins. Lower and upper outliers are ignored. If not provided, range is (x.min(), x.max()) . Range has no effect if bins is a sequence.
If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.
density bool, default: False
If True , draw and return a probability density: each bin will display the bin’s raw count divided by the total number of counts and the bin width ( density = counts / (sum(counts) * np.diff(bins)) ), so that the area under the histogram integrates to 1 ( np.sum(density * np.diff(bins)) == 1 ).
If stacked is also True , the sum of the histograms is normalized to 1.
weights (n,) array-like or None, default: None
An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If density is True , the weights are normalized, so that the integral of the density over the range remains 1.
cumulative bool or -1, default: False
If True , then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints.
If density is also True then the histogram is normalized such that the last bin equals 1.
If cumulative is a number less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if density is also True , then the histogram is normalized such that the first bin equals 1.
bottom array-like, scalar, or None, default: None
Location of the bottom of each bin, i.e. bins are drawn from bottom to bottom + hist(x, bins) If a scalar, the bottom of each bin is shifted by the same amount. If an array, each bin is shifted independently and the length of bottom must match the number of bins. If None, defaults to 0.
The type of histogram to draw.
- ‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side.
- ‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other.
- ‘step’ generates a lineplot that is by default unfilled.
- ‘stepfilled’ generates a lineplot that is by default filled.
The horizontal alignment of the histogram bars.
- ‘left’: bars are centered on the left bin edges.
- ‘mid’: bars are centered between the bin edges.
- ‘right’: bars are centered on the right bin edges.
If ‘horizontal’, barh will be used for bar-type histograms and the bottom kwarg will be the left edges.
rwidth float or None, default: None
The relative width of the bars as a fraction of the bin width. If None , automatically compute the width.
Ignored if histtype is ‘step’ or ‘stepfilled’.
log bool, default: False
If True , the histogram axis will be set to a log scale.
color color or array-like of colors or None, default: None
Color or sequence of colors, one per dataset. Default ( None ) uses the standard line color sequence.
label str or None, default: None
String, or sequence of strings to match multiple datasets. Bar charts yield multiple patches per dataset, but only the first gets the label, so that legend will work as expected.
stacked bool, default: False
If True , multiple data are stacked on top of each other If False multiple data are arranged side by side if histtype is ‘bar’ or on top of each other if histtype is ‘step’
Returns : n array or list of arrays
The values of the histogram bins. See density and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence of arrays [data1, data2, . ] , then this is a list of arrays with the values of the histograms for each of the arrays in the same order. The dtype of the array n (or of its element arrays) will always be float even if no weighting or normalization is used.
bins array
The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.
patches BarContainer or list of a single Polygon or list of such objects
Container of individual artists used to create the histogram or list of such containers if there are multiple input datasets.
Other Parameters : data indexable object, optional
If given, the following parameters also accept a string s , which is interpreted as data[s] (unless this raises an exception):
2D histogram with rectangular bins
2D histogram with hexagonal bins
Plot a pre-computed histogram
Plot a pre-computed histogram
For large numbers of bins (>1000), plotting can be significantly accelerated by using stairs to plot a pre-computed histogram ( plt.stairs(*np.histogram(data)) ), or by setting histtype to ‘step’ or ‘stepfilled’ rather than ‘bar’ or ‘barstacked’.
pandas.DataFrame.hist#
DataFrame. hist ( column = None , by = None , grid = True , xlabelsize = None , xrot = None , ylabelsize = None , yrot = None , ax = None , sharex = False , sharey = False , figsize = None , layout = None , bins = 10 , backend = None , legend = False , ** kwargs ) [source] #
Make a histogram of the DataFrame’s columns.
A histogram is a representation of the distribution of data. This function calls matplotlib.pyplot.hist() , on each series in the DataFrame, resulting in one histogram per column.
Parameters data DataFrame
The pandas object holding the data.
column str or sequence, optional
If passed, will be used to limit data to a subset of columns.
by object, optional
If passed, then used to form histograms for separate groups.
grid bool, default True
Whether to show axis grid lines.
xlabelsize int, default None
If specified changes the x-axis label size.
xrot float, default None
Rotation of x axis labels. For example, a value of 90 displays the x labels rotated 90 degrees clockwise.
ylabelsize int, default None
If specified changes the y-axis label size.
yrot float, default None
Rotation of y axis labels. For example, a value of 90 displays the y labels rotated 90 degrees clockwise.
ax Matplotlib axes object, default None
The axes to plot the histogram on.
sharex bool, default True if ax is None else False
In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in. Note that passing in both an ax and sharex=True will alter all x axis labels for all subplots in a figure.
sharey bool, default False
In case subplots=True, share y axis and set some y axis labels to invisible.
figsize tuple, optional
The size in inches of the figure to create. Uses the value in matplotlib.rcParams by default.
layout tuple, optional
Tuple of (rows, columns) for the layout of the histograms.
bins int or sequence, default 10
Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified.
backend str, default None
Backend to use instead of the backend specified in the option plotting.backend . For instance, ‘matplotlib’. Alternatively, to specify the plotting.backend for the whole session, set pd.options.plotting.backend .
legend bool, default False
Whether to show the legend.
All other plotting keyword arguments to be passed to matplotlib.pyplot.hist() .
Returns matplotlib.AxesSubplot or numpy.ndarray of them
Plot a histogram using matplotlib.
This example draws a histogram based on the length and width of some animals, displayed in three bins
>>> df = pd.DataFrame( . 'length': [1.5, 0.5, 1.2, 0.9, 3], . 'width': [0.7, 0.2, 0.15, 0.2, 1.1] . >, index=['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3)
Метод Matplotlib.pyplot.hist() в Python — как построить гистограмму
matplotlib.pyplot.hist() — это библиотечная функция matplotlib в Python, которая создает гистограмму для заданной точки и строит график в качестве вывода.
Синтаксис
Параметры
Функция matplotlib.pyplot.hist() имеет один обязательный аргумент в качестве параметра:
- x: обязательный аргумент. Принимает массив в качестве значения. Этот массив состоит из точек.
- bins: этот аргумент принимает целое число или последовательность целых чисел в качестве значения. Этот аргумент является необязательным. По умолчанию ему присвоено значение 10.
- range: это необязательный аргумент. Если нижнее значение и верхнее значение указаны в аргументе диапазона, значения меньше нижнего значения и больше верхнего значения не будут отображаться на графике. По умолчанию предоставляется с минимальными значениями для нижнего и максимальным для верхнего значения.
- density: принимает логическое значение. Функция плотности вероятности возвращается, если это значение передается как True. По умолчанию это передается как False. data: объект с помеченными данными передается в качестве аргумента. Это необязательный аргумент.
- weights: необязательный аргумент. Может быть передан с массивом значений. Форма этого массива должна быть равна форме массива x.
- cumulative: необязательный аргумент. Принимает логическое значение в качестве значения аргумента. Если это передается как True, то значение каждой ячейки добавляется к значению предыдущей ячейки, а общая оценка сохраняется как значение ячейки.
- bottom: необязательный аргумент. Этот аргумент принимает значения в массиве и состоит из мест, где должен располагаться бункер.
- histtype: необязательный аргумент. Принимает строковые значения. Представляет тип гистограммы, которую необходимо построить. Значения могут быть столбчатыми, ступенчатыми или ступенчато заполненными.
- align: этот аргумент представляет выравнивание графика. У него есть такие значения, как левое, правое и среднее.
- orientation: это значение описывает ориентацию графика, имеет такие значения, как вертикальное и горизонтальное. По умолчанию он остается вертикальным.
- rwidth: это относительная ширина полос. По умолчанию сохраняется значение «None».
- log: в качестве аргумента принимает логическое значение. Если это True, то масштаб устанавливается в логарифмическом масштабе.
- color: цвета для графика передаются в этом аргументе. Цвета также можно передавать в массиве.
- label: эта строка аргумента в качестве входных данных. Если на этом этапе используется несколько наборов данных, первые данные получают метку, переданную в этом аргументе.
- stacked: в качестве значения этого аргумента принимает логическое значение. Если true, то несколько значений накладываются друг на друга.
Возвращаемое значение
Функция matplotlib.pyplot.hist() возвращает массив из n элементов. Затем он возвращает массив бинов. Наконец, он также возвращает массив patches.