如何使用python在两个数据(日期和X1)附加一个列表的同时绘制图形

问题描述 投票:0回答:2

我有一个包含日期,时间和一个输入列的数据集。在这里,我通过一小时一小时的减少来编写输入列7值的代码。(日期,值)然后,我将该数据放入一个列表中。之后,我想根据列表的值和日期绘制图形。但是我无法绘制图形,它什么也不显示。谁能帮我解决这个问题?

>>> x=[]
>>> some code is running here to decrease the value of 7
>>> x.append({'date':next_record_time, 'X1':new_X1})

>>> print(x)
[{'date': Timestamp('2018-06-08 09:30:00'), 'X1': 7},
 {'date': Timestamp('2018-06-08 10:30:00'), 'X1': 6.5},
 {'date': Timestamp('2018-06-08 11:30:00'), 'X1': 6},
 {'date': Timestamp('2018-06-08 12:30:00'), 'X1': 5.5},
 {'date': Timestamp('2018-06-08 13:30:00'), 'X1': 5}]

如果我们分开它:

>>> for i in x:
>>>    print(i['date'], "\t\t", i['X1'])
2018-06-08 09:30:00          7
2018-06-08 10:30:00          6.5
2018-06-08 11:30:00          6
2018-06-08 12:30:00          5.5
2018-06-08 13:30:00          5
2018-06-08 14:30:00          4.5
2018-06-08 15:30:00          4

然后,我想使用此值X1和日期绘制图形。然后,我编写了代码,并在没有图形的情况下显示了它:

plt.plot(['date'], ['X1'])
plt.show()

图:enter image description here

在将i添加到情节之后:

plt.plot(i['date'], i['X1'])
plt.show()

获得输出:

enter image description here

python for-loop matplotlib time
2个回答
0
投票

与其创建字典列表,不如创建一个包含两个列表的字典可能更好:

>>> my_data = {'dates': [], 'X1': []}
>>> some code is running here to decrease the value of 7
>>> my_data['dates'].append(next_record_time)
>>> my_data['X1'].append(new_X1)

>>> print(my_data)
{'dates': [Timestamp('2018-06-08 09:30:00'),
           Timestamp('2018-06-08 10:30:00'),
           Timestamp('2018-06-08 11:30:00'),
           Timestamp('2018-06-08 12:30:00'),
           Timestamp('2018-06-08 13:30:00'),
           Timestamp('2018-06-08 14:30:00'),
           Timestamp('2018-06-08 15:30:00')],
 'X1': [7, 6.5, 6, 5.5, 5, 4.5, 4]}

然后您可以按照预期的方式进行绘图:

plt.plot(my_data['dates'], my_data['X1'])
plt.show()

0
投票

您可以做:

pd.DataFrame(x).plot(x='date', y='X1')

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.