Pol*_*enn 7 python matplotlib pandas
我的目标是为数据中的每一列及其相应的滚动平均值创建时间序列图。我希望子图之间的线条颜色不同。例如,对于第二个子图中的gym 和rolling_mean_gym,线条的颜色应为紫色和红色。我该怎么做呢?
当我在plot()中设置颜色选项时,它会更改原始数据图和滚动平均图的颜色,这并不理想。
我通过使用以下代码计算时间序列每列的滚动平均值来创建下图:
# calculate rolling mean
def rolling_mean(col):
rolling_mean_col = 'rolling_mean_{}'.format(col)
df[rolling_mean_col] = df[col].rolling(12).mean()
# create rolling mean columns
cols = ['diet', 'gym', 'finance']
for col in cols:
rolling_mean(col)
# plot data in subplots
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(13,10));
df[['diet', 'rolling_mean_diet']].plot(ax=axes[0]);
df[['gym', 'rolling_mean_gym']].plot(ax=axes[1]);
df[['finance', 'rolling_mean_finance']].plot(ax=axes[2]);
Run Code Online (Sandbox Code Playgroud)
一种选择是提供颜色列表:.plot(..., color=['red', 'blue'])。
Pandasplot()方法只是 matplotlib 绘图方法的一个薄包装。任何未使用的关键字参数都将传递给它们。
df = pd.DataFrame()
df['diet'] = np.random.random_sample(100)
df['rolling_mean_diet'] = np.random.random_sample(100) / 10 + 0.5
df['gym'] = np.random.random_sample(100)
df['rolling_mean_gym'] = np.random.random_sample(100) / 10 + 0.5
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(13,10));
df[['diet', 'rolling_mean_diet']].plot(ax=axes[0], color=['red', 'green']);
df[['gym', 'rolling_mean_gym']].plot(ax=axes[1], color=['purple', 'red']);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27025 次 |
| 最近记录: |