添加自定义刻度和标签 [英] Adding a custom tick and label

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

问题描述

我想在matplotlib中添加自定义的主要刻度和标签.一个典型的用途是在 math.pi 位置添加一个标签,标签为 "$\pi$".我的目的是让其他刻度线保持不变:我想保留原来的主要和次要刻度线,使其具有以前选择的格式,但带有额外的刻度线和标签.我想出了一种方法(并在这些论坛上找到了帖子)来添加勾号:

I would like to add a custom major tick and label in matplotlib. A typical use is to add a label at the location math.pi with the label "$\pi$". My aim is to leave the other ticks as is: I would like to retain the original major and minor ticks with the formatting that have been previously chosen but with this extra tick and label. I have figured out a way (and found posts on these forums) to add the tick:

list_loc=list(ax.xaxis.get_majorticklocs())
list_loc.append(pos)
list_loc.sort()
ax.xaxis.set_ticks(list_loc)

我的麻烦在于标签.我尝试使用 ax.xaxis.get_majorticklabels()以类似的方式检索标签,但这给了我 matplotlib.text.Text 的列表,我不确定如何处理.我的意图是获取标签列表作为字符串,添加新标签(在正确的位置),然后以与位置类似的方式使用 ax.xaxis.set_ticklabels(list_label)

My trouble is with the label. I have tried to retrieve the labels in a similar way with ax.xaxis.get_majorticklabels() but that gives me a list of matplotlib.text.Textwhich I am unsure how to deal with. My intention was to get the list of labels as strings, to add the new label (at the correct position) and then use ax.xaxis.set_ticklabels(list_label) in a way that is similar to the location.

推荐答案

这是我通常所做的,尽管我从未对这种方法感到完全满意.可能有更好的方法,而无需调用 draw().

This is what I usually do, though I've never been completely satisfied with the approach. There may be a better way, without calling draw().

fig,ax=plt.subplots()
x=linspace(0,10,1000)
x.plot(x,exp(-(x-pi)**2))
plt.draw() # this is required, or the ticklabels may not exist (yet) at the next step
labels = [w.get_text() for w in ax.get_xticklabels()]
locs=list(ax.get_xticks())
labels+=[r'$\pi$']
locs+=[pi]
ax.set_xticklabels(labels)
ax.set_xticks(locs)
ax.grid()
plt.draw()

这篇关于添加自定义刻度和标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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