【问题标题】:Add different color markers by day of week to a Pandas time series plot按星期几向 Pandas 时间序列图添加不同的颜色标记
【发布时间】:2018-01-05 17:51:34
【问题描述】:

我用自定义的 x 轴制作了如下时间序列图:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.DataFrame({'points': np.random.randint(1,100, 61)}, 
index=pd.date_range(start='11-1-2017', end='12-31-2017', freq='D'))
df['dow'] = df.index.dayofweek

fig, ax = plt.subplots();
ax.plot_date(df.index, df.points, '-o')
ax.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=(0), interval=1))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('\n\n\n%b\n%Y'))

情节是这样的:

我真正想要的是让标记颜色在一周中的每一天(周一,周二...)都不同,所以我修改了上面的代码:

colors = dict(zip(df.dow.unique(), ['orange', 'yellow', 'green', 'blue', 'purple', 'black', 'red']))
ax.plot_date(df.index, df.points, '-o', color=df['dow'].apply(lambda x: colors[x]))

但结果是

ValueError: RGBA 参数无效

如果有人有解决方案,不胜感激!

【问题讨论】:

    标签: python pandas matplotlib timeserieschart


    【解决方案1】:

    我看到用不同颜色标记绘制线条的唯一方法是将标记绘制为散点图,然后绘制线条。在这种情况下,我会使用标记 - 绘制日期,然后在顶部绘制散点图,如下所示:

    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    df = pd.DataFrame({'points': np.random.randint(1,100, 61)}, 
    index=pd.date_range(start='11-1-2017', end='12-31-2017', freq='D'))
    df['dow'] = df.index.dayofweek
    colors = dict(zip(df.dow.unique(), ['orange', 'yellow', 'green', 'blue', 'purple', 'black', 'red']))
    
    
    fig, ax = plt.subplots();
    ax.plot_date(df.index, df.points, '-')
    ax.scatter(df.index, df.points, color=df.dow.map(lambda x: colors[x]))
    ax.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=(0), interval=1))
    ax.xaxis.set_minor_formatter(mdates.DateFormatter('%d\n%a'))
    ax.xaxis.grid(True, which="minor")
    ax.yaxis.grid()
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('\n\n\n%b\n%Y'))
    

    【讨论】:

      【解决方案2】:

      或者,您可以通过 plot 仅使用标记创建新的线条对象(线条样式为空)并循环浏览您的颜色列表。 plot 为您的线对象应用一种独特的颜色,因此需要创建额外的线对象或使用scatter,您可以在其中为创建的每个点分配颜色。

      fig, ax = plt.subplots()
      # create a line plot first
      ax.plot_date(df.index, df.points, '-')
      
      # Desired color list
      color_list = ['orange', 'yellow', 'green', 'blue', 'purple', 'black', 'red']
      
      # create additional line object by showing only marker of different colors
      for idc, d in enumerate(df.dow.unique()):
          this_dow = df.loc[df.dow == d, 'points']
          ax.plot_date(this_dow.index,this_dow, linestyle='', marker ='o', color=color_list[idc])
      
      # axis esthetics
      ax.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=(0), interval=1))
      ax.xaxis.set_minor_formatter(mdates.DateFormatter('%d\n%a'))
      ax.xaxis.grid(True, which="minor")
      ax.yaxis.grid()
      ax.xaxis.set_major_locator(mdates.MonthLocator())
      ax.xaxis.set_major_formatter(mdates.DateFormatter('\n\n\n%b\n%Y'))
      

      【讨论】:

        猜你喜欢
        • 2013-06-16
        • 2020-06-01
        • 2017-01-12
        • 2022-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多