python - 日期和图表对齐 - 经济分析
问题描述
我正在进行基本经济分析,当我开始可视化和绘制图表时,我无法将日期与图表对齐。
我希望最近的日期条目显示在右侧,其余日期每两年显示一次。
我已经尝试了一切,但找不到解决方案。
这是我的代码:
%matplotlib inline
import pandas as pd
from matplotlib import pyplot
import matplotlib.dates as mdates
df = pd.read_csv('https://fred.stlouisfed.org/graph/fredgraph.csvbgcolor=%23e1e9f0&chart_type=line&drp=0&fo=open%20sans&graph_bgcolor=%23ffffff&height=450&mode=fred&recession_bars=off&txtcolor=%23444444&ts=12&tts=12&width=1168&nt=0&thu=0&trc=0&show_legend=yes&show_axis_titles=yes&show_tooltip=yes&id=NAEXKP01EZQ657S&scale=left&cosd=1995-04-01&coed=2020-04-01&line_color=%234572a7&link_values=false&line_style=solid&mark_type=none&mw=3&lw=2&ost=-99999&oet=99999&mma=0&fml=a&fq=Quarterly&fam=avg&fgst=lin&fgsnd=2020-02-01&line_index=1&transformation=lin&vintage_date=2020-09-21&revision_date=2020-09-21&nd=1995-04-01')
df = df.set_index('DATE')
df['12MonthAvg'] = df.rolling(window=12).mean().dropna(how='all')
df['9MonthAvg'] = df['12MonthAvg'].rolling(window=12).mean().dropna(how='all')
df['Spread'] = df['12MonthAvg'] - df['9MonthAvg']
pyplot.style.use("seaborn")
pyplot.subplots(figsize=(10, 5), dpi=85)
df['Spread'].plot().set_title('EUROPE: GDP Q Growth Rate (12M/12M Avg Spread)', fontsize=16)
df['Spread'].plot().axhline(0, linestyle='-', color='r',alpha=1, linewidth=2, marker='')
df['Spread'].plot().spines['left'].set_position(('outward', 10))
df['Spread'].plot().spines['bottom'].set_position(('outward', 10))
df['Spread'].plot().spines['right'].set_visible(False)
df['Spread'].plot().spines['top'].set_visible(False)
df['Spread'].plot().yaxis.set_ticks_position('left')
df['Spread'].plot().xaxis.set_ticks_position('bottom')
df['Spread'].plot().text(0.50, 0.02, "Crossing red line downwards / Crossing red line Upwards",
transform=pyplot.gca().transAxes, fontsize=14, ha='center', color='blue')
df['Spread'].plot().fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
print(df['Spread'].tail(3))
pyplot.autoscale()
pyplot.show()
和输出:
这是原始数据:
解决方案
您的代码有一些更正。
在您的网址中插入“?” 在fredgraph.csv之后。它开始所谓的查询字符串,其中bgcolor是第一个参数。
使用附加参数读取您的 DataFrame:
df = pd.read_csv('...', parse_dates=[0], index_col=[0])
目的是:
- 将Date列读取为datetime,
- 将其设置为索引。
创建其他列:
df['12MonthAvg'] = df.NAEXKP01EZQ657S.rolling(window=12).mean() df['9MonthAvg'] = df.NAEXKP01EZQ657S.rolling(window=9).mean() df['Spread'] = df['12MonthAvg'] - df['9MonthAvg']
更正:
- 9MonthAvg(我认为)应该从源列计算,而不是从12MonthAvg,
- 此处不需要dropna,因为无论如何您都会创建整个列。
现在是在Spread列上使用dropna()并将其保存在专用变量中的地方:
spread = df['Spread'].dropna()
用以下方式绘制你的图形:
import matplotlib.pyplot as plt import matplotlib.dates as mdates plt.style.use("seaborn") fig, ax = plt.subplots(figsize=(10, 5), dpi=85) plt.plot_date(spread.index, spread, fmt='-') ax.set_title('EUROPE: GDP Q Growth Rate (12M/12M Avg Spread)', fontsize=16) ax.axhline(0, linestyle='-', color='r',alpha=1, linewidth=2, marker='') ax.spines['left'].set_position(('outward', 10)) ax.spines['bottom'].set_position(('outward', 10)) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.text(0.50, 0.02, "Crossing red line downwards / Crossing red line Upwards", transform=ax.transAxes, fontsize=14, ha='center', color='blue') ax.xaxis.set_major_formatter(mdates.DateFormatter(fmt='%Y-%m-%d')) plt.show()
更正:
- plt.subplots返回fig和ax,所以我保存了它们(实际上,只需要ax )。
- 当一个轴包含日期时,最好使用plot_date。
- 我改变了DateFormatter的设置方式。
使用上面的代码,我得到了以下图片:
推荐阅读
- python - 如何让 Sphinx 识别 `:param` 元素?
- javascript - 旋转画布 JS 中的特定元素
- ios - 您可以将 Firebase 添加到 Swift 包中的单元测试中吗?
- laravel - 即使在锚标记的 href 中设置了正确的 id,我的控制器也会在后面加上一个 id
- json - 需要帮助 RxSwift MVVM:无法在线将数据 JSON 加载到表格视图单元格
- c++ - Need help fixing this C++ code (Quadratic Formula solver)
- java - 如何替换html字符串上的常量值?
- database - 想根据以下要求创建表
- ios - 在 iOS 15 中选择退出 SwiftUI 文本 Markdown 支持
- r - 如何从 Excel 导出数据以使用 timevis 在 R 中创建时间线