terte 发表于 2018-4-9 13:21:04

python画时间序列散点图

在运维管理中,经常遇到时间序列的数据,比如网卡流量、在线用户数、并发连接数,等等。用散点图可以直观的查看数据的分布情况。

matplotlib模块的pyplot有画散点图的函数,但是该函数要求x轴是数字类型。pandas的plot函数里,散点图类型'scatter'也要求数字型的,用时间类型的会报错。在搜索阅读了几十篇网文后,摸索出画散点图的简单办法。可以使用pyplot的plot_date()画散点图。

下面是完整的python代码:

      # -*- coding: utf-8 -*-
      """
      speed1219.csv data file format:
      dtime,speed
      2017-12-19 10:33:30,803
      2017-12-19 10:35:29,1008
      2017-12-19 10:36:04,1016
      2017-12-19 10:37:32,984
      2017-12-19 10:38:06,1008
      """
      import pandas as pd
      import matplotlib.pyplot as plt
      from matplotlib.dates import AutoDateLocator, DateFormatter

      df = pd.read_csv('d:/speed1219.csv',parse_dates=['dtime'])
      plt.plot_date(df.dtime, df.speed, fmt='b.')

      ax = plt.gca()
      ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d %H:%M'))#设置时间显示格式
      ax.xaxis.set_major_locator(AutoDateLocator(maxticks=24))       #设置时间间隔

      plt.xticks(rotation=90, ha='center')
      label = ['speedpoint']
      plt.legend(label, loc='upper right')

      plt.grid()

      ax.set_title(u'传输速度', fontproperties='SimHei',fontsize=14)
      ax.set_xlabel('dtime')
      ax.set_ylabel('Speed(KB/s)')

      plt.show()

结果图如下,从图中看出,传输速度在1MB/s左右,十点半之前、下午四点前后没有数据传输。

如果不要求美观,可以把ax开始的行删掉。只保留下面几行代码:

      df = pd.read_csv('d:/speed1219.csv',parse_dates=['dtime'])
      plt.plot_date(df.dtime, df.speed, fmt='b.')
      plt.xticks(rotation=90, ha='center')
      plt.grid()
      plt.show()

页: [1]
查看完整版本: python画时间序列散点图