pandas 绘图在x轴上显示所有日期值(matplolib仅显示少量值),格式为MMM-YYYY [英] Pandas Plotting Display all date values on x-axis (matplolib only displays few values) formatted as MMM-YYYY

查看:96
本文介绍了 pandas 绘图在x轴上显示所有日期值(matplolib仅显示少量值),格式为MMM-YYYY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import os将熊猫作为pd导入导入matplotlib.pyplot作为plt导入日期时间df = pd.read_excel(DATA_DIR +"/" + file_list [0],index_col ="Date").df.head(5)

  smooth = df ['Pur.Rate'].rolling(window=20).mean()平滑.plot()

我得到以下图表,并且需要在x轴上绘制每个MONTH-YEAR的所有日期值.我想以格式 (Feb-19) 在 x 轴上显示对角格式的所有月份和年份.我可以将图的大小放大为适合所有的图,因为我会将其另存为jpg.

我希望 x 轴具有以下值:1月16日、2月16日、3月16日、4月16日、5月16日、6月16日、7月16日、8月16日、9月16日、10月16日、11月16日、12月16日、1月17日、2月17日……(我想显示所有这些值,matplotlib会自动将其截断,我想避免这种情况)

解决方案

如评论中所述,您必须同时设置 Locator 和 Formatter.这在

import os
import pandas as pd
import matplotlib.pyplot as plt
import datetime

df = pd.read_excel(DATA_DIR+"/"+file_list[0], index_col="Date")
df.head(5)

smooth = df['Pur. Rate'].rolling(window=20).mean()
smooth.plot()

I get the following graph and need to plot all the date values for every MONTH-YEAR on the x-axis. I want to display all the months and years formatted diagonally on the x-axis in the format (Feb-19). I can make the size of the plot larger to fit all as I will save it as jpg.

I want the x-axis to have the following values: Jan 16, Feb 16, Mar 16, Apr 16, May 16, Jun 16, Jul 16, Aug 16, Sep 16, Oct 16, Nov 16, Dec 16, Jan 17, Feb 17 … (I want to display all these values, matplotlib automatically truncates this, I want to avoid that)

解决方案

As mentioned in the comments, you have to set both, the Locator and the Formatter. This is explained well in the matplotlib documentation for graphs in general and separately for datetime axes. See also an explanation of the TickLocators. The formatting codes are derived from Python's strftime() and strptime() format codes.

from matplotlib import pyplot as plt
import pandas as pd
from matplotlib.dates import MonthLocator, DateFormatter


#fake data
import numpy as np
np.random.seed(123)
n = 100
df = pd.DataFrame({"Dates": pd.date_range("20180101", periods=n, freq="10d"), "A": np.random.randint(0, 100, size=n), "B": np.random.randint(0, 100, size=n),})
df.set_index("Dates", inplace=True)
print(df)

ax = df.plot()

#defines the tick location 
ax.xaxis.set_major_locator(MonthLocator())
#defines the label format
ax.xaxis.set_major_formatter(DateFormatter("%b-%y"))
ax.tick_params(axis="x", labelrotation= 90)

plt.tight_layout()
plt.show()

Sample output:

这篇关于 pandas 绘图在x轴上显示所有日期值(matplolib仅显示少量值),格式为MMM-YYYY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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