如何从多个DataFrame中绘制特定国家的x值?
问题:批量绘制多DataFrame中特定国家的x值
我有10个列名完全相同的DataFrame,数据示例如下:
country_code country x y SVN Slovenia 29.794 21.041 ESP Spain 380.429 176.025 SWE Sweden 43.313 38.123 CHE Switzerland 173.884 67.118 GBR UK 630.777 202.434
需求:优雅实现绘制这10个DataFrame中某个特定国家的x值。
我尝试过合并后分组的方法,代码如下:
import numpy as np import pandas as pd import matplotlib.pyplot as plt keys = np.arange(1,11) result = pd.concat(frames, keys=keys) grouped = result.groupby(["country_code"]) fig, axs = plt.subplots(10, sharex=True) for ax, (key, frame) in zip(axs, agg_ita): frame = frame.droplevel(0) frame.plot(ax=ax) ax.set_title(f'{key}') fig.tight_layout()
优雅实现方案
方案1:先筛选再合并(推荐,减少数据处理量)
先从每个DataFrame中提取目标国家的数据,再合并后绘图,避免全量合并所有数据,效率更高:
import pandas as pd import matplotlib.pyplot as plt # 假设目标国家的country_code是'ITA' target_country = 'ITA' # 遍历所有DataFrame,筛选目标国家并添加批次标识 filtered_dfs = [] for idx, df in enumerate(frames, 1): filtered = df[df['country_code'] == target_country].copy() filtered['batch'] = idx # 添加批次列,标记来自第几个DataFrame filtered_dfs.append(filtered) # 合并筛选后的结果 combined = pd.concat(filtered_dfs) # 绘制折线图,直观展示各批次的x值变化 plt.figure(figsize=(8, 5)) plt.plot(combined['batch'], combined['x'], marker='o', linestyle='-', color='#2E86AB') plt.xlabel('DataFrame批次') plt.ylabel('x值') plt.title(f'目标国家{target_country}在各DataFrame中的x值') plt.xticks(range(1, 11)) plt.grid(axis='y', linestyle='--', alpha=0.7) plt.tight_layout() plt.show()
方案2:合并时添加标识,灵活筛选绘图
如果需要保留全量数据用于后续其他分析,也可以在合并时统一添加批次列,再筛选目标国家绘图:
import pandas as pd import matplotlib.pyplot as plt # 给每个DataFrame添加批次标识后合并 frames_with_batch = [df.assign(batch=idx+1) for idx, df in enumerate(frames)] combined = pd.concat(frames_with_batch) # 筛选目标国家数据 target_data = combined[combined['country_code'] == 'ITA'] # 用子图展示每个批次的单独数据(适合对比细节) fig, axs = plt.subplots(5, 2, figsize=(12, 10), sharex=True, sharey=True) axs = axs.flatten() for idx, (batch, data) in enumerate(target_data.groupby('batch'), 0): axs[idx].bar(data['country'], data['x'], color='#F24C4C') axs[idx].set_title(f'批次{batch}') axs[idx].set_ylabel('x值') plt.tight_layout() plt.show()
方案优势
- 避免全量数据的冗余分组操作,只聚焦目标国家数据,逻辑更简洁
- 批次标识清晰,绘图时可直观看到不同DataFrame中目标国家x值的变化趋势
- 代码易读易维护,后续调整目标国家或绘图样式的成本极低
内容的提问来源于stack exchange,提问作者strawhat
相关产品推荐
相关产品推荐

