【问题标题】:Python Matplotlib Plot - Change x-axis from int to dates to make a smooth line chartPython Matplotlib Plot - 将 x 轴从 int 更改为日期以制作平滑折线图
【发布时间】:2017-02-08 15:27:18
【问题描述】:

我正在尝试使用 matplotlib 进行绘图。我当前的日期实际上是整数,195003、195006 等。因此,当我制作绘图时,折线图并不平滑,因为 195012 到 195101 之间有很大的差距。有没有办法解决这个问题?非常感谢!

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)

【问题讨论】:

  • 您能更具体地说明您期望的结果吗?目前看来您已经解决了图 2 中的问题。
  • @LongwenOu 我不认为这是一个平滑问题的重复。 Instaed,我想这是一个轴标签问题的重复:)但是让我们等待 OP 澄清......
  • 谢谢大家!如果这是一个重复的问题,请道歉..
  • 我想要的是均匀分布的日期。如果日期是 int、195012、195103... x 轴的间距不均匀。感谢下面的答案 - 我将 int 更改为 datetime 格式,它解决了问题。谢谢大家!

标签: python datetime matplotlib


【解决方案1】:

如果我没看错的话,整数 195003 代表 1950 年 3 月?所以我认为将你的整数日期转换为 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)

【讨论】:

    猜你喜欢
    • 2017-03-26
    • 2013-06-15
    • 1970-01-01
    • 2016-11-10
    • 2019-11-12
    • 2018-08-31
    • 2018-07-19
    • 2021-06-19
    • 1970-01-01
    相关资源
    最近更新 更多