本文共 1186 字,大约阅读时间需要 3 分钟。
在 Python 中,我们可以使用 Pandas 库来处理数据框,以及 matplotlib 或 seaborn 等库来绘制条形图。本文将介绍如何将 pandas 数据框转换为海运分组条形图的实现步骤。
首先,我们需要导入 Pandas 库和 matplotlib 以进行数据处理和图表绘制。
import pandas as pdimport matplotlib.pyplot as plt
假设我们有一个名为 data 的 DataFrame,其中包含以下字段:Container_ID(容器编号)、Sea_line(海运公司)、container_type(容器类型)和weight(重量)。
我们可以通过 groupby 方法将 Sea_line 和 container_type 字段进行分组,并计算每个组的总重量。
grouped = data.groupby(['Sea_line', 'container_type']).sum()['weight']
接下来,我们使用 matplotlib 的 barh() 函数来绘制条形图。
grouped.unstack().plot(kind='barh')plt.xlabel('Weight') # 设置 x 轴标签plt.ylabel('Sea_line') # 设置 y 轴标签plt.title('Container Weight by Sea Line and Type') # 设置图表标题plt.show() # 显示图表 为了更直观地区分不同容器类型,我们可以为每个容器类型分配不同的颜色。
colors = {'Tanker': 'red', 'Refrigerated': 'blue', 'Dry Bulk': 'green'}grouped.unstack().plot( kind='barh', color=[colors[t] for t in grouped.index.get_level_values('container_type')])plt.xlabel('Weight')plt.ylabel('Sea_line')plt.title('Container Weight by Sea Line and Type')plt.show() 通过以上步骤,我们可以将 pandas 数据框转换为海运分组条形图。代码首先通过 groupby 方法分组计算总重量,然后通过 unstack() 展开数据并绘制条形图。为了更直观地区分容器类型,我们可以为每个容器类型分配不同的颜色。这个方法适用于实际项目中的数据处理和可视化需求。
转载地址:http://dsvfk.baihongyu.com/