matplotlib的demo演示讲解,fillbetween方法绘画直方图亢保星
#!/usr/bin/env python #-*- coding:utf-8 -*- import itertools from functools import partial import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as mticker from cycler import cycler # set up histogram function to fixed bins """ 阅读一: edges:边界,边缘的意思; 这里是20个边界,范围是[-3,3],这个edges是一个等差数列。 """ edges = np.linspace(-3, 3, 20, endpoint=True) """ partial 包装了np.histogram函数,给np.histogram规定一个默认参数bins,方便以后调用 np.histogram:这方法的作用是: 计算一个数据集的分布。 比如:有1,2,3,4,5,6这个数据集,经过np.histogram分析后,在1到3范围内有3个数字;在4到6范围内有3个数字。 这个分析结果是基于bins=[1,3,6]的。 """ hist_func = partial(np.histogram, bins=edges) # set up style cycles """ cycker: 是周期的意思 cycler:是一个属性组合器,一个属性下面有多个值,可以有多个属性 cycler:是一个迭代器,可以用迭代器的方式进行访问。 cycle:cycle和cycle之间可以进行加法运算,组装成多个属性,每个属性下面有多个值。 它的数据结构如下: 颜色:蓝,黄,绿,红 标签:set 0 ,set 1,set 2,set 3 形状:形状0,形状1,形状2,形状3 cycle: 它的访问,既可以按标签访问,这里的标签指的是(颜色,标签,形状),也可以 这样访问(蓝,set0,形状0),(黄,标签1,形状1);一组一组的的访问 颜色属性,这个color_cycle里面有四种颜色,这里的facecolor是前景色的意思, 我们从plt.rcParams["axes.prop_cycle"][:4]里面,拿四种前景色。 [:4] 的意思是从0开始,取四个元素。 我们的结果图里面有四种颜色,从下往上,依次是蓝色,黄色,绿色,红色 """ color_cycle = cycler(facecolor=plt.rcParams["axes.prop_cycle"][:4]) """ 依然使用cycler这个数据结构,我们定义了四个标签,分别是set 0,set 1,set 2,set 3 """ label_cycle = cycler(label=["set {n}".format(n=n) for n in range(4)]) """ 形状周期(cycler):斜线,星装,方格,竖线 """ hatch_cycle = cycler(hatch=["/", "*", "+", "|"]) test_v = color_cycle+label_cycle+hatch_cycle for v in test_v: print(v) # Fixing random state for reproducibility """ 设定随机种子,可以使程序每次运行,都产生同样的随机数。 """ np.random.seed(19680801) """ 应为我们有四个数据集的分布图,所以我们要做四组数据,放在stack_data中 stack_data:是堆_数据的意思,我们这有四堆数据 """ stack_data = np.random.randn(4, 12250) print(stack_data.shape) """ 让四堆数据和四个label进行一一对应。 这里的知识点有: (c["label"] for c in label_cycle):从label_cycle中获取lable周期对应的数据,获得的结果 是一个元组("set 0","set 1","set 2","set 3") 然后zip(元组,stack_data),形成一个zip对象,zip对象是一个迭代器,可以被迭代访问的。for...in 的形势进行访问。 dict(zip),这个可以把一个zip对象转为字典 """ dict_data = dict(zip((c["label"] for c in label_cycle), stack_data)) for k,v in dict_data.items(): print(k) print(v.shape) """ 我们要做一个一行两列的图,figsize,宽950,高450,tight_layout:为True是紧密布局。 """ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5), tight_layout=True) """ 调用我们的方法,先在第一个坐标系画图。我们传了四个参数,ax1坐标系;stack_data:要被我们统计分析的数据 color_cycle+label_cycle+hatch_cycle,三个cycler相加,形成一个大的周期,这个大的周期数据结构如下: 颜色:蓝,黄,绿,红 标签:set 0 ,set 1,set 2,set 3 形状:形状0,形状1,形状2,形状3 hist_func: 从numpy来的统计函数,对stack_data中的数据进行统计分析 """ arts = stack_hist(ax1, stack_data, color_cycle + label_cycle + hatch_cycle, hist_func=hist_func) arts = stack_hist(ax2, stack_data, color_cycle, hist_func=hist_func, plot_kwargs=dict(edgecolor="w", orientation="h")) """ 设置x轴和y轴的标签。 """ ax1.set_ylabel("counts") ax1.set_xlabel("x") ax2.set_xlabel("counts") ax2.set_ylabel("x") """ 让这个图,绘画完成 """ plt.show() """ 阅读二: ax:直角坐标系 stacked_data:被分析的数据 sty_cycle:数据类型为cycler,是四种不同分布的形状,颜色,标签的设置。 hist_func:数据分析函数,分析每个阶段,有多少个数据。 """ def stack_hist(ax, stacked_data, sty_cycle, bottoms=None, hist_func=None, labels=None, plot_func=None, plot_kwargs=None): """ Parameters ---------- ax : axes.Axes The axes to add artists too stacked_data : array or Mapping A (M, N) shaped array. The first dimension will be iterated over to compute histograms row-wise sty_cycle : Cycler or operable of dict Style to apply to each set bottoms : array, default: 0 The initial positions of the bottoms. hist_func : callable, optional Must have signature `bin_vals, bin_edges = f(data)`. `bin_edges` expected to be one longer than `bin_vals` labels : list of str, optional The label for each set. If not given and stacked data is an array defaults to "default set {n}" If *stacked_data* is a mapping, and *labels* is None, default to the keys. If *stacked_data* is a mapping and *labels* is given then only the columns listed will be plotted. plot_func : callable, optional Function to call to draw the histogram must have signature: ret = plot_func(ax, edges, top, bottoms=bottoms, label=label, **kwargs) plot_kwargs : dict, optional Any extra keyword arguments to pass through to the plotting function. This will be the same for all calls to the plotting function and will override the values in *sty_cycle*. Returns ------- arts : dict Dictionary of artists keyed on their labels """ # deal with default binning(把...归入统计堆) function """ 我们传入了自己的hist_func,直方图分析函数。 所以不为None,代码不执行。 """ if hist_func is None: hist_func = np.histogram # deal with default plotting function """ plot_func 画直方图的函数,我们没有传入画直方图的函数, 这里是None,我们用系统默认的直方图函数filled_hist. 我们在调用plot_func的时候,讲解这个函数。 """ if plot_func is None: plot_func = filled_hist # deal with default """ 我们没有设置plot_kwargs,也就是没有设置绘图的参数。这里直接为空。 """ if plot_kwargs is None: plot_kwargs = {} print(plot_kwargs) try: """ 我们的stacked_data,也就是对数据是一个二维的数组,[4, 12250] stack_data = np.random.randn(4, 12250) 哪里会有key? 调用stacked_data.keys(),肯定会抛出异常。直接跳到异常模块 """ l_keys = stacked_data.keys() label_data = True if labels is None: labels = l_keys #这里是异常模块 except AttributeError: """ 设置label_data = False,意思是没有标签数据。 """ label_data = False if labels is None: """ 因为我们的labels为None, itertools.repeat(None),这个方法返回的结果是一个迭代器 每次迭代的结果都是None.可以无限访问,访问就有,不访问就没有。 现在的labels是一个迭代器了。 """ labels = itertools.repeat(None) if label_data: loop_iter = enumerate((stacked_data[lab], lab, s) for lab, s in zip(labels, sty_cycle)) else: """ 我们的label_data为False,就会执行下面这个代码。 zip 降三个数组装起来组装结果如下: (我们要分析的第一个数据集,标签(这里为None),样式(颜色,形状,标签)) (我们要分析的第二个数据集,标签(这里为None),样式(颜色,形状,标签)) (我们要分析的第三个数据集,标签(这里为None),样式(颜色,形状,标签)) (我们要分析的第四个数据集,标签(这里为None),样式(颜色,形状,标签)) enumerate,枚举,enumerate给每速数据添加了一个索引。用for循环访问 可以返回这个索引。 """ loop_iter = enumerate(zip(stacked_data, labels, sty_cycle)) arts = {} """ 访问,我们封装的数据。 """ for j, (data, label, sty) in loop_iter: """ 我们的label为None,所以会执行if里面的语句,给当前label进行赋值。 """ if label is None: label = "dflt set {n}".format(n=j) """ 这里的sty是一个字典,当用for循环访问sty_cycle的时候,sty_cycle是Cycler对象 也就是当用for循环访问Cycler对象的时候,它反会的是一个字典。 这个的sty的数据结构如下: sty["lable"]="" sty["hatch"]="" syt["facecolor"]="" pop是字典的方法,sty.pop("label", label)的意思是: 删除key为"label"的值,并返回这个key对应的值, 如果字典中没有这个key,就直接返回第二个参数对应的值。 """ label = sty.pop("label", label) """ hist_fun开始对数据进行分析 edges 代表这个直方图中20条边。 vals 代表这个直方图中有19个柱子 """ vals, edges = hist_func(data) if bottoms is None: """ 我们没有传入bottoms,也是柱状图的底部没有传入 默认为0. 我们要让这19根柱子,底部为0.就用 np.zeros_like(vals);这行代码的意思: 创建一个元素全是0的数组,这个数组的形状和vals的形状一样。 vals代表19根柱子的高度,也就是长度为19的数组 那么bottom就是19根柱子的底部位置 """ bottoms = np.zeros_like(vals) """ bottoms 和 vals都是numpy的数组,可以用加法进行运算, 使两个数组对应的元素进行相加。 tips: python中普通数组的相加,只是将两个数组连接起来。 19根柱子的底部位置+19根柱子的高度,就算出了19根柱子的顶部位置 """ top = bottoms + vals print(sty) """ 我们没有设置plot_kwargs,这里为None。 sty是一个字典。字典的update方法中,再传入一个字典,可以完成对原来字典的更新。 """ sty.update(plot_kwargs) print(sty) """ 开始调用我们的绘图函数。 ax:直角坐标系。 edges:19根柱子的20个边。 top:19根柱子的高度所在位置 bottols:19根柱子的底部所在位置 label:19根柱子的标签。 **sty:对我们的样式字典进行解包:解包结果:color="",hatch="" """ ret = plot_func(ax, edges, top, bottoms=bottoms, label=label, **sty) """ 第一个图画完了。第二个图,在第一个图的上边画。 所以第二个图的起点是第一个图的最高点。 """ bottoms = top """ 将绘图结果保存在字典里 """ arts[label] = ret """ 设置图例 """ ax.legend(fontsize=10) return arts 阅读三 """ 我们传入了参数ax:直角坐标系; edges:20条边 values:19个柱子的顶部位置 bottoms:19个柱子的底部位置 **kwargs:参数:我们传入的样式。 orientation:方向,我们没有传入,默认为v,垂直方向。 """ def filled_hist(ax, edges, values, bottoms=None, orientation="v", **kwargs): """ Draw a histogram as a stepped patch. Parameters ---------- ax : Axes The axes to plot to edges : array A length n+1 array giving the left edges of each bin and the right edge of the last bin. values : array A length n array of bin counts or values bottoms : float or array, optional A length n array of the bottom of the bars. If None, zero is used. orientation : {"v", "h"} Orientation of the histogram. "v" (default) has the bars increasing in the positive y-direction. **kwargs Extra keyword arguments are passed through to `.fill_between`. Returns ------- ret : PolyCollection Artist added to the Axes """ """ 传入的方向检查,要么是h,要么是v;其它的报错。 """ print(orientation) if orientation not in "hv": raise ValueError("orientation must be in {{"h", "v"}} " "not {o}".format(o=orientation)) """ 如果kwargs中没有step,则设置step的值为post 如果kwargs中没有alpha,则设置alpha的值为0.7 """ kwargs.setdefault("step", "post") kwargs.setdefault("alpha", 0.7) """ np.asarray: 将输入的数据转换为ndarray """ edges = np.asarray(edges) values = np.asarray(values) """ 如果19个柱子的边,不等于20,就报错。 """ if len(edges) - 1 != len(values): raise ValueError("Must provide one more bin edge than value not: " "len(edges): {lb} len(values): {lv}".format( lb=len(edges), lv=len(values))) """ 如果bottoms为None,就默认为0,这个标量。标量是相对于向量来说的。 向量就是数组。 bottoms 也可以是数组。 我们给这个函数传入的bottoms就是一个数组。 """ if bottoms is None: bottoms = 0 """ np.broadcast_to,这个函数的作用是:将bottoms中的值,广播到 values.shape中。 """ bottoms = np.broadcast_to(bottoms, values.shape) """ 在画图的时候,我们有20条边,我们要设置20条边的顶部位置 和20条边的底部位置。 现在values和bottoms里面存放的时候,19根柱子的顶部位置,19根柱子的底部位置 补充的这条边,应该和最后一条边一样长 """ values = np.append(values, values[-1]) bottoms = np.append(bottoms, bottoms[-1]) if orientation == "h": return ax.fill_betweenx(edges, values, bottoms, **kwargs) elif orientation == "v": """ 开始进行绘图 """ return ax.fill_between(edges, values, bottoms, **kwargs) else: raise AssertionError("you should never be here")
5g物联卡你了解多少?网速如何?贵不贵?物联卡也就是纯流量卡,只能用来上网,可以开热点,不能打电话和发短信的,但可以收短信。4G物联网卡广泛流行了很多年,现在轮到5G物联网卡了。现在的5G有多贵相信大家都知道,我自己的移
预算3000,要用得稍微久一点,速度要快,求手机推荐,最好一部?3000元预算看似不少,实则非常尴尬。现在这个价格买旗舰机肯定是不够的,基本上旗舰机都是4000打底,但买一些次旗舰多多少少又有点不甘心,并且现在这个时间点3000元价格可选择并不
现在哪款手机性价比高?这个问题比较宽,要从手机价位来分,一干左右选realmeQ3s,1199元的价格给你骁龙778处理器,5000毫安大电池还要什么自行车!一干五左右选红米note10pro,天玑11
你觉得农村老人过得幸福吗?农村老人过得幸福吗!农村老人过得幸福谈不上,但是比以前过得好,以前吃不饱,穿得破旧,现在能吃饱穿暖,跟以前比现在算得上幸福了!但是也有地区不同,穷的地区农村老人生活过得不是这么好,
求推荐2000元以内,超过HKCT7000钻石版的显示器?捂脸尴,你这个问题太专业了。整得我去补课了很久。先说下2k现在专业的数码up主都不用2k你搞设计2k有点不够用了。直接上4k显示器配置很重要,khc的入手过一台后边换易美逊了。每台
NVIDIAOmniverse在GTC22上有哪些更新?在创建和连接虚拟世界方面,已有超过15万人下载NVIDIAOmniverse,从而在助力3D设计工作流转型方面实现巨大飞跃,将物理属性准确的实时仿真提升到新高度。在GTC22上,N
javascript判断一个变量是否是不为空的对象问题如何判断一个变量或者对象,不是空对象代码如下说明如果是对象那么这个对象一定有成员。使用这样的原理进行判断下面是循环代码,得到当前对象的成员Keyfor(varkeyinobj)
一屋不扫何以扫天下与扫天下何以扫一屋两种观点你更赞同哪一种?谢邀简答如下命题一屋不扫何以扫天下与扫天下何以扫一屋两种观点你更赞同哪一种?本文明确赞同一屋不扫后何以扫天下这一种观点。小事都不做,或做不成,哪还能成就大事业!参天大树高楼大厦巨著
怎样用生活照制作1寸证件照?怎样用生活照制作1寸证件照?这个过程并不难,关键是对生活照的选择,不是什么样的生活照都适合做寸照的。还有就是生活照必须要经过抠图处理才能做成寸照。举个例子,说一下操作过程。先用PS
聊聊这些年我用过的手机(一)本人一直对数码产品比较感兴趣,随着智能手机的普及,这些年来我也换过很多手机,苹果华为小米三星这些品牌的手机也买过不少。先给大家上张图,这张照片是我好几年前拍的,那时候苹果才刚出到6
红米10A上市,649元,到底是谁在买?红米手机可以说是业界良心,无论是百元手机Redmi9普及18W,还是千元机小金刚note系列的高性价比与接近旗舰级的品质,可以说整个品牌的任何一款产品都非常的用心。红米10A这次的