Skip to content
Advertisement

How to label milliseconds axis with datetime labels in matplotlib

I’ve got a sort of timeline plot. I’m drawing rectangles all over it, which is easy to do when time is in milliseconds. But then the x axis labels come out numerical, and I’d rather they be dates. I can convert my timestamps with df['timestamp'] = pandas.to_datetime(df['timestamp']) to fix the x axis labels, but then my rectangle drawing math breaks, because I can’t subtract milliseconds from a datetime like rect = [(t - 59000, h - 0.4), (t - 59000, h + 0.4), (t, h + 0.4), (t, h - 0.4), (t - 59000, h - 0.4)]; bars.append(rect); bars = PolyCollection(bars)

I think it would be easiest to just change the way my axis is labeled. How can I make it quit trying to plot massively long numbers and instead plot pretty date strings?

enter image description here

I just want to show the x axis labels as datetimes instead of these horribly unreadable numbers.

JavaScript

Here is some example data used to generate the plot:

JavaScript

Advertisement

Answer

Alright, great! I was able to reproduce your code and I added a couple of lines to get the outcome you are looking for @PavelKomarov

JavaScript

The 2 extra lines I added were:

JavaScript

The timestamps on the xaxis were down to the milliseconds so I formatted them to be in YYYY/MM/DD you can change the format using this.

Let me know if this is what you were looking for.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement