Matplotlib fill_between

时间:2017-04-28 17:43:26

标签: python python-2.7 pandas matplotlib

我正在尝试将fill_between与pandas Series值一起使用,但它无效。 'DAY'字段是字符串日期格式,如'%Y-%m-%d'

df_tmp喜欢:

MEDIA_B2W  MEDIA_CONC  UPPER_BOUND  LOWER_BOUND     DAY
2017.48     2512.55       2811.0       1924.0       2017-01-01
1999.38     2512.55       2811.0       1924.0       2017-01-02
1930.89     2512.55       2811.0       1924.0       2017-01-03

df_tmp[['UPPER_BOUND','LOWER_BOUND','MEDIA_CONC','MEDIA_B2W','DAY']].plot(
                 x='DAY',ax=ax[0],grid=True,style=['r-','b-','y--','g-o'])

ax[0].fill_between(df_tmp.index,df_tmp['UPPER_BOUND'], df_tmp['LOWER_BOUND'],
                    facecolor='green', alpha=0.2, interpolate=True)

我想在上下界之间进行着色。 这是current plot

只是线条出现在图中。

1 个答案:

答案 0 :(得分:1)

此解决方法对x刻度使用df索引,然后交换时间序列。

df = df[['UPPER_BOUND','LOWER_BOUND','MEDIA_CONC','MEDIA_B2W','DAY']]

ax = df.plot(x=df.index, grid=True, style=['r-','b-','y--','g-o'])
ax.fill_between(df.index, df.LOWER_BOUND, df.UPPER_BOUND,
                facecolor='green', alpha=0.2, interpolate=True)

# replace index values with dates
ax.set_xticks(df.index)
ax.set_xticklabels(df.DAY)

# cosmetic adjustments
pad = 700
ax.set_ylim([df.LOWER_BOUND.min()-pad, df.UPPER_BOUND.max()+pad])

fill-between time series

或者,您可以将DAY设置为df.index

df.DAY = pd.to_datetime(df.DAY)
df = df.set_index('DAY')

ax = df.plot(grid=True, style=['r-','b-','y--','g-o'])
ax.fill_between(df.index, df.LOWER_BOUND, df.UPPER_BOUND,
                facecolor='green', alpha=0.2, interpolate=True)

# cosmetic adjustments
pad = 700
_=ax.set_ylim([df.LOWER_BOUND.min()-pad, df.UPPER_BOUND.max()+pad])

fill between 2