pyplot直方图绘制(北理大嵩天MOOC课程笔记)

例一:

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.(用于创建柱状图或此类列表(如果有多个输入数据集)的各个修补程序的静默列表。)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,080评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,422评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,630评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,554评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,662评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,856评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,014评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,752评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,212评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,541评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,687评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,347评论 4 331
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,973评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,777评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,006评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,406评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,576评论 2 349

推荐阅读更多精彩内容