繁体   English   中英

使用 matplotlib 将日期设置为 x 轴上的第一个字母

[英]Setting dates as first letter on x-axis using matplotlib

我有时间序列图(超过 1 年),其中 x 轴上的月份格式为 Jan、Feb、Mar 等,但我只想使用月份的第一个字母(J、F、 M 等)。 我使用设置刻度线

ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_minor_locator(MonthLocator())

ax.xaxis.set_major_formatter(matplotlib.ticker.NullFormatter())
ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter('%b')) 

任何帮助,将不胜感激。

我试图使@Appleman1234 建议的解决方案起作用,但是由于我自己想要创建一个可以保存在外部配置脚本中并导入到其他程序中的解决方案,我发现格式化程序必须定义变量很不方便在格式化程序功能本身之外。

我没有解决这个问题,但我只是想在这里分享我稍微简短的解决方案,以便您和其他人可以接受或放弃它。

事实证明,首先获取标签有点棘手,因为您需要在设置刻度标签之前绘制轴。 否则,当您使用Text.get_text()时,您只会得到空字符串。

您可能想要摆脱特定于我的情况的 agrument minor=True

# ...

# Manipulate tick labels
plt.draw()
ax.set_xticklabels(
    [t.get_text()[0] for t in ax.get_xticklabels(minor=True)], minor=True
)

我希望它有帮助:)

根据官方公布的例子下面的代码片段在这里为我工作。

这使用基于函数的索引格式化程序顺序仅根据要求返回月份的第一个字母。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
datafile = cbook.get_sample_data('aapl.csv', asfileobj=False)
print 'loading', datafile
r = mlab.csv2rec(datafile)

r.sort()
r = r[-365:]  # get the last year

# next we'll write a custom formatter
N = len(r)
ind = np.arange(N)  # the evenly spaced plot indices
def format_date(x, pos=None):
    thisind = np.clip(int(x+0.5), 0, N-1)
    return r.date[thisind].strftime('%b')[0]


fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()

plt.show()

原始答案使用日期索引。 这是没有必要的。 可以改为从DateFormatter('%b')获取月份名称,并使用FuncFormatter仅使用月份的第一个字母。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from matplotlib.dates import MonthLocator, DateFormatter 

x = np.arange("2019-01-01", "2019-12-31", dtype=np.datetime64)
y = np.random.rand(len(x))

fig, ax = plt.subplots()
ax.plot(x,y)


month_fmt = DateFormatter('%b')
def m_fmt(x, pos=None):
    return month_fmt(x)[0]

ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(FuncFormatter(m_fmt))
plt.show()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM