2 回答

TA貢獻1789條經(jīng)驗 獲得超8個贊
優(yōu)雅的解決方案是:
將DataFrame 中的Dates列設置為索引。
創(chuàng)建一個具有所需數(shù)量的子圖(在您的情況下為 4)的圖形,調(diào)用plt.subplots。
從 DataFrame 中繪制一個圖,傳遞:
ax -子圖的ax結(jié)果(這里是Axes對象的數(shù)組 ,而不是單個Axes),
subplots=True - 在單獨的子圖中繪制每一列。
執(zhí)行此操作的代碼是:
fig, a = plt.subplots(2, 2, figsize=(12, 6), tight_layout=True)
df.plot(ax=a, subplots=True, rot=60);
為了測試上面的代碼,我創(chuàng)建了以下 DataFrame:
np.random.seed(1)
ind = pd.date_range('2005-01-01', '2006-12-31', freq='7D')
df = pd.DataFrame(np.random.rand(ind.size, 4),
index=ind, columns=['ES1', 'Z 1', 'VG1', 'NK1'])
并得到以下圖片:
由于我的測試數(shù)據(jù)是隨機的,我假設“7天”頻率,以使圖片不會太“混亂”。對于真實數(shù)據(jù),請考慮使用“7D”頻率和mean()聚合函數(shù)進行重采樣。

TA貢獻1856條經(jīng)驗 獲得超5個贊
我認為更簡潔的選擇是不要制作許多數(shù)據(jù)幀,這會造成不必要的工作和復雜性。
繪制數(shù)據(jù)就是為繪圖 API 塑造數(shù)據(jù)框
在這種情況下,更好的選擇是使用 .dataframe 將寬格式轉(zhuǎn)換為長(整齊)格式
.melt
。這會將所有標簽放在一列中,并將值放在另一列中
使用,它可以從長格式的數(shù)據(jù)幀?
seaborn.relplot
創(chuàng)建。FacetGrid
seaborn
是 的高級 API?matplotlib
,使繪圖變得更加容易。
如果數(shù)據(jù)框包含許多股票,但只繪制少數(shù)股票,則可以使用布爾索引來選擇它們
fig, a = plt.subplots(2, 2, figsize=(12, 6), tight_layout=True)
df.plot(ax=a, subplots=True, rot=60);
為了測試上面的代碼,我創(chuàng)建了以下 DataFrame:
np.random.seed(1)
ind = pd.date_range('2005-01-01', '2006-12-31', freq='7D')
df = pd.DataFrame(np.random.rand(ind.size, 4),
? ? index=ind, columns=['ES1', 'Z 1', 'VG1', 'NK1'])
并得到以下圖片:
我在這里做錯了什么?
當前的實現(xiàn)效率低下,有許多不正確的方法調(diào)用和未定義的變量。
如果需要,必須為每個子圖顯示圖例。
Date
沒有定義為x = Date
y2 = Notes
:Notes
未定義.line
不是plt
方法并導致AttributeError
;?它應該是plt.plot
y1 - y4
是 DataFrame,但傳遞給 y 軸的繪圖方法,這會導致TypeError: unhashable type: 'numpy.ndarray'
;?一列應作為 傳遞y
。.legends
不是一種方法;它是.legend
fig, a = plt.subplots(2, 2, figsize=(12, 6), tight_layout=True)
df.plot(ax=a, subplots=True, rot=60);
為了測試上面的代碼,我創(chuàng)建了以下 DataFrame:
np.random.seed(1)
ind = pd.date_range('2005-01-01', '2006-12-31', freq='7D')
df = pd.DataFrame(np.random.rand(ind.size, 4),
? ? index=ind, columns=['ES1', 'Z 1', 'VG1', 'NK1'])
并得到以下圖片:
添加回答
舉報