Pandas Plot: How to change xlim in datatime format?

Victor Wang :

The range of date is from 2020-01-30 to 2020-03-31. The format of Date is datetime64[ns]. I want to change the xlim range to (2020-01-30, 2020-03-31), but not working.

My code is as follows:

#Plot left Y
fig, ax1 = plt.subplots()
fig.autofmt_xdate()

x_lim = (datetime.date(2020, 1, 30), datetime.date(2020, 3, 31))

df.plot(x = 'Date', y = ["TotalCount", "CumVirusCount"], ax = ax1, xlim = x_lim)


Plot right (Y)
ax2 = ax1.twinx()
df.plot(x = 'Date', y = ["Percent"], ax = ax2, xlim = x_lim, ylim=(0,70), color = 'tab:green')

#Decorations
#ax1:
ax1.set_xlabel('Date', fontsize=18)
ax2.set_ylabel("Percentage")

plt.show()

The plot is as follows:

Plot

I expect the first date to be 2020-01-30 and the last date to be 2020-03-31 on the x-axis.

How to make that happen? Why my approach doesn't work? Thank you!

Arne :

You do set the x-range in your code with xlim=..., and it works fine. But the ticks that matplotlib places on the x-axis by default do not necessarily include the min and max values. To change that, you have to change the ticks, not the range. Pandas' df.plot() wrapper takes an xticks keyword argument for this, e.g. pass this in the plot function call:

xticks=[x_lim[0], <some in-between dates to label>, x_lim[1]] 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=405762&siteId=1