Minor ticks with only major tick labels are shown(仅显示主要刻度标签的次要刻度)
问题描述
我想在轴上有次要刻度,但只显示主要刻度标签.例如,次要刻度是 [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))
你会得到这个图像:
这篇关于仅显示主要刻度标签的次要刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:仅显示主要刻度标签的次要刻度


基础教程推荐
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01