简体   繁体   English

Python Matplotlib Plot-将x轴从int更改为日期以制作平滑的折线图

[英]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. 我正在尝试使用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? 我当前的日期实际上是整数,即195003、195006等。因此,当我进行绘图时,折线图并不平滑,因为195012至195101之间有很大的差距。是否有解决方法? 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? 如果我没看错,整数195003代表1950年3月吗? 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. 因此,我认为将整数日期转换为datetime.date对象将满足您的要求,因为matplotlib可以获取x数据的日期列表。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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