python从数据框中绘制几条曲线

时间:2017-03-12 10:35:29

标签: python pandas matplotlib plot

我试图在情节上绘制几个家电的温度。

数据来自下面的数据框df,我首先创建日期列作为索引。

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

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

plt.plot(df.index, [df.value for i in range(len(appliance)]
ax = df.plot()
ax.set_xlim(pd.Timestamp('2016-07-05'), pd.Timestamp('2015-11-30'))

ggplot对此更好吗?

我无法让这件作品

1 个答案:

答案 0 :(得分:1)

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

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')

使用matplotlib pyplot.plot()

import matplotlib.pyplot as plt

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

plt.plot(df1.index, df1["Value"].values, marker="o", label="Thermostat")
plt.plot(df2.index, df2["Value"].values, marker="o", label="Thermmeter")
plt.gcf().autofmt_xdate()
plt.legend()

使用pandas 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()