[英]Add different color markers by day of week to a Pandas time series plot
我使用自定義的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參數
如果有人有解決方案,請感激!
我看到用不同顏色標記繪制的線的唯一方法是將標記繪制為散點圖,然后再繪制線。 在這種情況下,我將用標記繪制日期-
然后在頂部繪制散點圖,如下所示:
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'))
另外,您可以通過僅使用標記的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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.