python 多组直方图 画图_5种方法教你用Python玩转histogram直方图

直方图是一个可以快速展示数据概率分布的工具,直观易于理解,并深受数据爱好者的喜爱。大家平时可能见到最多就是matplotlib,seaborn等高级封装的库包,类似以下这样的绘图。

c968f5200ae9633b789a26a0f362846b.png

本篇博主将要总结一下使用Python绘制直方图的所有方法,大致可分为三大类(详细划分是五类,参照文末总结):纯Python实现直方图,不使用任何第三方库

使用Numpy来创建直方图总结数据

使用matplotlib,pandas,seaborn绘制直方图

下面,我们来逐一介绍每种方法的来龙去脉。

纯Python实现histogram

当准备用纯Python来绘制直方图的时候,最简单的想法就是将每个值出现的次数以报告形式展示。这种情况下,使用字典来完成这个任务是非常合适的,我们看看下面代码是如何实现的。>>> a = (0, 1, 1, 1, 2, 3, 7, 7, 23)

>>> def count_elements(seq) -> dict:

...     """Tally elements from `seq`."""

...     hist = {}

...     for i in seq:

...         hist[i] = hist.get(i, 0) + 1

...     return hist

>>> counted = count_elements(a)

>>> counted

{0: 1, 1: 3, 2: 1, 3: 1, 7: 2, 23: 1}

我们看到,count_elements()返回了一个字典,字典里出现的键为目标列表里面的所有唯一数值,而值为所有数值出现的频率次数。hist[i] = hist.get(i, 0) + 1实现了每个数值次数的累积,每次加一。

实际上,这个功能可以用一个Python的标准库collection.Counter类来完成,它兼容Pyhont 字典并覆盖了字典的.update()方法。

>>> from collections import Counter

>>> recounted = Counter(a)

>>> recounted

Counter({0: 1, 1: 3, 3: 1, 2: 1, 7: 2, 23: 1})

可以看到这个方法和前面我们自己实现的方法结果是一样的,我们也可以通过collection.Counter来检验两种方法得到的结果是否相等。>>> recounted.items() == counted.items()

True

我们利用上面的函数重新再造一个轮子ASCII_histogram,并最终通过Python的输出格式format来实现直方图的展示,代码如下:def ascii_histogram(seq) -> None:

"""A horizontal frequency-table/histogram plot."""

counted = count_elements(seq)

for k in sorted(counted):

print('{0:5d} {1}'.format(k, '+' * counted[k]))

这个函数按照数值大小顺序进行绘图,数值出现次数用(+)符号表示。在字典上调用sorted()将会返回一个按键顺序排列的列表,然后就可以获取相应的次数counted[k]。>>> import random

>>> random.seed(1)

>>> vals = [1, 3, 4, 6, 8, 9, 10]

>>> # `vals` 里面的数字将会出现5到15次

>>> freq = (random.randint(5, 15) for _ in vals)

>>> data = []

>>> for f, v in zip(freq, vals):

...     data.extend([v] * f)

>>> ascii_histogram(data)

1 +++++++

3 ++++++++

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Python的Matplotlib库中的mpl_toolkits.mplot3d来绘制3D柱状图和直方图,其中ax.bar3d函数可以用于创建3D柱状图。 例如,以下是一个使用ax.bar3d绘制3D柱状图的示例代码: ```python import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 数据 x = np.random.randint(0, 10, 10) y = np.random.randint(0, 10, 10) z = np.random.randint(0, 10, 10) dx = np.ones_like(x) dy = np.ones_like(y) dz = z # 绘制3D柱状图 ax.bar3d(x, y, z, dx, dy, dz) # 添加轴标签 ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show() ``` 如果您想要绘制3D直方图,可以使用ax.hist3d函数。以下是一个使用ax.hist3d绘制3D直方图的示例代码: ```python import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # 数据 x = np.random.randn(100) y = np.random.randn(100) z = np.random.randn(100) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 绘制3D直方图 hist, xedges, yedges = np.histogram2d(x, y, bins=10) xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:]) xpos = xpos.flatten()/2. ypos = ypos.flatten()/2. zpos = np.zeros_like(xpos) dx = xedges[1] - xedges[0] dy = yedges[1] - yedges[0] dz = hist.flatten() ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average') # 添加轴标签 ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show() ``` 希望这能帮到您!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值