我正在进行基本经济分析,当我开始可视化和绘制图表时,我无法将日期与图表对齐。
我希望最近的日期条目显示在右侧,其余日期每两年显示一次。
我几乎已经尝试了所有方法,但找不到解决方案。
这是我的代码:
%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()
输出:
这是原始数据:
最佳答案
您的代码有几个更正。
在您的 URL 中插入“?”在 fredgraph.csv 之后。它开始所谓的查询字符串, 其中 bgcolor 是第一个参数。
使用附加参数读取您的 DataFrame:
df = pd.read_csv('...', parse_dates=[0], index_col=[0])
目的是:
- 将日期列读作日期时间,
- 将其设置为索引。
创建额外的列:
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 - 日期和图表对齐 - 经济分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63990443/