Pandas子图部分空白或显示异常,折线图绘制场景下的问题求助
问题解决方案
子图空白问题修复
导致空白的核心问题如下,均已在修正代码中处理:
- 样式配置顺序错误:样式、字体等全局配置需要放在所有绘图代码之前,绘图完成后再修改配置不会生效,还会导致已绘制元素渲染异常
- 子图遍历逻辑错误:
df.plot返回的子图对象是shape为(5,2)的二维数组,原代码的遍历逻辑没有正确匹配所有子图与对应数据列,导致部分子图没有绘制折线 - 列名冲突:原代码中两个数据列设置了重复的列名,导致绘图时数据匹配错误
- 冗余代码干扰:末尾的
ax.set_title("US Reserves")会覆盖最后一个子图的正确标题,plt.xlabel仅作用于最后一个子图,不符合预期
FRED数据拉取偶发报错修复
报错通常由网络波动、FRED接口限流、旧版本库兼容问题导致,修复方案:
- 升级pandas_datareader到最新版本:
pip install --upgrade pandas-datareader - 拉取数据时增加超时参数,避免短时间网络波动导致请求失败
import matplotlib.pyplot as plt import seaborn as sns import pandas_datareader.data as pdr import pandas as pd import datetime # 全局样式配置放在最前面 plt.style.use('seaborn-whitegrid') plt.rcParams.update({'font.family':'Latin Modern Sans'}) start = datetime.datetime(2000,1,1) end = datetime.datetime(2021,5,1) # 拉取数据增加超时参数 df = pdr.DataReader(['FDHBFRBN', 'FDHBFIN', 'FYGFDPUN', 'FRDGBSAM', 'HBFRGDQ188S', 'MTSMFBP133FMS', 'GFDEGDQ188S', 'GFDEBTN', 'FYFSD', 'FYFSGDA188S'], 'fred', start, end, timeout=30) # 修正重复列名,保证每个列名唯一 df.columns = ['Federal Debt Held by Federal Reserve Banks', 'Federal Debt Held by Foreign and International Investors', 'Federal Debt Held by the Public ', 'Federal Reserve Bank Held Gold Bullion: On Display', 'Federal Debt Held by Federal Reserve Banks as Percent of Gross Domestic Product', 'Means of Financing: Borrowing from the Public', 'Federal Debt: Total Public Debt as Percent of Gross Domestic Product', 'Federal Debt: Total Public Debt', 'Federal Surplus or Deficit', 'Federal Surplus or Deficit [-] as Percent of Gross Domestic Product'] # 绘图返回的axes为5行2列二维数组 axes = df.plot(subplots=True, layout=(5,2), figsize=(15,25), linewidth=2, colormap="summer") # 用ravel()展平axes后遍历,不破坏原二维索引结构 for ax, col in zip(axes.ravel(), df.columns): ax.axvspan('2007-1-12', '2009-6-1', color='teal', alpha=0.5, label='2008 Crisis') ax.axvspan('2019-12-1', '2020-2-1', color='orange', alpha=0.5, label='Pandemic') ax.set_title(col) ax.set_xlabel('Date') # 给每个子图添加x轴标签 axes[0,0].set_title('Federal Debt Held by Federal Reserve Banks') axes[0,0].set_ylabel('Billions of Dollars(Quarterly)') axes[0,0].legend(bbox_to_anchor=(1.05, 1)) axes[0,1].set_title('Federal Debt Held by Foreign and International Investors') axes[0,1].set_ylabel('Billions of Dollars(Quarterly)') axes[0,1].legend(bbox_to_anchor=(1.05, 1)) axes[1,0].set_title('Federal Debt Held by the Public ') axes[1,0].set_ylabel('Millions of Dollars(Quarterly)') axes[1,0].legend(bbox_to_anchor=(1.05, 1)) axes[1,1].set_title('Federal Reserve Bank Held Gold Bullion: On Display ') axes[1,1].set_ylabel('Fine Troy Ounces(Monthly)') axes[1,1].legend(bbox_to_anchor=(1.05, 1)) axes[2,0].set_title('Federal Debt Held by Federal Reserve Banks as Percent of Gross Domestic Product') axes[2,0].set_ylabel('Percent of GDP(Quarterly)') axes[2,0].legend(bbox_to_anchor=(1.05, 1)) axes[2,1].set_title('Means of Financing: Borrowing from the Public') axes[2,1].set_ylabel('Millions of Dollars(Monthly)') axes[2,1].legend(bbox_to_anchor=(1.05, 1)) axes[3,0].set_title('Federal Debt: Total Public Debt as Percent of Gross Domestic Product ') axes[3,0].set_ylabel('Percent of GDP(Quarterly)') axes[3,0].legend(bbox_to_anchor=(1.05, 1)) axes[3,1].set_title('Federal Debt: Total Public Debt') axes[3,1].set_ylabel('Millions of Dollars(Quarterly)') axes[3,1].legend(bbox_to_anchor=(1.05, 1)) axes[4,0].set_title('Federal Surplus or Deficit') axes[4,0].set_ylabel('Billions of Dollars(Annual)') axes[4,0].legend(bbox_to_anchor=(1.05, 1)) axes[4,1].set_title('Federal Surplus or Deficit [-] as Percent of Gross Domestic Product') axes[4,1].set_ylabel('Percent of GDP(Annual)') axes[4,1].legend(bbox_to_anchor=(1.05, 1)) # 布局调整放在所有配置完成后 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者user15157590
相关产品推荐
相关产品推荐

