使用共享的“ x”绘制数据帧的多列

时间:2019-04-08 14:08:52

标签: python-3.x pandas matplotlib

我有一个如下所示的数据框df(所有列均为数字,但最后两列应为分类的)

                 Close  Direction  prediction
Date
2018-03-31   40.889999         -1           1
2017-12-31   34.459999          1           1
2017-09-30   40.529999         -1          -1
2017-06-30   38.200001          1          -1
2017-03-31   43.160000          1          -1
2016-12-31   46.369999          1          -1
2016-09-30   63.180000          1          -1
2016-06-30   64.300003          1           1
2016-03-31   66.500000          1           1
2015-12-31   85.250000         -1          -1
2015-09-30   63.020000          1           1
2015-06-30   87.139999         -1          -1
2015-03-31   83.169998         -1           1
我想用共享的x轴绘制这三列。

  

plot1-线图(x =数据框的日期索引,y = df [关闭])
  plot2-散点图(x =数据框的日期索引,y = df [Direction])
  plot3-散点图(x =数据框的日期索引,y = df [预测])

所有三个图都应该在另一个共享x轴上相互重叠,
我已经尝试了以下核心,但没有得到想要的输出。

fig, (ax1, ax2,ax3) = plt.subplots(3, 1,figsize=(10,7), sharex=True)
ax1.plot(x= df.index, y=df['Close'])
ax2.scatter(x= df.index, y=df['Direction'].astype('category'),color='blue')
ax3.scatter(x= df.index, y=df['prediction'].astype('category'),color='red')

xtick_dates = pd.date_range(df.index[0], df.index[-1], freq='3M')
plt.xticks(dates_rng, [dtz.strftime('%Y-%m') for dtz in xtick_dates], rotation=90)
plt.show()

有人能找到解决方法吗?

1 个答案:

答案 0 :(得分:0)

弄清楚了

def plot_predictions(details):
    global path
    df = pd.read_csv(path+"Quarterly_prediction.csv",parse_dates=['Date'],index_col=0)

    fig, (ax1, ax2,ax3) = plt.subplots(3, 1,figsize=(10,7), sharex=True)
    fig.subplots_adjust(bottom=0.2)

    ax1.plot( df.index, df['Close'])
    ax1.xaxis.grid(True,alpha=0.3)
    ax1.set_ylabel('Quarterly Closing')

    ax2.scatter(x= df.index, y=df['Direction'],color='blue')
    ax2.xaxis.grid(True,alpha=0.3)
    ax2.set_ylabel('Actual Direction')

    ax3.scatter(x= df.index, y=df['prediction'],color='red')
    ax3.xaxis.grid(True,alpha=0.3)
    ax3.set_ylabel('Predicted Direction ')

    fig.suptitle(details, fontsize=10)

    xtick_dates = pd.date_range(start = df.index[0], end = df.index[-1], freq='3M')
    plt.xticks(xtick_dates, [dtz.strftime('%Y-%m') for dtz in xtick_dates], rotation=88)

    fig.text(0.5, 0.04, 'Quarter Closing Dates', ha='center')

    plt.show()

Prediction for GM