简体   繁体   English

使用 matplotlib 添加自定义刻度

[英]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.

相关问题 将自定义对数刻度位置添加到 matplotlib - Add custom logarithmic tick location to matplotlib Matplotlib:添加自定义刻度标签并删除y轴上的自定义刻度 - Matplotlib: add custom tick label and remove custom tick on y-axis Matplotlib 自定义样式:不同的刻度颜色和刻度标签颜色 - Matplotlib custom styles: different tick color and tick label color 在matplotlib图上设置自定义刻度线间距 - Set custom tick spacing on matplotlib graph Matplotlib:添加字符串作为自定义x-ticks但是还保留现有(数字)刻度标签? matplotlib.pyplot.annotate的替代品? - Matplotlib: Add strings as custom x-ticks but also keep existing (numeric) tick labels? Alternatives to matplotlib.pyplot.annotate? 在matplotlib的右yaxis上添加刻度标签 - Add tick labels on right yaxis in matplotlib Python / Matplotlib:带有contourf的颜色条不尊重自定义cmap的刻度标签 - Python/Matplotlib: colorbar with contourf does not respect the tick labels of custom cmap 如何在 matplotlib 中标记空间刻度线并自定义网格线 - How to mark spacial tick mark in matplotlib and custom the gridlines 如何在 matplotlib 中的所有水平网格线上添加垂直刻度线? - How to add vertical tick marks to all horizontal grid lines in matplotlib? 如何在matplotlib中添加其他格式的刻度线标签 - How to add additional tick labels, formatted differently, in matplotlib
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM