Matplotlib不在轴上写出所有日期 [英] Not write out all dates on an axis, Matplotlib

查看:102
本文介绍了Matplotlib不在轴上写出所有日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这个例子:

import datetime as dt
from matplotlib import pyplot as plt 
import matplotlib.dates as mdates
x = []
d = dt.datetime(2013, 7, 4)
for i in range(30):
        d = d+dt.timedelta(days=1)
        x.append(d)

y = range(len(x))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.gcf().autofmt_xdate()
plt.bar(x,y)
plt.show()

代码在绘图的x轴上写出日期,请参见下图.问题在于,日期被阻塞了,如图所示.如何使matplotlib仅写出每五分之一或十分之一的坐标?

The code writes out dates on the x-axis in the plot, see the picture below. The problem is that the dates get clogged up, as seen in the picture. How to make matplotlib to only write out every fifth or every tenth coordinate?

推荐答案

您可以为DateLocator指定一个interval参数,如下所示.与例如interval=5定位器在第5个日期放置刻度.另外,将autofmt_xdate()放在bar方法之后,以获得所需的输出.

You can specify an interval argument to the DateLocator as in the following. With e.g. interval=5 the locator places ticks at every 5th date. Also, place the autofmt_xdate() after the bar method to get the desired output.

import datetime as dt
from matplotlib import pyplot as plt 
import matplotlib.dates as mdates
x = []
d = dt.datetime(2013, 7, 4)
for i in range(30):
        d = d+dt.timedelta(days=1)
        x.append(d)

y = range(len(x))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.bar(x, y, align='center') # center the bars on their x-values
plt.title('DateLocator with interval=5')
plt.gcf().autofmt_xdate()
plt.show()

使用interval=3,您将在每第3个日期得到一个滴答声:

With interval=3 you will get a tick for every 3rd date:

这篇关于Matplotlib不在轴上写出所有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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