首页 > 解决方案 > 日期和图表对齐 - 经济分析

问题描述

我正在进行基本经济分析,当我开始可视化和绘制图表时,我无法将日期与图表对齐。

我希望最近的日期条目显示在右侧,其余日期每两年显示一次。

我已经尝试了一切,但找不到解决方案。

这是我的代码:

%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()

和输出:

在此处输入图像描述

这是原始数据:

在此处输入图像描述

标签: pythonmatplotlibstatistics

解决方案


您的代码有一些更正。

  1. 在您的网址中插入“?” 在fredgraph.csv之后。它开始所谓的查询字符串,其中bgcolor是第一个参数。

  2. 使用附加参数读取您的 DataFrame:

    df = pd.read_csv('...', parse_dates=[0], index_col=[0])
    

    目的是:

    • 将Date列读取为datetime
    • 将其设置为索引。
  3. 创建其他列:

    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,因为无论如何您都会创建整个列。
  4. 现在是在Spread列上使用dropna()并将其保存在专用变量中的地方:

    spread = df['Spread'].dropna()
    
  5. 用以下方式绘制你的图形:

    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返回figax,所以我保存了它们(实际上,只需要ax )。
    • 当一个轴包含日期时,最好使用plot_date
    • 我改变了DateFormatter的设置方式。

使用上面的代码,我得到了以下图片:

在此处输入图像描述


推荐阅读