如何仅移动刻度线标签(不移动相应的刻度线)? [英] How can I move a tick label only(without moving corresponding tick)?

查看:41
本文介绍了如何仅移动刻度线标签(不移动相应的刻度线)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib生成图表,并且使用 set_ticks set_ticklabels 在x轴上标记了几个重要值.但是其中一些标签太近并且会重叠.但是我不知道如何在不移动刻度线的情况下移动这些标签.

I'm using matplotlib to generate a diagram, and I use set_ticks and set_ticklabels to mark out several important values on the x-axis. But some of these labels are too close and get overlapped. But I don't know how to move these labels without moving the ticks.

这是一个例子:

我尝试了几个技巧但都失败了,而且我还没有在网上找到这个问题的答案.任何帮助,谢谢.

I have tried several tricks but failed, and I haven't found an answer to this question on the Internet. Any help, thanks.

源代码:

fig = mpl.figure( figsize=(3, 3) )              # force figsize here to reproduce the problem.
ax = fig.add_subplot(1, 1, 1, frameon=False)
ax.set_xlim(-0.015, 1.515)
ax.set_ylim(-0.01, 1.01)
ax.set_xticks([0, 0.3, 0.4, 1.0, 1.5])
ax.grid(True)
mpl.show()

结果:

我尝试了几种技巧,最好的一种是:

I have tried several tricks and the best one is:

fig = mpl.figure( figsize=(3, 3) )
ax = fig.add_subplot(1, 1, 1, frameon=False)
ax.set_xlim(-0.015, 1.515)
ax.set_ylim(-0.01, 1.01)
ax.set_xticks([0, 0.3, 0.4, 1.0, 1.5])
ax.set_xticklabels([0.0, "", "", 1.0, 1.5])
ax.set_xticks([0.35], minor=True)
ax.set_xticklabels(["0.3 0.4"], minor=True)
ax.grid(True)
mpl.show()

但是在 x = 0.35 处有一个小刻度,我不知道如何删除它.

But there is a minor tick at x = 0.35 and I don't know how to remove it.

好的,我找到了如何自己去除小蜱虫:

OK, I found how to remove minor ticks myself:

for line in ax.xaxis.get_minorticklines():
    line.set_visible(False)

通过这种方式,我们可以利用小刻度将刻度标签放在我们想要的任何地方.

In this manner, we can utilize minor ticks to put tick labels anywhere we want.

感谢所有热心的人!

推荐答案

从您的评论"..在x轴上标记几个重要值"我认为您不应该更改xticks和标签,而应该添加带有适当注释的垂直线.

From your comment "..mark out several important values on the x-axis" I think you shouldn't be changing the xticks and labels, but rather add vertical lines with appropriate annotation.

这意味着您的数据保持规则的网格并允许您为重要点着色,您还可以相当轻松地添加数值.

This means the grid over which your data remains regular and allows you to colourise important points, you could also add the numeric values as well fairly easily.

示例

import pylab as py

# Plot a sinc function
delta=2.0
x=py.linspace(-10,10,100)
y=py.sinc(x-delta)

# Mark delta
py.axvline(delta,ls="--",color="r")
py.annotate(r"$\delta$",xy=(delta+0.2,-0.2),color="r",size=15)
py.plot(x,y) 

这篇关于如何仅移动刻度线标签(不移动相应的刻度线)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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