简体   繁体   English

在python中修改特定的x轴刻度标签

[英]Modify a specific x-axis tick label in python

I am an undergrad newbie to the Python pyplot. 我是Python pyplot的本科新手。 What I want to do is to plot a function against a sequence, for example, x = [1,2,3,4,5] . 我想做的是针对一个序列绘制函数,例如x = [1,2,3,4,5]

The pyplot.plot function naturally gives a nice figure. pyplot.plot函数自然会给出一个漂亮的数字。 But I want to replace on the x-axis the tick label "2" by a string say "key point" and at the same time make the tick labels, for example, "4" and "5" invisible. 但是我想在x轴上用一个表示“关键点”的字符串替换刻度标签“ 2”,同时使刻度标签(例如,“ 4”和“ 5”)不可见。 How can I achieve this in pyplot ? 我如何在pyplot实现呢?

Your help will be highly appreciated. 非常感谢您的帮助。

This is how you do it: 这是您的操作方式:

from matplotlib import pyplot as plt

x = [1,2,3,4,5]
y = [1,2,0,2,1]

plt.clf()
plt.plot(x,y,'o-')
ax = plt.gca() # grab the current axis
ax.set_xticks([1,2,3]) # choose which x locations to have ticks
ax.set_xticklabels([1,"key point",2]) # set the labels to display at those ticks

By omitting 4 and 5 from your xtick list, they won't be shown. 从您的xtick列表中省略4和5,它们将不会显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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