Python 直观理解基尼系数

基尼系数最开始就是衡量人群财富收入是否均衡,大家收入平平,那就是很平均,如果大家收入不平等,那基尼系数就很高。

还是给老干部们讲的言简意赅。
什么是基尼系数

我们接下来直接直观地看吧,程序说话

python 复制代码
# -*- coding: utf-8 -*-

"""
@author: 赫凯
@software: PyCharm
@file: xx.py
@time: 2023/12/15 12:57
"""

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
import matplotlib

matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False

# 基尼系数值
def gini_coef(kpi_num):
    cum_kpi = np.cumsum(sorted(np.append(kpi_num, 0)))
    sum_kpi = cum_kpi[-1]
    xarray = np.array(range(0, len(cum_kpi)))/np.float(len(cum_kpi)-1)
    yarray = cum_kpi/sum_kpi
    B = np.trapz(yarray, xarray)
    A = 0.5 - B
    return A/(A+B)


# 初始化画布
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
data1 = [[10, 20, 30],
         [10, 20, 30, 40],
         [10, 20, 30, 40, 50],
         [10, 20, 30, 40, 50, 180],
         [10, 20, 30, 40, 50, 180, 200],
         [10, 20, 30, 40, 50, 180, 200, 1000]]


def draw(num):
    data = data1[num]
    # 绘制基尼系数曲线
    x = range(1, len(data) + 1)
    x1 = [sum(x[:i]) for i in x]
    y1 = [sum(data[:i]) for i in x]
    y2 = data
    # 清空原有图形
    plt.cla()
    # 创建包含两个子图的图形
    ax1.clear()
    # 在第一个子图中绘制 sin 曲线
    ax1.plot(x, y1, 'r-')
    ax1.set_xticks(x, x1)
	# 斜线
    ax1.plot([x[0], x[-1]], [y1[0], y1[0]])
    ax1.plot([x[-1], x[-1]], [y1[0], y1[-1]])
    ax1.plot([x[0], x[-1]], [y1[0], y1[-1]])

    y_ = [(y1[-1] - y1[0]) / (x[-1] - x[0]) * (i - x[0]) + y1[0] for i in x]
    # 填充区域
    ax1.fill_between(x, y1, [y1[0] for i in x], color='g', alpha=0.3, interpolate=True)
    ax1.fill_between(x, y_, y1, color='pink', alpha=0.3, interpolate=True)
    ax1.set_xlabel('最低收入到最高收入个数累计')
    ax1.set_ylabel('财富累计)')
    ax1.set_title(f'基尼系数展示{gini_coef(y1)}')

    # 在第二个子图中绘制 cos 曲线
    ax2.bar(x, y2)
    ax2.set_xlabel('个人')
    ax2.set_ylabel('财富值')
    ax2.set_title('每个人的财富总览')


# 创建动画对象
ani = FuncAnimation(plt.gcf(), draw, frames=len(data1), interval=500, blit=False)

ani.save('xx.gif')
# 显示动画
plt.show()
相关推荐
Julyyyyyyyyyyy38 分钟前
【软件测试】web自动化:Pycharm+Selenium+Firefox(一)
python·selenium·pycharm·自动化
Fanxt_Ja1 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法
蓝婷儿1 小时前
6个月Python学习计划 Day 15 - 函数式编程、高阶函数、生成器/迭代器
开发语言·python·学习
love530love2 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
水银嘻嘻2 小时前
05 APP 自动化- Appium 单点触控& 多点触控
python·appium·自动化
slandarer2 小时前
MATLAB | 绘图复刻(十九)| 轻松拿捏 Nature Communications 绘图
开发语言·matlab
狐凄2 小时前
Python实例题:Python计算二元二次方程组
开发语言·python
roman_日积跬步-终至千里3 小时前
【Go语言基础【3】】变量、常量、值类型与引用类型
开发语言·算法·golang
roman_日积跬步-终至千里3 小时前
【Go语言基础】基本语法
开发语言·golang·xcode
Felven3 小时前
C. Basketball Exercise
c语言·开发语言