显示仅带有主要刻度线标签的次要刻度线

编程入门 行业动态 更新时间:2024-10-28 12:23:45
本文介绍了显示仅带有主要刻度线标签的次要刻度线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在轴上有较小的刻度线,但只显示主要的刻度线标签.例如,次刻度线为[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:

更多推荐

显示仅带有主要刻度线标签的次要刻度线

本文发布于:2023-07-18 08:32:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1142873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:刻度   标签

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!