我使用以下代码生成一个图:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
index=pd.date_range('2018-01-01',periods=200)
data=pd.Series(np.random.randn(200),index=index)
plt.figure()
plt.plot(data)
这给了我一个情节,看起来如下:
看起来像Matplotlib决定将x-ticks格式化为%Y-%m
(source)
我正在寻找一种方法来检索这种日期格式。像ax.get_xtickformat()
这样的函数,然后返回%Y-%m
。这是最聪明的方法吗?
没有内置方法来获取用于标记轴的日期格式。原因是此格式在绘制时确定,甚至可能在放大或缩小绘图时发生变化。
但是,您仍然可以自己确定格式。这需要首先绘制图形,以便修复轮廓。然后,您可以查询自动格式化中使用的格式,并选择将为当前视图选择的格式。
请注意,以下假设正在使用AutoDateFormatter
或子类化的格式化程序(默认情况下应该是这种情况)。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
index=pd.date_range('2018-01-01',periods=200)
data=pd.Series(np.random.randn(200),index=index)
plt.figure()
plt.plot(data)
def get_fmt(axis):
axis.axes.figure.canvas.draw()
formatter = axis.get_major_formatter()
locator_unit_scale = float(formatter._locator._get_unit())
fmt = next((fmt for scale, fmt in sorted(formatter.scaled.items())
if scale >= locator_unit_scale),
formatter.defaultfmt)
return fmt
print(get_fmt(plt.gca().xaxis))
plt.show()
这打印%Y-%m
。
如果要在myFmt = DateFormatter("%d-%m-%Y")
中编辑日期的格式:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
index=pd.date_range('2018-01-01',periods=200)
data=pd.Series(np.random.randn(200),index=index)
fig, ax = plt.subplots()
ax.plot(index, data)
myFmt = DateFormatter("%d-%m-%Y")
ax.xaxis.set_major_formatter(myFmt)
fig.autofmt_xdate()
plt.show()