Matplotlib.pyplot 常用方法(二)

来源:互联网 发布:session php注册示例 编辑:程序博客网 时间:2024/06/05 03:13

hist()——直方图

n, bins, patches = hist (x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)

参数的意义:

  • x : (n,) array or sequence of (n,) arrays,表示:就是输入的数据啦,可以为一个序列数,也可以多组;

  • bins : integer or array_like, 表示:控制分的块数,要分的块数为bins,默认为10;

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

If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.

Default is None

  • normed : boolean, optional, 意义就是说,返回的第一个n(后面解释它的意义)吧,把它们正则化它,让bins的值 的和为1,这样差不多相当于概率分布似的了;

If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., n/(len(x)`dbin), i.e., the integral of the histogram will sum to 1. If stacked is also True, the sum of the histograms is normalized to 1.

Default is False

  • 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 is True, the weights are normalized, so that the integral of the density over the range remains 1.

Default is None

  • cumulative : boolean, 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 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 is also True, then the histogram is normalized such that the first bin equals 1.

Default is Fal

  • bottom : array_like, scalar, or None,下面的每个bin的基线,表示bin的值都从这个基线上往上加;

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 t

Default is None

  • histtype : {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}, optional, 表明了画出的bar的形状;

The type of histogram to draw.

‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are aranged 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.

Default is ‘bar’

  • align : {‘left’, ‘mid’, ‘right’}, optional 它决定了你画的bar是以什么为中心的。你看看哈,画图时,每个bin的边界已经分好了,align就决定了你画每一个bar时,要依左边界为中心呢,还是右边界,还是中间呢?当然默认为中间了,这样才准确的

Controls how the histogram is plotted.

‘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.
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.

  • rwidth : scalar or None, optional ,控制你要画的bar 的宽度哦;

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’.

Default is None

  • log : boolean, 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.

Default is False

  • color : color or array_like of colors or None, optional 表示bar的颜色;

Color spec or sequence of color specs, one per dataset. Default (None) uses the standard line color sequence.

Default is None

  • label : string or None, optional 这个不错,可以给图上画的加个标签,要加上这么一句哦;plt.legend() 作用为显示出来;

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 : boolean, optional 作用就是当多个输入的时候,要不要把它们luo 起来;

If True, multiple data are stacked on top of each other If False multiple data are aranged side by side if histtype is ‘bar’ or on top of each other if histtype is ‘step’

Default is False


输出参数:

  • n : array or list of arrays 每一个 bin的值;

The values of the histogram bins. See normed 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 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.

  • bins : array :返回bin的边界值,长度为bin的数目 + 1.

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.

# 柱状图import numpy as npimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt# example datamu = 100  # mean of distributionsigma = 15  # standard deviation of distributionx = mu + sigma * np.random.randn(10000)                 # np.random.randn(n)函数的作用为生成n个标准的正态分布的数;num_bins = 50# the histogram of the datan, bins, patches = plt.hist(x, bins = num_bins, normed=1, color='b', alpha=0.5)# add a 'best fit' liney = mlab.normpdf(bins, mu, sigma) # normpdf(x,mu,sigma):返回参数为μ和σ的正态分布密度函数在x处的值                                                            # (其中参数mu是μ,参数sigma是σ)plt.plot(bins, y, 'r--')plt.xlabel('Smarts')plt.ylabel('Probability')plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')# Tweak spacing to prevent clipping of ylabelplt.subplots_adjust(left=0.15)   # 把画的图从左边0.15(整个为1)处开始, 要不把y轴的label显示不出来 ,可以设为0试试.                                                 # 另外,其实不加也没事;plt.show()

运行结果:
这里写图片描述

pie()——饼图

函数pie()如下所示,它画出数组x表示的饼形图,每一份的比例为x/sum(x);如果sum(x)的和小于1,那么,直接用x的值当作比例哦,不会去标准化它。默认的块是逆时针来的,从x轴开始。

pie (x, explode=None, labels=None,colors=(‘b’, ‘g’, ‘r’, ‘c’, ‘m’, ‘y’, ‘k’, ‘w’),autopct=None, pctdistance=0.6, shadow=False,labeldistance=1.1, startangle=None, radius=None,counterclock=True, wedgeprops=None, textprops=None,center = (0, 0), frame = False, hold = None, data = None )

参数的意义:

  • explode : [ None | len(x) sequence ] 为None或着长度为len(x)的数的序列,表明每一块中心与圆心的位移,基本都是小数哦,意思就是让每一块分开一定距离,这样好看;

If not None, is a len(x) array which specifies the fraction of the radius with which to offset each wedge.

  • colors : [ None | color sequence ] 表示每一块的颜色;

A sequence of matplotlib color args through which the pie chart will cycle.

  • labels : [ None | len(x) sequence of strings ] 表示每一块的标签;

A sequence of strings providing the labels for each wedge

  • autopct : [ None | format string | format function ] ,用于标记它们的值(大小为x/sum(x)*100);,可以为一个format string,或function。如format string, %d(整数),%1.1f(保留一位的小数)等

If not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt%pct. If it is a function, it will be called.

  • pctdistance : scalar ,用于控制上面的那个autopct生成的显示的值 的位置,默认离每一块的中心0.6的比例处;

The ratio between the center of each pie slice and the start of the text generated by autopct. Ignored if autopct is None; default is 0.6.

  • labeldistance : scalar 控制那个label的位置,它代表了径向的相对距离哦;

The radial distance at which the pie labels are drawn

  • shadow : [ False | True ] 要不要画个阴影呢?它决定!!!

Draw a shadow beneath the pie.

  • startangle : [ None | Offset angle ] 开始的位置偏移的角度;

If not None, rotates the start of the pie chart by angle degrees counterclockwise from the x-axis.

  • radius : [ None | scalar ] The radius of the pie, if radius is None it will be set to 1. 直径的大小;

  • counterclock : [ False | True ] 逆时针还是顺时针呢;

Specify fractions direction, clockwise or counterclockwise.

  • wedgeprops : [ None | dict of key value pairs ] 用字典属性指定了块的一些属性;

Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = { ‘linewidth’ : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default clip_on=False.

  • textprops : [ None | dict of key value pairs ] 用字典属性指定了text的属性;

Dict of arguments to pass to the text objects.

  • center : [ (0,0) | sequence of 2 scalars ] Center position of the chart. 它的中心位置啦;

  • frame : [ False | True ] 它决定了你要不要显示坐标轴哦;

Plot axes frame with the chart.


返回值:

If autopct is None, return the tuple (patches, texts):
patches is a sequence of matplotlib.patches.Wedge instances
texts is a list of the label matplotlib.text.Text instances.
If autopct is not None, return the tuple (patches, texts, autotexts), where patches and texts are as above, and autotexts is a list of Text instances for the numeric labels.

import matplotlib.pyplot as plt# The slices will be ordered and plotted counter-clockwise.labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'      sizes = [15, 30, 45, 10]colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']   #这个颜色有点牛逼;explode = (0, 0.1, 0, 0)                         # only "explode" the 2nd slice (i.e. 'Hogs')plt.pie(sizes, explode=explode, labels=labels, colors=colors,        autopct='%1.1f%%', shadow=True, startangle=90)# Set aspect ratio to be equal so that pie is drawn as a circle.plt.axis('equal')                               # 让坐标的横轴与纵轴相等,这样圆才是圆的哦,目的好看啊.plt.show()

运行结果:
这里写图片描述

原创粉丝点击