![](/img/trans.png)
[英]Plotly: How to plot a bar & line chart combined with a bar chart as subplots?
[英]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.DatetimeIndex
從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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.