如何更改子图中线条的颜色? [英] How to change the color of lines within a subplot?

查看:58
本文介绍了如何更改子图中线条的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是为我的数据中的每一列及其相应的滚动平均值创建一个时间序列图.我希望子图中的线条颜色不同.例如,对于第二个子图中的gym 和rolling_mean_gym,线条的颜色应该是紫色和红色.我该怎么做?

My goal is to create a time series plot for each column in my data with their corresponding rolling mean. I'd like the color of the lines across subplots to be different. For example, for gym and rolling_mean_gym in the second subplot, the color of the lines should be purple and red. How do I do this?

当我在plot()中设置颜色选项时,它会同时更改原始数据图和滚动平均值图的颜色,这是不理想的.

When I set the color option inside plot(), it changes the color of both the raw data plot and the rolling mean plot, which is not ideal.

我通过使用以下代码计算时间序列各列的滚动平均值来创建以下图:

I created the plot below by calculating the rolling mean of each column of the time series using the following code:

# 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]);

推荐答案

一个选项是提供颜色列表: .plot(...,color = ['red','blue']).

One option is to provide a list of colors: .plot(..., color=['red', 'blue']).

Pandas plot() 方法只是围绕 matplotlib 绘图方法的一个薄包装.任何未使用的关键字参数都将传递给他们.

Pandas plot() method is just a thin wrapper around matplotlib plotting methods. Any non-consumed keyword argument will be passed on to them.

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']);

这篇关于如何更改子图中线条的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆