0

I have a pandas Series with two columns, Index (of timestamps) and floats

screenshot of  Series

which I try to plot using Matplotlib as follows

s2.plot()

which gives me the following plot

enter image description here

now I want to format the x-axis to just show the timestamp in '%Y-%m-%d' format so I try

fig, ax = plt.subplots()
xdfmt = dates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(xdfmt)
ax.xaxis_date()
s2.plot()

which fails as follows

dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)

ValueError: ordinal must be >= 1

How should I format the x-axis to display legible x-axis labels?

Mike Mavor
  • 23
  • 1
  • 4
  • You need to use `plot_date()`. [docs](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot_date.html) – harvpan Apr 26 '18 at 19:48
  • If you want to format dates, the data needs to be dates first, not strings. – ImportanceOfBeingErnest Apr 26 '18 at 19:48
  • 1
    Also, rather than the screenshot, it is always a good idea to show/paste the data so that one can copy and reproduce the results that you are getting. [See here](https://stackoverflow.com/help/mcve) for more details. – harvpan Apr 26 '18 at 19:50
  • 1
    @HarvIpan matplotlib's `plot_date` is essentially the same as matplotlib's `plot` if the input are datetime objects. Here the OP uses the `plot` method of pandas, which is a bit different. There are however enough questions around showing how to plot dates with either pandas or matplotlib. – ImportanceOfBeingErnest Apr 26 '18 at 19:52
  • You are right. @ImportanceOfBeingErnest. I jumped the guns to comment, I guess. – harvpan Apr 26 '18 at 19:55
  • @ImportanceOfBeingErnest I had looked at the duplicate to which you linked but the `plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))` threw an error of ValueError: DateFormatter found a value of x=0, which is an illegal date. – Mike Mavor Apr 26 '18 at 20:04
  • As said you first need to convert your strings to dates for the dateformatter to be able to format them. As states above, you can of course provide a [mcve] of the issue which allows to see at which exact point your code fails. – ImportanceOfBeingErnest Apr 26 '18 at 20:08

0 Answers0