简体   繁体   中英

add custom tick with matplotlib

I would like to add a custom tick in a matplotlib figure. 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.

Note: I've found this question from 4 years ago. 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()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM