1

I am trying to improve the x-axis format on a bar chart of a time series with a lot of data. By default Matplotlib adds a date label for each data, looking like this:

import pandas as pd
import pandas_datareader as pdr
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

AAPL = pdr.DataReader("AAPL", 'yahoo', "2020-01-01")["Adj Close"]

fig, ax = plt.subplots()
AAPL.plot(kind="bar", figsize=(15,6), grid=True, ax=ax)
plt.show()

enter image description here

I also tried Matplotlib.dates (mdates) and then add format (year-month) and got a better display, but the problem arose that the date values ​​are changed to the year 1970.

fig, ax = plt.subplots()
AAPL.plot(kind="bar", figsize=(15,6), grid=True, ax=ax)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.get_xaxis().set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.show()

enter image description here

Greetings and thanks

Marcelo
  • 133
  • 1
  • 7
  • Hi, can you please share some data? – My Work Dec 12 '21 at 14:06
  • The data used is automatically downloaded with this command AAPL = pdr.DataReader("AAPL", 'yahoo', "2020-01-01")["Adj Close"] – Marcelo Dec 12 '21 at 14:11
  • Does this answer your question? [Matplotlib fix axis - too many dates](https://stackoverflow.com/questions/48090043/matplotlib-fix-axis-too-many-dates) – Jody Klymak Dec 12 '21 at 15:53
  • You need to convert the dates to datetime objects. – Jody Klymak Dec 12 '21 at 15:54
  • Thank you Jody. But the DF.index is dtype='datetime64[ns]', name='Date', length=491, freq=None – Marcelo Dec 13 '21 at 13:06
  • good answer to this question here: https://stackoverflow.com/questions/47965026/why-is-my-date-axis-formatting-broken-when-plotting-with-pandas-built-in-plot-c – Marcelo Mar 09 '22 at 14:26

0 Answers0