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

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

问题描述

我想在轴上有较小的刻度线,但只显示主要的刻度线标签.例如,次刻度线为[19、20、21,... 40、41],而主要刻度线标签为[20、25、30、35、40].我该怎么做?下面的代码没有完成这项工作.我知道可以像此示例那样使用MultipleLocator,FormatStrFormatter.但是,我在轴上的值有些奇怪",起始值为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()

它给了我下面的情节:

it gives me the following plot:

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))

您将获得以下图像:

And you'll get this image:

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

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