例一:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0) #设置随机数种子
mu,sigma=100,200 #均值和标准差
a=np.random.normal(mu,sigma,size=100)
plt.hist(a,20,density=1,histtype='stepfilled',facecolor='r',alpha=0.75)
plt.title('Histogram')
plt.show()
改变第二个参数bin的值:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0) #设置随机数种子
mu,sigma=100,200 #均值和标准差
a=np.random.normal(mu,sigma,size=100)
plt.hist(a,10,density=1,histtype='stepfilled',facecolor='r',alpha=0.75)
plt.title('Histogram')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0) #设置随机数种子
mu,sigma=100,200 #均值和标准差
a=np.random.normal(mu,sigma,size=100)
plt.hist(a,15,density=1,histtype='stepfilled',facecolor='r',alpha=0.75)
plt.title('Histogram')
plt.show()
-
官方文档说明
matplotlib.pyplot.hist
-
matplotlib.pyplot.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)
-
Plot a histogram.
Compute and draw the histogram of x. The return value is a tuple (n, bins, patches) or ([n0, n1, ...], bins, [patches0, patches1,...]) if the input contains multiple data.(计算并绘制x的直方图。如果输入包含多个数据,则返回值是元组(n,bins,patches)或([n0,n1,...],bin,[patches0,patches1,...])。)
Multiple data can be provided via x as a list of datasets of potentially different length ([x0, x1, ...]), or as a 2-D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form.(可以通过x提供多个数据作为可能不同长度([x0,x1,...])的数据集列表,或者作为2-D nararray,其中每列是数据集。请注意,ndarray表单相对于列表表单进行转置。)
Masked arrays are not supported at present.(目前并不支持 masked array)
-
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, optional
If an integer is given, bins + 1 bin edges are calculated and returned, consistent with numpy.histogram.(如果给出整数,则计算并返回bin+1 bin边缘,与numpy.histogram一致。)
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.(如果bins是一个序列,则给出bin边缘,包括第一个bin的左边缘和最后一个bin的右边缘。在这种情况下,bins未经修改地返回。)
All but the last (righthand-most) bin is half-open.(除最后一个(最右边)的之外,所有bin都是半开的。) In other words, if bins is:
[1, 2, 3, 4]
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.
Unequally spaced bins are supported if bins is a sequence.(如果容器是一个序列,则支持不等距的容器。)
With Numpy 1.11 or newer, you can alternatively provide a string describing a binning strategy, such as 'auto', 'sturges', 'fd', 'doane', 'scott', 'rice', 'sturges' or 'sqrt', see numpy.histogram.(使用Numpy 1.11或更新版本,您可以选择提供描述分箱策略的字符串,例如'auto','sturges','fd','doane','scott','rice','sturges'或'sqrt' ,见numpy.histogram。)
- The default is taken from rcParams["hist.bins"].(默认值取自rcParams [“hist.bins”]。)
-
range : tuple or None, optional
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.(箱子的下部和上部范围。忽略下限和上限异常值。如果未提供,则范围为(x.min(),x.max())。如果区间是序列,则范围无效。)
If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.(如果bin是指定的序列或范围,则自动缩放基于指定的bin范围而不是x的范围。)
Default is None
-
density : bool, optional
If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1. This is achieved by dividing the count by the number of observations times the bin width and not dividing by the total number of observations. If stacked is also True, the sum of the histograms is normalized to 1.(如果为True,则返回元组的第一个元素将是规范化以形成概率密度的计数,即直方图下的面积(或积分)将总和为1.这是通过将计数除以观察次数来实现的。箱宽度并没有除以观测总数。如果stacked也为True,则直方图的总和标准化为1。)
Default is None for both normed and density. If either is set, then that value will be used. If neither are set, then the args will be treated as False.(对于标准和密度,默认值均为“无”。如果设置了其中任何一个,则将使用该值。如果两者都未设置,则args将被视为False。)
If both density and normed are set an error is raised.(如果同时设置了密度和标准,则会引发错误。)
-
weights : (n, ) array_like or None, optional
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 normed or density is True, the weights are normalized, so that the integral of the density over the range remains 1.(一组重量,与x的形状相同。 x中的每个值仅将其相关权重贡献给bin计数(而不是1)。如果标准或密度为真,则权重被归一化,因此密度在整个范围内的积分保持为1。)
Default is None
-
cumulative : bool, optional
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 normed or density is also True then the histogram is normalized such that the last bin equals 1. If cumulative evaluates to less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if normed and/or density is also True, then the histogram is normalized such that the first bin equals 1.(如果为True,则计算直方图,其中每个bin给出该bin中的计数加上较小值的所有bin。最后一个bin给出了数据点的总数。如果标准或密度也为真,则将直方图归一化,使得最后一个仓等于1.如果累积评估小于0(例如,-1),则累积方向反转。在这种情况下,如果标准和/或密度也为真,则将直方图标准化,使得第一个bin等于1。)
Default is False
-
bottom : array_like, scalar, or None
Location of the bottom baseline of each bin. If a scalar, the base line for 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.(每个仓的底部基线的位置。如果是标量,则每个bin的基线移动相同的量。如果是一个数组,每个bin都是独立移动的,底部的长度必须与bin的数量相匹配。如果为None,则默认为0。)
Default is None
-
histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, optional
-
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.('bar'是传统的条形直方图。如果给出多个数据,则条并排排列。)
'barstacked' is a bar-type histogram where multiple data are stacked on top of each other.('barstacked'是一种条形直方图,其中多个数据堆叠在一起。)
'step' generates a lineplot that is by default unfilled.('step'生成一个默认未填充的线图。)
'stepfilled' generates a lineplot that is by default filled.('stepfilled'生成一个默认填充的线图。)
Default is 'bar'
-
-
align : {'left', 'mid', 'right'}, optional
-
Controls how the histogram is plotted.(控制直方图的绘制方式。)
- 'left': bars are centered on the left bin edges.('left':条形图位于左边框边缘的中心。)
- 'mid': bars are centered between the bin edges.('mid':条在bin边缘之间居中。)
- 'right': bars are centered on the right bin edges.('right':条形图位于右边框边缘的中心位置。)
Default is 'mid'
-
-
orientation : {'horizontal', 'vertical'}, optional
- If 'horizontal', barh will be used for bar-type histograms and the bottom kwarg will be the left edges.(如果是“水平”,则barh将用于条形直方图,而底部kwarg将用于左边缘。)
-
rwidth : scalar or None, optional
The relative width of the bars as a fraction of the bin width. If None, automatically compute the width.(条的相对宽度作为箱宽度的一部分。如果为None,则自动计算宽度。)
Ignored if histtype is 'step' or 'stepfilled'.(如果histtype是'step'或'stepfilled',则忽略。)
Default is None
-
log : bool, optional
If True, the histogram axis will be set to a log scale. If log is True and x is a 1D array, empty bins will be filtered out and only the non-empty (n, bins, patches) will be returned.(如果为True,则直方图轴将设置为对数刻度。如果log为True且x为1D数组,则将过滤掉空箱,并仅返回非空(n,bins,patches)。)
Default is False
-
color : color or array_like of colors or None, optional
Color spec or sequence of color specs, one per dataset. Default (None) uses the standard line color sequence.(颜色规格或颜色规格序列,每个数据集一个。默认(无)使用标准线颜色序列。)
Default is None
-
label : str or None, optional
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 the legend command will work as expected.(字符串或匹配多个数据集的字符串序列。条形图为每个数据集生成多个补丁,但只有第一个获取标签,因此图例命令将按预期工作。)
default is None
-
stacked : bool, optional
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'.(如果为True,则多个数据堆叠在一起。如果为假的多个数据并排排列,如果histtype为'bar',或者如果histtype为'step'则彼此重叠。)
Default is False
-
normed : bool, optional
- Deprecated; use the density keyword argument instead.(不推荐使用;请改用density关键字参数。)
Returns:
-
n : array or list of arrays
- The values of the histogram bins. See normed or 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.(直方图箱的值。有关可能的语义的描述,请参阅规范或密度和权重。如果输入x是一个数组,那么这是一个长度为nbins的数组。如果input是一个数组序列[data1,data2,..],那么这是一个数组列表,其中每个数组的直方图值的顺序相同。)
-
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 : list or list of lists
- Silent list of individual patches used to create the histogram or list of such list if multiple input datasets.(用于创建柱状图或此类列表(如果有多个输入数据集)的各个修补程序的静默列表。)