使用python绘制华夫饼图

使用python绘制华夫饼图

  • 华夫饼图
  • 效果
  • 代码

华夫饼图

华夫饼图(Waffle Chart)是一种数据可视化图表,用于显示数据在一个网格中的分布情况。它类似于饼图,通过将数据划分为等大小的方块来表示不同类别的比例。华夫饼图的优势在于它更易于比较不同类别的数量关系,适合用于展示占比和组成情况。

效果

在这里插入图片描述

代码

import matplotlib.pyplot as plt
import numpy as np


def create_waffle_chart(categories, values, height, width, colormap):
    total_values = sum(values)
    category_proportions = [value / total_values for value in values]

    total_num_tiles = width * height
    tiles_per_category = [round(proportion * total_num_tiles) for proportion in category_proportions]

    waffle_chart = np.zeros((height, width))

    category_index = 0
    tile_index = 0

    for row in range(height):
        for col in range(width):
            tile_index += 1

            if tile_index > sum(tiles_per_category[:category_index + 1]):
                category_index += 1

            waffle_chart[row, col] = category_index

    fig, ax = plt.subplots()
    colormap = plt.cm.get_cmap(colormap)
    ax.matshow(waffle_chart, cmap=colormap)
    plt.colorbar(ax.matshow(waffle_chart, cmap=colormap))

    ax.set_xticks(np.arange(-0.5, (width), 1), minor=True)
    ax.set_yticks(np.arange(-0.5, (height), 1), minor=True)
    ax.grid(which='minor', color='w', linestyle='-', linewidth=2)

    ax.tick_params(which='minor', size=0)

    legend_handles = [plt.Rectangle((0, 0), 1, 1, color=colormap(i / len(categories))) for i in range(len(categories))]
    plt.legend(legend_handles, categories, loc='lower center', ncol=len(categories), bbox_to_anchor=(0.5, -0.2))

    plt.title('Waffle Chart')
    plt.show()


# 示例数据
categories = ['类别 A', '类别 B', '类别 C']
values = [50, 30, 20]
colormap = 'tab20'

# 绘制华夫饼图
create_waffle_chart(categories, values, height=10, width=10, colormap=colormap)

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

立秋6789

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值