使用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)

相关推荐

  1. R 绘图 -

    2024-06-05 22:36:02       54 阅读
  2. 使用Python绘制旭日

    2024-06-05 22:36:02       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-05 22:36:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-05 22:36:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-05 22:36:02       87 阅读
  4. Python语言-面向对象

    2024-06-05 22:36:02       96 阅读

热门阅读

  1. 基于单片机的电子万年历设计

    2024-06-05 22:36:02       28 阅读
  2. 第十五届蓝桥杯总结

    2024-06-05 22:36:02       29 阅读
  3. cesium学习6-相机camera

    2024-06-05 22:36:02       29 阅读
  4. Pytorch常用函数用法归纳:Tensor张量之间的计算

    2024-06-05 22:36:02       23 阅读
  5. 704. 二分查找

    2024-06-05 22:36:02       28 阅读
  6. 【leetcode--判断子序列】

    2024-06-05 22:36:02       31 阅读
  7. Python表达且:深入剖析其逻辑与实现

    2024-06-05 22:36:02       26 阅读
  8. Oracle数据库面试题-5

    2024-06-05 22:36:02       22 阅读