美文网首页
matplotlib可视化之hist直方图

matplotlib可视化之hist直方图

作者: 丰年的博客 | 来源:发表于2020-05-10 16:40 被阅读0次

直方图

直方图(英语:Histogram)是一种对数据分布情况的图形表示,是一种二维统计图表,它的两个坐标分别是统计样本和该样本对应的某个属性的度量,一般以长条图(bar)的形式具体表现。因为直方图的长度及宽度很适合用来表现数量上的变化,所以较容易解读差异小的数值.

hist

  1. 函数定义:
    在向量 x 和 y 指定的位置创建一个包含圆形的散点图,该类型的图形也称为气泡图。
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]
  1. 常用参数:
  • x:
    数据集,最终的直方图将对数据集进行统计
  • bins:
    统计的区间分布划分,指定bin(箱子)的个数;
  • range:
    显示的区间,range在没有给出bins时生效
  • density:
    显示概率密度,默认为false
  • histtype:
    可选{'bar', 'barstacked', 'step', 'stepfilled'}之一,默认为bar,推荐使用默认配置,step使用的是梯状,stepfilled则会对梯状内部进行填充,效果与bar类似
  • align:
    可选{'left', 'mid', 'right'}之一,默认为'mid',控制柱状图的水平分布,left或者right,会有部分空白区域,推荐使用默认
  • log:
    默认为False,y坐标轴是否选择指数刻度,在数据分布的范围较大的时候,可以通过log指数刻度来缩小显示的范围。
  • stacked:
    默认为False,是否为堆积状图

hist的详细定义:
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html?highlight=hist#matplotlib.pyplot.hist

示例说明:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib

"""
font:设置中文
unicode_minus:显示负好
"""
matplotlib.rcParams['font.family'] = ['Heiti TC']
matplotlib.rcParams['axes.unicode_minus']=False     # 正常显示负号

"""
随机数生成,自动生成正态分布的数据集
"""
data = np.random.randn(10000)

"""
facecolor:长条形的颜色
edgecolor:长条形边框的颜色
alpha:透明度
"""
plt.hist(data, bins=40, density=False, facecolor="tab:blue", edgecolor="tab:orange", alpha=0.7)

"""
xlabel:横轴标签
ylabel:纵轴标签
title:图标题
"""
plt.xlabel("区间")
plt.ylabel("频数(频数)")
plt.title("频数(频率)分布图")
plt.show()

扩展应用:

  • 增加不同长条形色彩映射
    利用hist函数的三个返回值,对每一个不同区间进行不同颜色的显示.通过这种方式可以直观的看出分布的差异.
    n: 数组或数组列表,表明每一个bar区间的数量或者百分比;
    bins : 数组,bar的范围和bins参数含义一样;
    patches : 列表,每个bar图形对象;

import matplotlib.pyplot as plt
import numpy as np
import matplotlib

"""
font:设置中文
unicode_minus:显示负好
"""
matplotlib.rcParams['font.family'] = ['Heiti TC']
matplotlib.rcParams['axes.unicode_minus']=False     # 正常显示负号

"""
随机数生成,自动生成正态分布的数据集
"""
data = np.random.randn(10000)

"""
n: 数组或数组列表,表明每一个bar区间的数量或者百分比
bins : 数组,bar的范围和bins参数含义一样
patches : 列表 或者列表的列表 图形对象
"""
n, bins, patches =plt.hist(data, bins=40,)
percent = n / n.max()
#将percent中的数据进行正则化,这样可以方便的映射到colormap中

norm = colors.Normalize(percent.min(), percent.max())
"""
patches为对应每个长条的对象,循环为每个bar条进行颜色的设置.
set_facecolor()用来设置条形的颜色
"""

for thisfrac, thispatch in zip(percent, patches):
    color = plt.cm.viridis(norm(thisfrac))
    thispatch.set_facecolor(color)
"""
xlabel:横轴标签
ylabel:纵轴标签
title:图标题
"""
plt.xlabel("区间")
plt.ylabel("频数(频数)")
plt.title("频数(频率)分布图")
plt.show()

  • 显示多个数据的直方图
    可以在一个图中显示多个数据的直方图,方便对不同数据进行对比.
    重点区分坐标系一和坐标系四两者之间显示的区别
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(64)

n_bins = 20
"""
生成为一个纬度为(6000,3)的随机数据
"""
x = np.random.randn(6000, 3)

"""
生成有两行行列坐标系的画布
"""
fig, axes = plt.subplots(nrows=2, ncols=2,figsize=(16,9))

"""
第一坐标系,使用bar条来显示

为了和第四坐标系进行效果对比,次数对三列随机数进行分别显示
"""
colors = ['tab:blue', 'tab:orange', 'tab:green']
alpha=[1,0.6,0.3]
for index in np.arange(x.shape[1]):
    axes[0][0].hist(x[:,index], n_bins, density=True, histtype='bar', color=colors[index], label=colors[index],alpha=alpha[index])    
#axes[0][0].hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
axes[0][0].legend(prop={'size': 10})
axes[0][0].set_title('bar hist')

"""
第二坐标系,使用bar条来显示,设置的堆积的属性stacked
"""
axes[0][1].hist(x, n_bins, density=True, histtype='bar', stacked=True)
axes[0][1].set_title('stacked bar hist')

"""
第三坐标系,使用step来显示,设置的堆积的属性stacked
"""
axes[1][0].hist(x, n_bins, histtype='step', stacked=True, fill=False)
axes[1][0].set_title('stacked step hist')


"""
第四坐标系,一次性显示三列数据
"""
axes[1][1].hist(x, n_bins, density=True,histtype='bar')
axes[1][1].set_title('bat hist')

fig.tight_layout()
plt.show()
  • 双变量直方图
    在进行一维频次直方图绘制之外,可以对二维数组按照二维区间进行二维频次的直方图绘制.

重点:此处使用另外一种方式进行多子图的绘制,利用GridSpec可以更加灵活的多子图的绘制

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter

import matplotlib.gridspec as gridspec

np.random.seed(64)
N_points = 800
n_bins = 40

"""
生成为x,y随机数据
"""
x = np.random.randn(N_points)
y = 2* x + np.random.randn(N_points) + 5


fig = plt.figure(figsize=(10, 8))
# gridspec的用法,可以使图像横跨多个坐标
G = gridspec.GridSpec(2, 2)

#显示第一坐标系,其位置第一行,第一列(G[0, 0])
axes =fig.add_subplot(G[0, 0])
axes.hist(x, bins=n_bins)

#显示第二坐标系,其位置第一行,第二列(G[0, 1])
axes =fig.add_subplot(G[0, 1])
axes.hist(y, bins=n_bins)

#显示第三坐标系,其位置第二行整行(G[1, :])
axes =fig.add_subplot(G[1, :])
axes.hist2d(x,y, bins=n_bins)

plt.show()

相关文章

  • matplotlib可视化之hist直方图

    直方图 直方图(英语:Histogram)是一种对数据分布情况的图形表示,是一种二维统计图表,它的两个坐标分别是统...

  • matplotlib之直方图hist

    问题描述 当我们想展示不同的数据在所有数据样本中的分布时,需要用直方图来展示。当然在数据量很大的时候,如果为每个数...

  • matplotlib可视化篇hist()--直方图

    直方图与柱状图外观表现很相似,用来展现连续型数据分布特征的统计图形(柱状图主要展现离散型数据分布),官方hist项...

  • python matplotlib模块: hist(直方图)

    需要注意的是边缘数据存在导致结果看上去"不完整"的情况: 最右边的数据看不清楚,但是确实存在,只是数据太小了。这时...

  • Python推荐阅读文章

    matplotlib可视化 plot所有颜色属性 matplotlib动画制作 重叠的直方图 plot指令 sca...

  • mmdetection可视化

    0. 可视化特征图 1. matplotlib > hist 参考:176:hxm/wetectron-maste...

  • python__matplotlib画直方图(hist)

    区分直方图与条形图: 条形图是用条形的长度表示各类别频数的多少,其宽度(表示类别)则是固定的;直方图是用面积表示各...

  • matplotlib.pyplot.hist绘制直方图

    第一:导入包 第二:造数据 第三:参数解释 plt.hist(x,bins=None,range=None,den...

  • plt绘画直方图

    hist 可以绘画直方图

  • hist()直方图

    0 前言: 0.1与条形图的区别: 来自百度知道 条形统计图中,横轴上的数据是孤立的,是一个具体的数据.而直方图中...

网友评论

      本文标题:matplotlib可视化之hist直方图

      本文链接:https://www.haomeiwen.com/subject/aawkghtx.html