• 在pandas中使matplotlib动态画子图的两种方法【推荐gridspec】


    先上对比图,在这里插入图片描述

    第一种方法,这里仅展示1个大区,多个的话需要加一层循环就可以了,主要是看子图的画法

    当大区下面的国家为1个或2个时,会进行报错

    # 获取非洲国家列表
    african_countries = df[df['大区'] == '南亚大区']['进口国'].unique()
    
    # 动态计算子图的行列数量
    num_countries = len(african_countries)
    rows = (num_countries + 2) // 3  # 计算行数
    cols = min(3, num_countries)  # 最多3列
    
    # 创建包含子图的图形
    fig, axes = plt.subplots(rows, cols, figsize=(15, 8))
    fig.suptitle('南亚大区不同国家进口金额月度变化趋势', fontsize=16, fontweight='bold')
    
    # 循环绘制子图
    for i, country in enumerate(african_countries):
        row, col = divmod(i, cols)
        ax = axes[row, col]
        
        # 按国家和月份对金额进行汇总
        monthly_sum = (df[(df['大区'] == '南亚大区') & (df['进口国'] == country)].groupby('月份')['金额'].sum() / 10000).round(1)
        
        # 绘制折线图
        ax.plot(monthly_sum.index, monthly_sum.values, marker='o', linestyle='-')
        ax.set_title(f'{country}进口金额月度变化趋势')
        ax.set_xlabel('月份')
        ax.set_ylabel('金额(万美元)')
        ax.grid(False)
        ax.tick_params(axis='x', rotation=45)
    
    # 调整子图布局
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])
    
    # 显示图形
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    第二种方法,这个可以动态的对数量进行调整,并不会出现空子图,仅有个框存在

    # 不同大洲的列表
    continents = ['北美大区', '拉美大区', '中东非大区', '南亚大区', '新亚太大区', '东欧大区', '西欧大区', '独联体大区', '东南亚大区']
    for continent in continents:
        # 获取非洲国家列表
        african_countries = df[df['大区'] == continent]['进口国'].unique()
    
        # 动态计算子图的行列数量
        num_countries = len(african_countries)
        rows = (num_countries + 2) // 3  # 计算行数
        cols = min(3, num_countries)  # 最多3列
    
        # 创建包含子图的图形
        fig = plt.figure(figsize=(15, rows * 3.5))
        fig.suptitle(f'{continent}国家进口金额月度变化趋势', fontsize=16, fontweight='bold')
        gs = fig.add_gridspec(rows, cols)
    
        # 循环绘制子图
        for i, country in enumerate(african_countries):
            row, col = divmod(i, cols)
            ax = fig.add_subplot(gs[row, col])
    
            # 按国家和月份对金额进行汇总
            monthly_sum = (df[(df['大区'] == continent) & (df['进口国'] == country)].groupby('月份')['金额'].sum() / 10000).round(1)
    
            # 绘制折线图
            ax.plot(monthly_sum.index, monthly_sum.values, marker='o', linestyle='-')
            ax.set_title(f'{country}进口金额月度变化趋势')
            ax.set_xlabel('月份')
            ax.set_ylabel('金额(万美元)')
            ax.grid(False)
            ax.tick_params(axis='x', rotation=45)
    
        # 调整子图布局
        plt.tight_layout(rect=[0, 0.03, 1, 0.95])
    
        # 显示图形
        plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
  • 相关阅读:
    [附源码]SSM计算机毕业设计校园超市进销存管理系统JAVA
    RT-Thread 中断管理(学习)
    C++面试八股文:技术勘误
    “中国国安部紧急警告”!境外公司利用加密货币诱使人员非法采集空间数据!当心不慎成“帮凶”!
    关于 Elasticsearch 内存占用及分配
    HTML+CSS+JavaScript仿京东购物商城网站 web前端制作服装购物商城 html电商购物网站
    CTFshow 信息收集 web12 13 14 15
    安装rGEDI包报错(已解决)
    OpenCV图像特征提取学习一,Harris图像角点检测算法
    使用elasticsearch_exporter监控elasticsearch集群的状态
  • 原文地址:https://blog.csdn.net/weixin_47744974/article/details/133170837