[英]add custom tick with matplotlib
I would like to add a custom tick in a matplotlib
figure.我想在
matplotlib
图中添加一个自定义刻度。 Currently, I add my ticks with the following command (for instance):目前,我使用以下命令添加我的刻度(例如):
axis.set_yticks([0.5,0.6,0.7,0.8,0.9,1.0])
I would like to be able to do:我希望能够做到:
axis.set_yticks({ 1.0 : "some custom text"})
So that instead of 1.0
, at that position some custom text
is shown.因此,而不是
1.0
,在该位置显示some custom text
。
Note: I've found this question from 4 years ago.注意:我在 4 年前发现了这个问题。 I am asking basically the same thing with the hope there's a better way of doing it: Adding a custom tick and label
我问的基本相同,希望有更好的方法: 添加自定义刻度和标签
The other question and its answer are still valid.另一个问题及其答案仍然有效。 You cannot use dictionaries to set the ticks.
您不能使用字典来设置刻度。
In this case however it seems your requirement is different.然而,在这种情况下,您的要求似乎有所不同。 While the linked question asks for leaving the ticks unchanged, here you want to set the ticks manually anyways.
虽然链接的问题要求保持刻度不变,但在这里您无论如何都想手动设置刻度。 This will require to set the ticks and ticklabels but then allows to just replace any key from a dictionary with the respective value when setting the labels.
这将需要设置刻度和刻度标签,但允许在设置标签时只用相应的值替换字典中的任何键。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ticks = [0.5,0.6,0.7,0.8,0.9,1.0]
ax.set_yticks(ticks)
dic = { 1.0 : "some custom text"}
labels = [ticks[i] if t not in dic.keys() else dic[t] for i,t in enumerate(ticks)]
## or
# labels = [dic.get(t, ticks[i]) for i,t in enumerate(ticks)]
ax.set_yticklabels(labels)
plt.tight_layout()
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.