mpld3 does not display dates on x axis correctly

1.6k Views Asked by At

I am plotting a large dataset from a database using matplotlib and I use mpld3 to pass the figure to the browser. On the x-axis there are dates. The issue here is that while plotting without the mpld3 works perfect, when I use it, the dates don't appear correctly.

Here is my code:

date1 = '2015-04-22 20:28:50'
date2 = '2015-04-23 19:42:09'

db = Base('monitor').open()
result_set = db.select(['MeanVoltage','time'],"time>=start and time<=stop",  start=date1, stop=date2)

V = [float(record.MeanVoltage) for record in result_set if record != 0]
Date = [str(record.time) for record in result_set]


dates = [datetime.datetime.strptime(record, '%Y-%m-%d %H:%M:%S') for record in Date]
dates = matplotlib.dates.date2num(dates)

fig, ax = plt.subplots()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y %H:%M:%S' ))

plt.gcf().autofmt_xdate()
ax.plot(dates,V)
#mpld3.fig_to_html(fig)
#mpld3.show(fig)
plt.show()

that shows the plot perfectly like this: first figure.

Now, if I comment out this line only:

plt.show()

and uncomment these two:

mpld3.fig_to_html(fig)
mpld3.show(fig)

the figure appears in the browser like this: second figure

As you can see, the only issue is how the dates appear in the x-axis. Is there any way to overcome it?

2

There are 2 best solutions below

0
On

The answer above is correct.

If you are exclusively passing through dates, for example

df["Date"][0] = "2018-11-23"

Then you can also pass that through in the format native mpl format below, without making an ordinal value by using date2num.

df["Date"] = [dt.datetime.strptime(d, '%Y-%m-%d') for d in df["Date"]]
ax.plot(df["Dates"].tolist(), some_y_value_list)
0
On

Before creating the HTML figure, add the following line to specify that it is a date axis:

ax.xaxis_date()