【问题标题】:Plot dataframe with datetime index使用日期时间索引绘制数据框
【发布时间】:2017-10-04 03:33:33
【问题描述】:
            is_avail   valu data_source
2015-08-07     False  0.282    source_a
2015-08-23     False  0.296    source_a
2015-09-08     False  0.433    source_a
2015-10-01      True  0.169    source_a
2015-10-10      True  0.160    source_a
2015-11-02     False  0.179    source_a
2016-03-09     False  0.557    source_a
2016-04-26     False  0.770    source_a
2016-05-05     False  0.826    source_a
2016-05-12     False  0.826    source_a
2016-05-28     False  0.747    source_a
2016-06-06     False  0.796    source_a
2016-07-31     False  0.322    source_a
2016-08-25      True  0.136    source_a
2016-09-10     False  0.180    source_a
2016-11-13     False  0.492    source_a
2016-12-15      True  0.124    source_a
2016-12-31     False  0.533    source_a
2017-03-28     False  0.524    source_a
2015-06-27      True  0.038    source_b
2015-07-30      True  0.035    source_b
2015-08-06     False  0.205    source_b
2015-08-09     False  0.241    source_b
2015-08-16      True  0.025    source_b
2015-08-19      True  0.092    source_b
2015-08-26     False  0.264    source_b
2015-08-29     False  0.312    source_b

我想在上面的数据框中绘制valu 列,当is_avail 为真或假时,source_a 行和source_b 行使用单独的线图和单独的颜色。目前,我正在这样做:

df['valu'].plot()

但是,这会将所有内容显示为单线图。如何达到上述目标?

【问题讨论】:

    标签: python pandas plot


    【解决方案1】:

    解决方案不是那么简单,但这很有效。

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates 
    
    df = df.sort_index()
    
    fig, ax = plt.subplots()
    for k,g in df.groupby(['is_avail','data_source'])['valu']:
        ax.plot_date(pd.to_datetime(g.index),g,'v-',label="{}, {}".format(*k))
    
    ax.xaxis.set_major_locator(mdates.MonthLocator(interval=3))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b\n%Y'))
    ax.legend()
    plt.show()
    

    结果:

    【讨论】:

      【解决方案2】:

      这个怎么样?假设您的数据在数据框中df

      import pandas as pd
      df.is_avail = df.is_avail.astype('str')
      grouped = df.groupby(['data_source','is_avail'])
      
      fig, ax = plt.subplots()
      for lab, gr in grouped:
          gr.valu.plot(ax=ax, label = lab)
      plt.legend()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-11
        • 2018-08-24
        • 1970-01-01
        • 2021-11-29
        • 2017-11-23
        • 2015-11-23
        • 1970-01-01
        • 2013-10-20
        相关资源
        最近更新 更多