我有以下資料集:
df.head(7)
Origin Dest Date Quantity
0 Atlanta LA 2021-09-09 1
1 Atlanta LA 2021-09-11 4
2 Atlanta Chicago 2021-09-16 1
3 Atlanta Seattle 2021-09-27 12
4 Seattle LA 2021-09-29 2
5 Seattle Atlanta 2021-09-13 2
6 Seattle Newark 2021-09-17 7
簡而言之,此表表示在給定日期從給定起點發送到給定目的地的專案數量(數量)。該表包含 1 個月的資料。該表是通過以下方式閱讀的:
shipments = pd.read_csv('shipments.csv', parse_dates=['Date'])
請注意,這是一個稀疏表:如果特定 (Origin,Dest,Date) 對的 Quantity=0,則該行不包含在表中。例如,在 2021 年 9 月 10 日,沒有任何物品從亞特蘭大發送到洛杉磯,該行不包含在資料中。
我想使用時間序列箱線圖和晶須圖來可視化這些資料。我的圖表的 x 軸應該顯示日期,數量應該在 y 軸上。箱線圖應該代表所有(起點-終點)對聚合的各個百分位數。
同樣,是否可以創建一個圖表,而不是每天,只在 x 軸上顯示周一至周日(因此顯示一周中每天的結果)?
為了生成缺少資料的行,我使用了以下代碼:
table = pd.pivot_table(data=shipments, index='Date', columns=['Origin','Dest'], values='Quantity', fill_value=0)
idx = pd.date_range('2021-09-06','2021-10-10')
table = table.reindex(idx,fill_value=0)
uj5u.com熱心網友回復:
您可以轉置table資料框,并將其用作sns.boxplot. 您可以為一周中的某一天創建一個類似的表格。請注意,有許多零,boxplot可能看起來有點奇怪。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# first create some test data, somewhat similar to the given data
N = 1000
cities = ['Atlanta', 'LA', 'Chicago', 'Seattle', 'Newark']
shipments = pd.DataFrame({'Origin': np.random.choice(cities, N),
'Dest': np.random.choice(cities, N),
'Date': np.random.choice(pd.date_range('2021-09-06', '2021-10-10'), N),
'Quantity': (np.random.uniform(1, 4, N) ** 3).astype(int)})
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15, 5), gridspec_kw={'width_ratios': [3, 1]})
# create boxplots for each day
table_month = pd.pivot_table(data=shipments, index='Date', columns=['Origin', 'Dest'], values='Quantity', fill_value=0)
idx = pd.date_range('2021-09-06', '2021-10-10')
table_month = table_month.reindex(idx, fill_value=0)
sns.boxplot(data=table_month.T, ax=ax1)
labels = [day.strftime('%d\n%b %Y') if i == 0 or day.day == 1 else day.strftime('%d')
for i, day in enumerate(table_month.index)]
ax1.set_xticklabels(labels)
# create boxplots for each day of the week
table_dow = pd.pivot_table(data=shipments, index=shipments['Date'].dt.dayofweek, columns=['Origin', 'Dest'],
values='Quantity', fill_value=0)
table_dow = table_dow.reindex(range(7), fill_value=0)
sns.boxplot(data=table_dow.T, ax=ax2)
labels = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']
ax2.set_xticklabels(labels)
ax2.set_xlabel('') # remove superfluous x label
fig.tight_layout()
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/428949.html
標籤:熊猫 matplotlib
