• 在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
  • 相关阅读:
    【测试沉思录】19. 如何设置 JMeter 线程组?
    CSS学习笔记
    [多线程] | 实例演示三种创建多线程的方式,初识线程同步以及解决线程安全问题(超卖)
    基于opencv实现简单人脸检测
    代码审计-4 代码执行漏洞
    【牛客 - 剑指offer】JZ64 求1+2+3+...+n Java实现
    君正X2100 使用SPI NOR Flash
    【无标题】H5页面解决点击页面处关闭键盘,触发了页面的事件的问题
    正则表达式
    应用在防蓝光显示器中的LED防蓝光灯珠
  • 原文地址:https://blog.csdn.net/weixin_47744974/article/details/133170837