Python 使用 matplotlib 添加额外的轴刻度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14716660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding extra axis ticks using matplotlib
提问by ahmethungari
I have a simple plot code as
我有一个简单的情节代码
plt.plot(x,y)
plt.show()
I want to add some extra ticks on the x-axis in addition to the current ones, let's say at
除了当前的刻度之外,我想在 x 轴上添加一些额外的刻度,让我们说
extraticks=[2.1, 3, 7.6]
As you see I do not have a pattern for ticks so I do not want to increase the tick frequency for the whole axis; just keep the original ones and add those extras...
如您所见,我没有刻度模式,所以我不想增加整个轴的刻度频率;只保留原始的并添加那些额外的......
Is it possible, at all?
有可能吗?
Regards
问候
采纳答案by Lev Levitsky
Yes, you can try something like:
是的,您可以尝试以下操作:
plt.xticks(list(plt.xticks()[0]) + extraticks)
The function to use is xticks(). When called without arguments, it returns the current ticks. Calling it with arguments, you can set the tick positions and, optionally, labels.
要使用的函数是xticks()。当不带参数调用时,它返回当前的刻度。使用参数调用它,您可以设置刻度位置和可选的标签。
回答by Mad Physicist
For the sake of completeness, I would like to give the OO version of @Lev-Levitsky's great answer:
为了完整起见,我想给出@Lev-Levitsky 很棒的答案的 OO 版本:
lines = plt.plot(x,y)
ax = lines[0].axes
ax.set_xticks(list(ax.get_xticks()) + extraticks)
Here we use the Axesobject extracted from the Lines2Dsequence returned by plot. Normally if you are using the OO interface you would already have a reference to the Axesup front and you would call ploton that instead of on pyplot.
这里我们使用Axes从Lines2D返回的序列中提取的对象plot。通常,如果您正在使用 OO 接口,那么您已经有了对Axes前面的引用,并且您将调用plot它而不是 on pyplot。
Corner Caveat
角落警告
If for some reason you have modified your axis limits (e.g, by programatically zooming in to a portion of the data), you will need to restore them after this operation:
如果由于某种原因您修改了轴限制(例如,通过编程放大数据的一部分),则需要在此操作后恢复它们:
lim = ax.get_xlim()
ax.set_xticks(list(ax.get_xticks()) + extraticks)
ax.set_xlim(lim)
Otherwise, the plot will make the x-axis show all the available ticks on the axis.
否则,绘图将使 x 轴显示轴上的所有可用刻度。

