DateFormatter 将 1970 作为年份而不是数据集中的原始年份 [英] DateFormatter is bringing 1970 as year not the original year in the dataset

查看:27
本文介绍了DateFormatter 将 1970 作为年份而不是数据集中的原始年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制时间序列数据.但是 x 轴刻度没有按照它应该的方式出现.我想在 x 轴刻度上显示 mont 和 year.这是我的代码

I am trying to plot time series data. But x axis ticks are not coming the way it should. I wanted to out mont and year as x axis ticks. here is my code

from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
fig,ax = plt.subplots()
df_month.loc['2017', "Volume"].plot.bar(color='blue', ax=ax)
ax.set_ylabel("Volume")
ax.set_title("Volume")
date_form = DateFormatter("%y-%m")
ax.xaxis.set_major_formatter(date_form)

plt.xticks(rotation=45)
plt.show()

输出看起来像这样我究竟做错了什么?请帮忙.

The output looks like this What am I doing wrong? Please help.

我的数据集如下所示:

这里是 df_month 数据:

Here is df_month data:

推荐答案

下面给出了正确的 x 轴标签.

The following gives the right x-axis labels.

导入模块

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates

示例数据

df_month = pd.DataFrame({'Date':['2006-01-03', '2006-02-04', '2006-02-08'], 'Volume':[24232729, 20553479, 20500000]}) # '2006-01-03', '2006-01-04'

df_month['Date'] = pd.to_datetime(df_month['Date'])

绘图

fig,ax = plt.subplots()
ax.set_ylabel("Volume")
ax.set_title("Volume")

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.bar(df_month['Date'], df_month['Volume'])

plt.xticks(df_month['Date'], rotation=90)
plt.show()

这篇关于DateFormatter 将 1970 作为年份而不是数据集中的原始年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆