在1个窗口中绘制2个图形(python)

时间:2014-07-31 02:03:51

标签: python time graph plot

如何在同一个地块中绘制两条线?下面的代码是我尝试这样做但它没有用。 '温度'是我添加的新变量

     (2nd EDITED )

    from datetime import datetime
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import numpy as np
    from scipy.stats import mode
    import re
    linematchregex = re.compile('(\d+/\d+/\d+ \d+:\d+),(\d+\.\d+),(\d+\.\d+)')

    startTime = datetime.strptime(raw_input('please enter start time in format like 21/7/2014 0:00 :'), '%d/%m/%Y %H:%M')
    endTime   = datetime.strptime(raw_input('please enter end time in format like 22/7/2014 23:57 :') , '%d/%m/%Y %H:%M')

    with open(r'data.txt', 'r') as strm:
        strm.next() #skip first line
        t, y, temp = zip(*[p for line in strm for p in linematchregex.findall(line)])
    t = [datetime.strptime(x, '%d/%m/%Y %H:%M') for x in t ]
    temp = [float(x) for i,x in enumerate(temp) if startTime<=t[i]<=endTime]
    y = [float(x) for i,x in enumerate(y) if startTime<=t[i]<=endTime]

    t = [x for x in t if startTime<=x<=endTime]
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1, axisbg='white')
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    ax1.plot(t, y, 'c', linewidth=3.3)
    ax1.plot(t, temp)
    plt.show()

我的程序可以使用辐照度绘制TimeStamp,但我如何绘制下面的所有列 时间与光辉 &安培; 温度时间

(EDITED)

TimeStamp,Irradiance,Ambient_Temperature
21/7/2014 12:00:06 AM,0.66,29.16
21/7/2014 12:00:20 AM,0.71,29.16
21/7/2014 12:00:34 AM,0.65,29.17
21/7/2014 12:00:48 AM,0.67,29.17
21/7/2014 12:01:08 AM,0.58,29.17
21/7/2014 12:01:23 AM,0.54,29.18
21/7/2014 12:01:37 AM,0.63,29.17
21/7/2014 12:01:52 AM,0.65,29.16
21/7/2014 12:02:07 AM,0.64,29.16
21/7/2014 12:02:22 AM,0.63,29.18
21/7/2014 12:02:36 AM,0.63,29.16
21/7/2014 12:02:50 AM,0.64,29.17
21/7/2014 12:03:04 AM,0.62,29.19
21/7/2014 12:03:24 AM,0.64,29.21

1 个答案:

答案 0 :(得分:1)

如果要在绘图中创建另一个子图。试试这个,

fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1, axisbg='white')
ax2 = fig.add_subplot(1, 2, 2, axisbg='white')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))
ax1.plot(t, y, 'c', linewidth=3.3)
ax2.plot(t, temp)

方法add_subplot添加了一个子图。前两个参数给出行数和列数,第三个参数表示要创建的1x2矩阵中的哪个子图。上面的代码将在左侧和右侧创建一个子图。如果你想要一个在另一个之上,你可以在两次调用add_subplot时反转前两个参数。

另一个问题是(尽我所知)创建temp时会出现错误,

temp = [float(x) for i,x in enumerate(y) if startTime<=t[i]<=endTime]

应该是

temp = [float(x) for i,x in enumerate(temp) if startTime<=t[i]<=endTime]

如果您希望在同一组轴上使用两个图,则原始代码仅适用于上述更改。如果您希望在图例中标记线条,您也可以通过将绘图命令更改为

来实现
ax1.plot(t, y, 'c', linewidth=3.3, label="Irradiance")
ax1.plot(t, temp, label="Temperature")
plt.legend()