繁体   English   中英

如何绘制具有3个特征的折线图子图

[英]How to plot subplots of line chart with 3 features

我正在尝试从此数据框中绘制子图。

df:

cOne:    cTwo:      cThree:     Date:    
car      blue        other     2006-06-12 15:00:00
truck    yellow      other2    2004-05-19 17:00:00
car      red         other3    2012-05-28 09:00:00

我想为一周中的每一天(星期一,星期二...星期日)绘制一个单独的子图。 x轴应该是一天中的每个小时。 尽管这些行应表示“ cOne”,但y轴是每个“ cOne”在相应的小时和日期的发生次数。

谢谢。

我认为最简单的方法是使用pandas.DatetimeIndexdatetimes时间中提取星期几,并将其与您感兴趣的一系列选项(例如,“ ['car”,“ truck”])一起使用累积日期范围内每天每一小时的发生次数。 这是一个演示此方法的示例(使用一些随机生成的数据进行演示)

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
opts   = [['car', 'truck'],
         ['blue', 'yellow', 'red'],
         ['other', 'other2', 'other3']]
dates = pd.date_range('01-01-2000', '01-01-2001', freq='H')
cOne = list()
cTwo = list()
cThree = list()
n = len(dates)
for ii in range(n):
    cOne.append(opts[0][np.random.randint(0,2)])
    cTwo.append(opts[1][np.random.randint(0,3)])
    cThree.append(opts[2][np.random.randint(0,3)])

df = pd.DataFrame({'cOne': cOne,
                  'cTwo': cTwo,
                  'cThree': cThree,
                  'Date': dates})
df = df.set_index(pd.DatetimeIndex(pd.to_datetime(df['Date'])))
hours = df.index.hour
columnsTitles=["Date", "cOne", "cTwo", "cThree"]
df=df.reindex(columns=columnsTitles)

x = pd.date_range('00:00', '23:00', freq = 'H')
x = range(0,24,1)
rows = len(df.index)
col = df.columns
fig = plt.figure(figsize=(21,3*(len(col)-1)))
fig.suptitle("Hourly Occurence by Day of Week", y = 1)
for mm in range(1, len(col)):
    for ii in range(len(week)):
        y = [[0]*len(x) for i in range(len(opts[mm-1]))]
        for jj in range(rows):
            if dates[jj].dayofweek == ii:
                for kk in range(len(opts[mm-1])):
                    if df[col[mm]][jj] == opts[mm-1][kk]:
                        y[kk][hours[jj]] = y[kk][hours[jj]] + 1
                        break
        ax = fig.add_subplot(len(col)-1, len(week), ii + (mm - 1)*(len(week)) + 1)
        if mm == 1:
            ax.set_title(week[ii])
        for ll in range(len(opts[mm-1])):
            ax.plot(x, y[ll], linewidth=1, linestyle='-', alpha=0.7)
plt.show()

其输出是 按星期几每小时发生的次数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM