在matplotlib中的刻度线之间使x-tick标签居中 [英] Centering x-tick labels between tick marks in matplotlib

查看:641
本文介绍了在matplotlib中的刻度线之间使x-tick标签居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让x-tick日期标签居于刻度线之间,而不是如下图所示居中于刻度线.

I want to have the x-tick date labels centered between the tick marks, instead of centered about the tick marks as shown in the photo below.

我已经阅读了文档,但无济于事-有人知道这样做的方法吗?

I have read the documentation but to no avail - does anyone know a way to do this?

如果有帮助,这里是我用于x轴刻度格式的所有内容:

Here is everything that I've used for my x-axis tick formatting if it helps:

day_fmt = '%d'   
myFmt = mdates.DateFormatter(day_fmt)
ax.xaxis.set_major_formatter(myFmt)    
ax.xaxis.set_major_locator(matplotlib.dates.DayLocator(interval=1))     

for tick in ax.xaxis.get_major_ticks():
    tick.tick1line.set_markersize(0)
    tick.tick2line.set_markersize(0)
    tick.label1.set_horizontalalignment('center')

推荐答案

一种方法是使用次刻度.这样的想法是,您可以设置次要刻度线,使其位于主要刻度线之间的中间位置,然后手动指定标签.

One way to do it is to use the minor ticks. The idea is that you set the minor ticks so that they are located halfway between the major ticks, and you manually specify the labels.

例如:

import matplotlib.ticker as ticker

# a is an axes object, e.g. from figure.get_axes()

# Hide major tick labels
a.xaxis.set_major_formatter(ticker.NullFormatter())

# Customize minor tick labels
a.xaxis.set_minor_locator(ticker.FixedLocator([1.5,2.5,3.5,4.5,5.5]))
a.xaxis.set_minor_formatter(ticker.FixedFormatter(['1','2','3','4','5']))

三行:

  • 隐藏"主要刻度线上的1,2,3,4,...
  • 在主要刻度线的中间设置次要刻度线(假设您的主要刻度线位于1,2,3 ...)
  • 手动指定小刻度线的标签.在这里,图中的"1"将介于1.0和2.0之间.

这只是一个简单的例子.您可能希望通过循环填充列表或其他方式来简化它.

This is just a simple example. You would probably want to streamline it a bit by populating the lists in a loop or something.

您还可以尝试使用其他定位符或格式化程序.

You can also experiment with other locators or formatters.

或者,如注释中所建议:

Alternatively, as suggested in the comments:

# Hide major tick labels
a.set_xticklabels('')

# Customize minor tick labels
a.set_xticks([1.5,2.5,3.5,4.5,5.5],      minor=True)
a.set_xticklabels(['1','2','3','4','5'], minor=True)


示例:

之前:


Example:

Before:

之后:

这篇关于在matplotlib中的刻度线之间使x-tick标签居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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