在python中修改特定的x轴刻度标签
问题描述:
我是Python pyplot的本科新手.我要做的是针对一个序列绘制一个函数,例如 x = [1,2,3,4,5]
.
I am an undergrad newbie to the Python pyplot. What I want to do is to plot a function against a sequence, for example, x = [1,2,3,4,5]
.
pyplot.plot
函数自然会给出一个漂亮的数字.但是我想在x轴上用一个表示关键点"的字符串替换刻度标签"2",同时使刻度标签(例如,"4"和"5")不可见.我怎样才能在 pyplot
中实现这一点?
The pyplot.plot
function naturally gives a nice figure. 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. How can I achieve this in pyplot
?
您的帮助将不胜感激.
答
这就是你的做法:
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
通过在您的xtick列表中省略4和5,它们将不会显示.
By omitting 4 and 5 from your xtick list, they won't be shown.