Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show date and time on x axis in matplotlib

I would like to assign for x axis in matplotlib plot full date with time but with autoscale I could get only times or dates but not both. Following code:

import matplotlib.pyplot as plt
import pandas as pd

times = pd.date_range('2015-10-06', periods=500, freq='10min')

fig, ax = plt.subplots(1)
fig.autofmt_xdate()
plt.plot(times, range(times.size))
plt.show()

And on x axis I get only times without any dates so it's hard to distinct measurements.

I think that it's some option in matplotlib in matplotlib.dates.AutoDateFormatter but I couldn't find any one that could allow me to change that autoscale.

enter image description here

like image 730
Anton Protopopov Avatar asked Oct 06 '15 14:10

Anton Protopopov


People also ask

How to plot dates on the x-axis with Python's Matplotlib?

Plotting dates on the X-axis with Python's Matplotlib. Using Pandas, we can create a dataframe and can set the index for datetime. Using gcf ().autofmt_xdate (), we will adjust the date on the X-axis.

How do I plot a time series in Matplotlib?

You can use the following syntax to plot a time series in Matplotlib: import matplotlib. pyplot as plt plt. plot (df. x , df. y ) This makes the assumption that the x variable is of the class datetime.datetime() .

How to change the format of a date on a plot axis?

Luckily, matplotlib provides functionality to change the format of a date on a plot axis using the DateFormatter module, so that you can customize the look of your labels without having to rotate them. You can also add a character between the "%X %X" to specify how the values are connected in the label such as - or \.

Does Matplotlib support plots with time on the horizontal?

Python hosting: Host, run, and code Python in the cloud! Matplotlib supports plots with time on the horizontal (x) axis. The data values will be put on the vertical (y) axis. In this article we’ll demonstrate that using a few examples.


1 Answers

You can do this with a matplotlib.dates.DateFormatter, which takes a strftime format string as its argument. To get a day-month-year hour:minute format, you can use %d-%m-%y %H:%M:

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

times = pd.date_range('2015-10-06', periods=500, freq='10min')

fig, ax = plt.subplots(1)
fig.autofmt_xdate()
plt.plot(times, range(times.size))

xfmt = mdates.DateFormatter('%d-%m-%y %H:%M')
ax.xaxis.set_major_formatter(xfmt)

plt.show()

enter image description here

like image 160
tmdavison Avatar answered Sep 23 '22 08:09

tmdavison