2

I'm trying to plot two data series:

  • day of the year (X-axis): ['2019-01-01', '2019-01-02', ...]
  • hour of sunrise (Y-axis): ['07:04', '07:03', ...]

But matplotlib is getting me crazy… here's the plot of a subset (ax.plot(datelist[130:230], hourlist[130:230], label='sunrise')):

example plot

As you can see, the Y-axis decrease from '03:57' to '03:33' and, then, suddenly start to increase up to '04:26'. That's non-sense to me.

Can you help me fixing that ?

Bonus points if you tell me how to show a decent scale on both axis (i.e. 00:00 – 24:00 equally spaced by 1 hour with minor ticks; and a list of chosen dates for the X-axis).

Thank you in advance!

4
  • 5
    You need to convert your strings to datetime objects first. (Otherwise, matplotlib cannot know that "2019-01-01" is a date.) Commented Aug 7, 2019 at 16:05
  • Thank you, that helped a lot. I had to force a date for the Y-axis's values, but that's ok. Commented Aug 7, 2019 at 16:20
  • Try with a conversion to timedelta for the Y axis so you don't need to force a date. I've never tried myself but I think shoud work too. Commented Aug 7, 2019 at 16:25
  • @Valentino No, matplotlib requires dates (but one can use an arbitrary date if only times are desired) Commented Aug 7, 2019 at 16:40

2 Answers 2

1

So, thanks to @ImportanceOfBeingErnest's insight, I managed to make it work by converting both data series to Python's datetime.datetime objects, but that wasn't enough.

In order to be properly plotted, the Y-values needed to also have the same date (with a fixed reference date just for plotting purposes).

For the chart's scale I've found the matplotlib.dates module which happens to contains useful Formatters and Locators for the axis's attributes.

In order to get a full 24 hours range for the Y-axis I've used:

ax.set_ylim([datetime.datetime(2019, 1, 1), datetime.datetime(2019, 1, 2)])
ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.yaxis.set_major_locator(HourLocator())

The overall result (with some additions) seems good enough for now (even if I have to fix the UTC's offsets): result chart

Thank you again!

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

Comments

0

What type of variables did you use? You probably used strings in datelist and hourlist. Therefore when you plot them, matplotlib doesn't sort the lists. You need to convert your values to the correct object type, and then you would be able to plot correctly.

For example: If I plot the list ['c','a','b'] in the y values, then my y axis would be: c, then a, then b.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.