仅显示主要刻度标签的次要刻度 [英] Minor ticks with only major tick labels are shown

查看:133
本文介绍了仅显示主要刻度标签的次要刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在轴上有次要刻度,但只显示主要刻度标签.例如,次要刻度是 [19, 20, 21, ... 40, 41],主要刻度标签是 [20, 25, 30, 35, 40].我该怎么做?下面的代码没有完成这项工作.我知道可以使用 MultipleLocator、FormatStrFormatter,例如 this example.但是,我在轴上的值有点奇怪",起始值为 19(不是 20),结束值为 41,这在使用 MultipleLocator 时会造成困难.

I would like to have minor ticks on a axis but show only major tick labels. For instance, minor ticks are [19, 20, 21, ... 40, 41] and major tick labels are [20, 25, 30, 35, 40]. How can I do it? the code below didn't do the job. I know one could use MultipleLocator, FormatStrFormatter like this example. However, my values on the axis are a bit "strange" with the starting value is 19 (not 20) and end value is 41, which cause difficulty when using MultipleLocator.

import numpy as np
from matplotlib import pylab as plt

fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(19.,41,23)
y = x**2
ax.plot(x,y)
ax.set_xticks(x)
ax.set_xticklabels(x, minor=False)
plt.show()

它给了我以下情节:

ax.set_xticklabels([20, 25, 30, 35, 40], minor=False)给我另一个情节:我怎样才能改变我的代码来得到我需要的东西.非常感谢您的帮助!

or ax.set_xticklabels([20, 25, 30, 35, 40], minor=False) give me another plot: How can I change my code to get what I need. Thanks a lot for your help!

推荐答案

我真的不明白为什么在你的例子中使用 MultipleLocator 很困难.

I don't really understand why is it difficult to use MultipleLocator in your example.

通过在代码中添加这些行

By adding these lines in your code

from matplotlib.ticker import MultipleLocator, FormatStrFormatter

majorLocator   = MultipleLocator(5)
majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(1)

ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
ax.xaxis.set_minor_locator(minorLocator)

你会得到这张图片,我知道这是你想要的(不是吗?):

You'll get this image, which I understood it is what you want (isn't it?):

如果您不希望刻度显示在您的数据范围下方,请使用 FixedLocator 手动定义刻度:

In case you don't want the ticks to show below your range of data, define your ticks manually using the FixedLocator:

from matplotlib.ticker import FixedLocator

majorLocator   = FixedLocator(np.linspace(20,40,5))
minorLocator   = FixedLocator(np.linspace(19,41,23))

你会得到这个图像:

这篇关于仅显示主要刻度标签的次要刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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