【问题标题】:python plot several curves from dataframepython从数据框中绘制几条曲线
【发布时间】:2017-03-12 21:08:18
【问题描述】:

我正在尝试在一个绘图上绘制多个电器的温度。

数据来自下面的dataframe 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 条曲线:一条是温度计的温度,另一条是恒温器的温度,有 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 更适合这个吗?

我无法做到这一点

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案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()
    

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

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2021-07-29
      • 2012-06-16
      • 2021-12-10
      相关资源
      最近更新 更多