减少x轴刻度并移除零填充
我刚开始学习matplotlib和pyplot,想要绘制一个大数据集。下面是一个小片段。
图表可以正常显示,但x轴的刻度标记太挤了。
我该如何减少刻度标记的数量呢?
我试着用 plt.locator_params(nbins=4)
,结果报错了:
AttributeError: 'FixedLocator' object has no attribute 'set_params'
另外,有没有办法去掉pyplot中日期标签前面的零填充呢?
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
xticks = ['01/01', '01/02', '01/03', '01/04', '01/05', '01/06', '01/07', '01/08', '01/09', '01/10', '01/11', '01/12', '01/13', '01/14', '01/15', '01/16', '01/17', '01/18', '01/19', '01/20', '01/21', '01/22', '01/23', '01/24', '01/25', '01/26', '01/27', '01/28', '01/29', '01/30']
y = [80, 80, 60, 30, 90, 50, 200, 300, 200, 150, 10, 80, 20, 30, 40, 150, 160, 170, 180, 190, 20, 210, 220, 20, 20, 20, 200, 270, 280, 90, 00]
y2 = [100, 100, 200, 300, 40, 50, 60, 70, 80, 90, 100, 110, 12, 13, 10, 110, 16, 170, 80, 90, 20, 89, 28, 20, 20, 28, 60, 70, 80, 90, 30]
plt.plot(x, y)
plt.plot(x, y2)
plt.xticks(x, xticks, rotation=90)
plt.show()
2 个回答
3
你可以使用 maxNLocator。
fig, ax = plt.subplots()
locator = MaxNLocator(nbins=3) # with 3 bins you will have 4 ticks
ax.xaxis.set_major_locator(locator)
另外,你可以查看 这个链接。
4
因为matplotlib有一些非常好用的日期工具,所以把你的日期字符串转换成 datetime.datetime
对象是个不错的主意。
这样你就可以使用一些方便的日期定位器;在这种情况下,DayLocator
是最合适的。为了让它跳过一些标签,你可以使用 interval
这个参数。
然后,为了去掉你x轴标签前面的零,你需要一个自定义的格式化函数。
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as tkr
def xfmt(x,pos=None):
''' custom date formatting '''
x = mdates.num2date(x)
label = x.strftime('%m/%d')
label = label.lstrip('0')
return label
x = ['01/01', '01/02', '01/03', '01/04', '01/05', '01/06', '01/07', '01/08', '01/09', '01/10', '01/11', '01/12', '01/13', '01/14', '01/15', '01/16', '01/17', '01/18', '01/19', '01/20', '01/21', '01/22', '01/23', '01/24', '01/25', '01/26', '01/27', '01/28', '01/29', '01/30', '01/31']
xdates = [dt.datetime.strptime(i,'%m/%d') for i in x]
y = [80, 80, 60, 30, 90, 50, 200, 300, 200, 150, 10, 80, 20, 30, 40, 150, 160, 170, 180, 190, 20, 210, 220, 20, 20, 20, 200, 270, 280, 90, 00]
y2 = [100, 100, 200, 300, 40, 50, 60, 70, 80, 90, 100, 110, 12, 13, 10, 110, 16, 170, 80, 90, 20, 89, 28, 20, 20, 28, 60, 70, 80, 90, 30]
plt.plot(xdates,y)
plt.plot(xdates,y2)
plt.setp(plt.gca().xaxis.get_majorticklabels(),rotation=90)
plt.gca().xaxis.set_major_formatter(tkr.FuncFormatter(xfmt))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=4))
plt.gca().xaxis.set_minor_locator(mdates.DayLocator())
plt.show()
上面的代码会生成如下的图表: