Python 使用Matplotlib 绘制图表

一、使用数据格式如下:

              id   timestamp      amount  ...       low      open           vol
0              1  1512999720   14.357200  ...  16049.70  16103.94  2.307250e+05
1              2  1513017720    2.078600  ...  16419.05  16458.97  3.417360e+04
2              3  1513089840   10.304860  ...  16240.00  16253.78  1.674319e+05
3              4  1512999900    3.341600  ...  16020.18  16054.65  5.361513e+04

二、 使用timestamp 作为索引, 作为x轴,删除原先索引,处理后的数据格式如下:

timestamp        atr   
1570666740   204.89
1568509440  1752.06
1572698040  1047.71
1572068820   386.34
1567377060   168.32
1571673420  1609.35

三、 代码如下:

if __name__ == '__main__':
    try:
        dw = pd.read_csv("btc.csv")
        print(dw)
        dw = dw[10:]
        dw.index = range(len(dw))
        # 使用ta工具,生成atr 
        dw['atr'] = ta.ATR(dw.high.values, dw.low.values, dw.close.values, timeperiod=1)
        # 删除dw中为na数据
        dw = dw.dropna(axis=0, how='any')
        dw = dw.dropna(axis=1, how='any')
        dw['di'] = dw.close.diff(-1)
        print(dw['atr'])
        dw = dw[1000000:]
        print("显示结果")
        dw = dw[['atr', 'timestamp']]
        print(dw)
        # 设置 timestamp为索引,替换以前的。
        dw.set_index('timestamp', inplace=True)
        print(dw)
        l_time = dw.index.to_list()
        print(l_time)
         # X坐标,将str类型的数据转换为datetime.date类型的数据,作为x坐标
        xs = [pd.to_datetime(d, utc=True, unit='s').tz_convert('Asia/Shanghai') for d in l_time]
        l_bank = dw['atr'].to_list()
        plt.plot(xs, l_bank, 'r', linewidth=1)
        plt.rc('x', labelsize=10)
        plt.rc('y', labelsize=10)
        plt.xticks(rotation=90)
        plt.close()
        plt.show()
    except:
        print(traceback.format_exc())

遇到的问题:

一、

问题描述:

ValueError: view limit minimum -1 is less than 1 and is an invalid Matplotlib date value.

答案:

在plot或者plt.show()之前加一句“plt.close()”即可;

原因:

将plt配置为更远的时间序列,然后在重新运行脚本时使用它,plt自己并不会在下一次使用时将清除之前的值,所以需要手动清除。

二、

问题描述:

刚开始使用str作为图表的x轴,报错;后来使用date依旧报错,如下:

   AttributeError: 'DataFrame' object has no attribute 'date'

使用时间作为,索引,解决问题;

猜你喜欢

转载自blog.csdn.net/wind1_rain/article/details/108590812