如何在matplotlib中使用一个数据框绘制两个图形?

时间:2017-05-18 10:46:28

标签: python matplotlib

我想通过重叠它们来绘制一个pandas数据帧(a)中的两个图形。

这是数据框(a)的一部分。

                       Temperature
DateTime
2017-05-01 07:20:00    49.15
2017-05-01 07:19:00    49.14
2017-05-01 07:18:00    49.15
2017-05-01 07:17:00    49.14
2017-05-01 07:16:00    49.14
2017-05-01 07:15:00    49.15
2017-05-01 07:14:00    49.15
2017-05-01 07:13:00    49.15
2017-05-01 07:12:00    49.16
2017-05-01 07:11:00    49.17
2017-05-01 07:10:00    49.18
2017-05-01 07:09:00    49.16
2017-05-01 07:08:00    49.15
2017-05-01 07:07:00    49.15
2017-05-01 07:06:00    49.16
2017-05-01 07:05:00    49.19
2017-05-01 07:04:00    49.19
2017-05-01 07:03:00    49.20
2017-05-01 07:02:00    49.21
2017-05-01 07:01:00    49.15

首先,我想将此图绘制为时间序列。其次,我想绘制满足一定条件的点。例如,我想绘制每个温度,该温度是+ - 5行范围内的最高值。下面显示了我为此条件所做的功能。

def HIGH(a, span):
    for m in range(span, len(a)-span):
        temp_df = a.iloc[m-span:m+span]

        if a.iloc[m] == pd.DataFrame.max(temp_df, axis=0):
            print(a.index.values[m])
            print(a.iloc[m])

>>> HIGH(a, 5)
2017-05-01T07:10:00.000000000
49.18

>>> matplotlib.pyplot.plot(a)
>>> matplotlib.pyplot.show()

显示下图,但如何标记该点(使用'rx'选项)?

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要从HIGH函数返回值并使用标记绘制它们。

import io
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


u = u"""DateTime;Temperature
2017-05-01 07:20:00;49.15
2017-05-01 07:19:00;49.14
2017-05-01 07:18:00;49.15
2017-05-01 07:17:00;49.14
2017-05-01 07:16:00;49.14
2017-05-01 07:15:00;49.15
2017-05-01 07:14:00;49.15
2017-05-01 07:13:00;49.15
2017-05-01 07:12:00;49.16
2017-05-01 07:11:00;49.17
2017-05-01 07:10:00;49.18
2017-05-01 07:09:00;49.16
2017-05-01 07:08:00;49.15
2017-05-01 07:07:00;49.15
2017-05-01 07:06:00;49.16
2017-05-01 07:05:00;49.19
2017-05-01 07:04:00;49.19
2017-05-01 07:03:00;49.20
2017-05-01 07:02:00;49.21
2017-05-01 07:01:00;49.15"""

data = io.StringIO(u)
df = pd.read_csv(data, sep=";", index_col=0)
df.index = pd.to_datetime(df.index)


def HIGH(a, span):
    x,y = [],[]
    for m in range(span, len(a)-span):
        temp_df = a.iloc[m-span:m+span]
        cur = float(pd.DataFrame.max(temp_df, axis=0))
        if float(a.iloc[m]) == cur:
            x.append( a.index.values[m] )
            y.append( float(a.iloc[m]) )
    return x,y

plt.plot(df)
x,y = HIGH(df,5)
plt.plot(x,y, marker="*", color="crimson", ls="", ms=15)
plt.show()

enter image description here