以下是使用Python Matplotlib绘制动态饼状图的示例代码:

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

# 数据
age_ranges = ['0-14', '15-59', '60+']
age_percents = [20, 60, 20]
age_colors = ['#ff9999','#66b3ff','#99ff99']

senior_percents = [5, 15, 80]
senior_colors = ['#ff9999','#66b3ff','#99ff99']

# 创建子图
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

# 绘制饼状图
def plot_pie(percentages, colors, ax):
    ax.pie(percentages, colors=colors, startangle=90, counterclock=False, autopct='%1.1f%%',
           wedgeprops={'linewidth': 2, 'edgecolor': 'white'})
    ax.axis('equal')

# 初始状态
plot_pie(age_percents, age_colors, ax1)
plot_pie(senior_percents, senior_colors, ax2)

# 动态更新饼状图
def update(num):
    if num == 0:
        return
    age_percents[0] += num
    age_percents[1] -= num
    plot_pie(age_percents, age_colors, ax1)
    
    senior_percents[0] -= num/4
    senior_percents[1] += num/4
    plot_pie(senior_percents, senior_colors, ax2)

# 创建动画
ani = animation.FuncAnimation(fig, update, frames=15, interval=500)

plt.show()

运行此代码将会绘制出一个动态的饼状图,其中左边的图表显示了各年龄段的占比,右边的图表显示了65岁及以上的人口占比。在动画中,我们将会看到20%的年龄在0-14岁之间的人口逐渐增加,同时15-59岁之间的人口逐渐减少,直到20%的年龄在0-14岁之间的人口占据了整个饼状图。右边的图表也会随之更新,显示65岁及以上的人口占比的变化


原文地址: https://www.cveoy.top/t/topic/fHOR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录