[英]How to plot subplots of line chart with 3 features
I am trying to plot subplots from this dataframe. 我正在尝试从此数据框中绘制子图。
df: 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
I want to plot an individual sub-plot for each day of the week (Monday, Tuesday...Sunday). 我想为一周中的每一天(星期一,星期二...星期日)绘制一个单独的子图。 The x-axis should be each hour of the day.
x轴应该是一天中的每个小时。 While the lines should represent 'cOne', the y-axis being the counts of the occurrences for each 'cOne' for the respective hour and day.
尽管这些行应表示“ cOne”,但y轴是每个“ cOne”在相应的小时和日期的发生次数。
Thanks. 谢谢。
I believe the easiest way to accomplish is to use pandas.DatetimeIndex
to extract the day of week from the datetimes
and use that along with an array of the options you are interested in (ie `['car', 'truck']) to accumulate the occurrence for each hour within each day over the date range. 我认为最简单的方法是使用
pandas.DatetimeIndex
从datetimes
时间中提取星期几,并将其与您感兴趣的一系列选项(例如,“ ['car”,“ truck”])一起使用累积日期范围内每天每一小时的发生次数。 Here is an example which demonstrates this approach (using some randomly generated data for demonstration) 这是一个演示此方法的示例(使用一些随机生成的数据进行演示)
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.