【问题标题】:How to change the color of lines within a subplot?如何更改子图中线条的颜色?
【发布时间】:2018-02-09 05:35:27
【问题描述】:

我的目标是为我的数据中的每一列创建一个时间序列图,并使用它们对应的滚动平均值。我希望跨子图的线条颜色不同。例如,对于第二个子图中的 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]);

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

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

    Pandas plot() 方法只是 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']);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      相关资源
      最近更新 更多