brunormoreira
brunormoreira

Reputation: 248

Matplotlib fill_between

I'm trying to use fill_between with a pandas Series values but it's not working. The 'DAY' field is string date format like '%Y-%m-%d'.

df_tmp like:

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)

I would like to color between the upper and lower bound. This is the current plot

Just the lines appear in the plot.

Upvotes: 0

Views: 471

Answers (1)

andrew_reece
andrew_reece

Reputation: 21264

This workaround uses df indices for x ticks, and then swaps for the time series.

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

Alternately, you can set DAY as 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

Upvotes: 1

Related Questions