【问题标题】:How to make the x axis of a graph sequential dates when dates in the dataframe are not sequential?当数据框中的日期不连续时,如何使图形的 x 轴连续日期?
【发布时间】:2021-04-23 20:22:17
【问题描述】:

假设我有

df = pd.DataFrame([{'Date': '3/4/2021', 'count': 2}, {'Date': '3/6/2021', 'count': 3}, {'Date': '3/12/2021', 'count': 5}], columns = ['Date', 'count'])

如果我简单地绘制图表

df.plot(x = 'Date, y='count')

那么 x 轴上的日期将非常不连续,并且 x 轴上没有可用的时间范围。如何使 x 轴只是日期的顺序列表,然后根据 df['Date'] 的值是否与 x 轴上的日期匹配来填充绘图?

【问题讨论】:

  • 您可能必须将日期格式化为时间而不是字符串

标签: python matplotlib graph


【解决方案1】:

将日期格式化为日期时间而不是字符串。

df.Date = pd.to_datetime(df.Date,format='%d/%m/%Y')
df.plot(x='Date', y='count')

根据您的本地化,您必须将格式更改为“%m/%d/%Y”

【讨论】:

  • 请注意,format 通常不需要。 pandas 有很好的自动检测功能。
猜你喜欢
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
相关资源
最近更新 更多