【发布时间】:2020-12-10 10:28:26
【问题描述】:
使用 matplotlib 我想创建一个图表,其中我的数据框 (df) 中的所有日期值都显示在 x 轴上。原则上,代码行plt.gca().xaxis.set_major_locator(matplotlib.dates.DayLocator(interval=1)) 应该可以完成这项工作,但它没有,可能是因为我使用的是自定义格式化程序!?这里需要自定义格式化程序,因为我会阻止 matplotlib 插入不属于我的数据框 (have a look at this question here) 的周末日期值。
我还想使用日期格式“%d.%m.%Y”。
虽然代码适用于 matplotlib 3.3.3/Python 3.8,但我的项目必须使用 matplotlib 3.2.2/Python 3.6,在这些情况下,代码不会返回所需的输出
代码如下:
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import Formatter
import pandas as pd
import numpy as np
df = pd.DataFrame(data={"col1": [1.000325, 1.000807, 1.001207, 1.000355, 1.001512, 1.003237, 1.000979,
1.000325, 1.000807, 1.001207, 1.000355, 1.001512, 1.003237, 1.000979],
"date": ['2018-01-08', '2018-01-09', '2018-01-10', '2018-01-11', '2018-01-12',
'2018-01-15', '2018-01-16', '2018-01-17', '2018-01-18', '2018-01-19',
'2018-01-22', '2018-01-23', '2018-01-24', '2018-01-25',]})
df["date"] = pd.to_datetime(df["date"])
class CustomFormatter(Formatter):
def __init__(self, dates, fmt='%d.%m.%Y'):
self.dates = dates
self.fmt = fmt
def __call__(self, x, pos=0):
'Return the label for time x at position pos'
ind = int(np.round(x))
if ind >= len(self.dates) or ind < 0:
return ''
return self.dates[ind].strftime(self.fmt)
fig = plt.figure()
plt.gca().xaxis.set_major_formatter(CustomFormatter(df["date"]))
plt.plot(np.arange(df.shape[0]), df["col1"])
plt.gcf().autofmt_xdate()
#plt.gca().xaxis.set_major_locator(matplotlib.dates.DayLocator(interval=1)) # <-- this line should do the job, in theory!
使用 matplotlib 3.2.2 输出
预期输出(matplotlib 3.3.3)
感谢您的帮助!
【问题讨论】:
标签: python-3.x pandas matplotlib