简体   繁体   中英

Python Matplotlib Plot - Change x-axis from int to dates to make a smooth line chart

I am trying to make a plot using matplotlib. My current dates are actually ints, 195003, 195006, etc. Therefore, when I make the plot, the line chart is not smooth as there is a big gap betweem 195012 to 195101. Is there a way to solve this? Thanks a lot!

import matplotlib.pyplot as plt


x = [195003,195006,195009,195012,195103,195106,195109]

y = [1,2,3,4,3,2,1]

plt.plot(x,y)


 #This is the target - a smooth line chart

plt.figure(2)

plt.plot(y)

If I am reading this correctly, the integer 195003 represents March, 1950? So I think converting your integer dates into datetime.date objects will do what you want, as matplotlib can take a list of dates for your x data.

import datetime
x = [195003,195006,195009,195012,195103,195106,195109]
y = [1,2,3,4,3,2,1]
years = [str(y)[:4] for y in x]
months = [str(m)[4:] for m in x]
dates = [datetime.date(int(y), int(m), 1) for y,m in zip(years, months)]
plt.plot(dates, y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM