使用 matplotlib 将日期设置为 x 轴上的第一个字母 [英] Setting dates as first letter on x-axis using matplotlib

查看:79
本文介绍了使用 matplotlib 将日期设置为 x 轴上的第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时间序列图(超过 1 年),其中 x 轴上的月份采用 Jan、Feb、Mar 等形式,但我只想使用月份的第一个字母 (J、F、M 等).我使用

I have time-series plots (over 1 year) where the months on the x-axis are of the form Jan, Feb, Mar, etc, but I would like to have just the first letter of the month instead (J,F,M, etc). I set the tick marks using

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建议的解决方案有效,但由于我本人希望创建可以保存在外部配置脚本中的解决方案,并且在其他程序中导入,我发现格式化程序必须在格式化程序函数本身之外定义变量很不方便.

I tried to make the solution suggested by @Appleman1234 work, but since I, myself, wanted to create a solution that I could save in an external configuration script and import in other programs, I found it inconvenient that the formatter had to have variables defined outside of the formatter function itself.

我没有解决这个问题,但我只是想在这里分享我略短的解决方案,以便您和其他人可以接受或离开它.

I did not solve this but I just wanted to share my slightly shorter solution here so that you and maybe others can take it or leave it.

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

It turned out to be a little tricky to get the labels in the first place, since you need to draw the axes, before the tick labels are set. Otherwise you just get empty strings, when you use Text.get_text().

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

You may want to get rid of the agrument minor=True which was specific to my case.

# ...

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

我希望对您有所帮助:)

I hope it helps:)

这篇关于使用 matplotlib 将日期设置为 x 轴上的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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