1

I have an excel sheet of retail gas prices from years 1990 to 2019. I successfully plotted a graph of their prices against the date(years). The x-axis was created on its own and its scaled to jump every 4 years. The Date is a datetime type and the Gas price is a float. my plot was created by writing:

date = dataset['Date']
price = dataset['U.S. All Grades All Formulations Retail Gasoline Prices (Dollars per Gallon)']

plt.plot_date(date, price, linestyle='solid')
plt.xlabel("Date")
plt.ylabel("Gaslone Price / Dollar Per Gallon")
plt.tight_layout()

Here is the gas prices graph I got so far.

Now I would to "zoom" into the picture and create another graph but I would like that part where there is a steep decline from around years 2007 to 2009.

I tried using plt.xlim but I'm not sure how to input my limits. Thank you.

5
  • Does this work plt.xlim(2007,2009) ? Commented Jan 3, 2020 at 15:08
  • @SaurabhPBhandari No. I get an empty graph. How can I clarify more? Should I upload a picture of my dataframe? Commented Jan 3, 2020 at 15:14
  • @SaurabhPBhandari ibb.co/rMsVhGX I hope this clarifies the problem. Thank you Commented Jan 3, 2020 at 15:21
  • Does this answer your question? How do I change the range of the x-axis with datetimes in matplotlib? Commented Jan 3, 2020 at 17:02
  • 1
    Specify the limits as datetime.datetime or numpy.datetime64 objects. I.e. ax.set_xlim(np.datetime64(‘2007-01-01’), np.datetime64(‘2009-12-31’)) Commented Jan 3, 2020 at 20:10

1 Answer 1

0

Coming to this waaaaaay after the fact, but since I just ran into this in the top of Google results while trying to do the same, I'll go ahead and answer. Assuming that your dates are of datatype DateTime (it looks like they are), you should be able to use the following:

plt.xlim(pd.to_datetime('2007-01-01'), pd.to_datetime('2009-12-31'))

The xlim() function takes two arguments, a left and a right boundary. These can be placed in a tuple (inside parenthesis), but even if you don't include them in a tuple, it seems that matplotlib will still figure it out. The use of pd.to_datetime is necessary to convert the date strings into a datetime object that can be checked against the datetime objects being used on the x-axis, so pyplot can identify where to draw the left and right boundaries. Without this conversion, pyplot would crash with an IndexError, because it would be trying to match a string to a non-string item (the DateTime x-axis objects).

In a scenario where you weren't needing to convert to datetime objects, you could simply pass values into the xlim() function without the conversion to datetime.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.