python从datafram绘制多条曲线

2024-06-26 01:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在一个图上画出几个电器的温度。在

数据来自下面的dataframedf,我首先创建date列作为索引。在

df=df.set_index('Date')

Date                  Appliance      Value (degrees)
2016-07-05 03:00:00   Thermometer    22
2016-08-06 16:00:00   Thermometer .  19
2016-12-07 21:00:00 . Thermometer .  25
2016-19-08 23:00:00 . Thermostat .   21
2016-25-09 06:00:00 . Thermostat .   20
2016-12-10 21:00:00 . Thermometer .  18
2016-10-11 21:00:00 . Thermostat .   21
2016-10-12 04:00:00 . Thermometer .  20
2017-01-01 07:00:00 . Thermostat .   19
2017-01-02 07:00:00 . Thermometer .  23

我们希望能够显示两个曲线:一个是温度计的温度,另一个是恒温器的温度,随着时间的推移,有两种不同的颜色。在

^{pr2}$

ggplot更好吗?在

我做不到


Tags: 数据dfdateindexvalue温度曲线degrees
1条回答
网友
1楼 · 发布于 2024-06-26 01:33:31

当然有几种绘制数据的方法。
假设我们有这样一个数据帧

import pandas as pd

dates = ["2016-07-05 03:00:00", "2016-08-06 16:00:00", "2016-12-07 21:00:00", 
         "2016-19-08 23:00:00", "2016-25-09 06:00:00", "2016-12-10 21:00:00", 
         "2016-10-11 21:00:00", "2016-10-12 04:00:00", "2017-01-01 07:00:00", 
         "2017-01-02 07:00:00"]       
app = ["Thermometer","Thermometer","Thermometer","Thermostat","Thermostat","Thermometer",
       "Thermostat","Thermometer","Thermostat","Thermometer"]     
values = [22,19,25,21,20,18,21,20,19,23]  
df = pd.DataFrame({"Date" : dates, "Appliance" : app, "Value":values})
df.Date = pd.to_datetime(df['Date'], format='%Y-%d-%m %H:%M:%S')  
df=df.set_index('Date')

使用matplotlibpyplot.plot()

^{pr2}$

使用熊猫DataFrame.plot()

df1 = df[df["Appliance"] == "Thermostat"]
df2 = df[df["Appliance"] == "Thermometer"]

ax = df1.plot(y="Value", label="Thermostat")
df2.plot(y="Value", ax=ax, label="Thermometer")
ax.legend()

相关问题 更多 >