Pandas 数据框分组绘图
- 2025-02-27 09:06:00
- admin 原创
- 57
问题描述:
我有一个数据框,其结构如下:
Date ticker adj_close
0 2016-11-21 AAPL 111.730
1 2016-11-22 AAPL 111.800
2 2016-11-23 AAPL 111.230
3 2016-11-25 AAPL 111.790
4 2016-11-28 AAPL 111.570
...
8 2016-11-21 ACN 119.680
9 2016-11-22 ACN 119.480
10 2016-11-23 ACN 119.820
11 2016-11-25 ACN 120.740
...
我怎样才能根据股票行情绘制adj_close
图表Date
?
解决方案 1:
简单的情节,
你可以使用:
df.plot(x='Date',y='adj_close')
或者您可以预先设置索引Date
,然后很容易绘制您想要的列:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
如果您想要一个包含一个系列的ticker
图表
您需要先进行groupby:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
如果您想要一个包含单独子图的图表:
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
解决方案 2:
与上述 Julien 的回答类似,我成功做到了以下几点:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
如果您想在 matlab 中获得更多控制,此解决方案可能更有意义。
解决方案灵感来自:https ://stackoverflow.com/a/52526454/10521959
解决方案 3:
问题是,我如何根据股票代码绘制 adj_close 与日期的关系图?
.pivot
这可以通过使用或将数据框重塑为宽格式.groupby
,或通过使用 直接绘制现有的长格式数据框来实现seaborn
。
在下面的示例数据中,
'Date'
列有一个datetime64[ns] Dtype
。如果需要的话,转换
Dtype
一下pandas.to_datetime
。
已在
python 3.10
,pandas 1.4.2
,matplotlib 3.5.1
,测试seaborn 0.11.2
导入和样本数据
import pandas as pd
import pandas_datareader as web # for sample data; this can be installed with conda if using Anaconda, otherwise pip
import seaborn as sns
import matplotlib.pyplot as plt
# sample stock data, where .iloc[:, [5, 6]] selects only the 'Adj Close' and 'tkr' column
tickers = ['aapl', 'acn']
df = pd.concat((web.DataReader(ticker, data_source='yahoo', start='2020-01-01', end='2022-06-21')
.assign(ticker=ticker) for ticker in tickers)).iloc[:, [5, 6]]
# display(df.head())
Date Adj Close ticker
0 2020-01-02 73.785904 aapl
1 2020-01-03 73.068573 aapl
2 2020-01-06 73.650795 aapl
3 2020-01-07 73.304420 aapl
4 2020-01-08 74.483604 aapl
# display(df.tail())
Date Adj Close ticker
1239 2022-06-14 275.119995 acn
1240 2022-06-15 281.190002 acn
1241 2022-06-16 270.899994 acn
1242 2022-06-17 275.380005 acn
1243 2022-06-21 282.730011 acn
pandas.DataFrame.pivot
&pandas.DataFrame.plot
pandas
`matplotlib`以作为默认后端的绘图。重塑数据框,将其
pandas.DataFrame.pivot
从长格式转换为宽格式,并将数据框转换为正确的格式以进行绘图。.pivot
不聚合数据,因此如果每个指数、每个股票代码有超过 1 个观察值,则使用.pivot_table
添加
subplots=True
将产生一个带有两个子图的图形。
# reshape the long form data into a wide form
dfp = df.pivot(index='Date', columns='ticker', values='Adj Close')
# display(dfp.head())
ticker aapl acn
Date
2020-01-02 73.785904 203.171112
2020-01-03 73.068573 202.832764
2020-01-06 73.650795 201.508224
2020-01-07 73.304420 197.157654
2020-01-08 74.483604 197.544434
# plot
ax = dfp.plot(figsize=(11, 6))
使用
seaborn
,它接受长格式数据,因此不需要将数据框重塑为宽格式。seaborn
是一个高级 API,用于matplotlib
sns.lineplot
:轴级图
fig, ax = plt.subplots(figsize=(11, 6))
sns.lineplot(data=df, x='Date', y='Adj Close', hue='ticker', ax=ax)
sns.relplot
:图形级图
添加
row='ticker'
,或col='ticker'
,将生成一个包含两个子图的图形。
g = sns.relplot(kind='line', data=df, x='Date', y='Adj Close', hue='ticker', aspect=1.75)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD