如何绘制三要素折线图子图

2024-05-16 00:05:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从这个数据帧中绘制子图。你知道吗

测向:

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轴应该是一天中的每一小时。虽然这些线应该表示“圆锥体”,但y轴是每个“圆锥体”在相应的小时和天内的发生次数。你知道吗

谢谢。你知道吗


Tags: 数据date绘制blueredcarother小时
1条回答
网友
1楼 · 发布于 2024-05-16 00:05:01

我认为最简单的方法是使用^{}datetimes中提取一周中的某一天,并将其与您感兴趣的一系列选项(即“['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()

其输出为 Hourly Occurrence by Day of Week

相关问题 更多 >