mjp
mjp

Reputation: 1679

Setting xlim for Pandas DataFrame plot

I'm plotting a stacked bar plot from a Pandas DataFrame. The index dates are in datetime format and plot just fine. The issue I'm having is trying to set xlim values.

day_counts = {'a': count_a,
              'b': count_b,
              'c': count_c,
              'd': count_d}

df_days = pd.DataFrame(day_counts, index=date)

The variables count_a, .., count_d are lists of numbers and date is a list of datetime objects.

Plotting without an xlim parameter gives: enter image description here

Plotting with xlim attempt 1:

ax = df_days.plot(kind='bar', stacked=True,
                  xlim=[pd.Timestamp('2015-09-01'), pd.Timestamp('2016-01-01')])

Plotting with xlim attempt 2:

ax = df_days.plot(kind='bar', stacked=True)
ax.set_xlim(pd.Timestamp('2015-09-01'), pd.Timestamp('2016-01-01')) 

Plotting with xlim attempt 3:

ax = df_days.plot(kind='bar', stacked=True)
ax.set_xlim(datetime.datetime(2015,9,1),date[-1])

I would like to have the xlim command inside the main plot command if possible, the dataset is really big. Suggestions?

Upvotes: 4

Views: 15594

Answers (1)

Kyle
Kyle

Reputation: 2894

Per https://stackoverflow.com/a/31500017/4893407 the following should work:

ax.set_xlim(pd.Timestamp('2015-09-01'), pd.Timestamp('2016-01-01'))

Are you sure the index of your df is a DatetimeIndex? Does it have duplicates? Is it sorted? Unsorted DatetimeIndex will cause slice indexing with Timestamps to fail.

Upvotes: 3

Related Questions