子图中的 Python xticks
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19626530/
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
Python xticks in subplots
提问by user2926577
If I plot a single imshowplot I can use
如果我绘制单个imshow图,我可以使用
fig, ax = plt.subplots()
ax.imshow(data)
plt.xticks( [4, 14, 24], [5, 15, 25] )
to replace my xtick labels.
替换我的 xtick 标签。
Now, I am plotting 12 imshowplots using
现在,我正在绘制 12 个imshow图使用
f, axarr = plt.subplots(4, 3)
axarr[i, j].imshow(data)
How can I change my xticks just for one of these subplots? I can only access the axes of the subplots with axarr[i, j]. How can I access pltjust for one particular subplot?
如何仅为这些子图之一更改我的 xticks?我只能使用axarr[i, j]. 如何plt仅访问一个特定的子图?
采纳答案by Joe Kington
There are two ways:
有两种方式:
- Use the axes methods of the subplot object (e.g.
ax.set_xticksandax.set_xticklabels) or - Use
plt.scato set the current axes for the pyplot state machine (i.e. thepltinterface).
- 使用子图对象的轴方法(例如
ax.set_xticks和ax.set_xticklabels)或 - 使用
plt.sca设置当前轴为pyplot状态机(即,plt接口)。
As an example (this also illustrates using setpto change the properties of all of the subplots):
作为一个例子(这也说明了使用setp来改变所有子图的属性):
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=3, ncols=4)
# Set the ticks and ticklabels for all axes
plt.setp(axes, xticks=[0.1, 0.5, 0.9], xticklabels=['a', 'b', 'c'],
yticks=[1, 2, 3])
# Use the pyplot interface to change just one subplot...
plt.sca(axes[1, 1])
plt.xticks(range(3), ['A', 'Big', 'Cat'], color='red')
fig.tight_layout()
plt.show()


回答by Archie
See the (quite) recent answeron the matplotlib repository, in which the following solution is suggested:
请参阅matplotlib 存储库上的(相当)最近的答案,其中建议使用以下解决方案:
If you want to set the xticklabels:
ax.set_xticks([1,4,5]) ax.set_xticklabels([1,4,5], fontsize=12)If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", horizontalalignment="left")`
如果要设置 xticklabels:
ax.set_xticks([1,4,5]) ax.set_xticklabels([1,4,5], fontsize=12)如果您只想增加 xticklabels 的字体大小,请使用默认值和位置(这是我个人经常需要并且非常方便的东西):
ax.tick_params(axis="x", labelsize=12)一次性完成所有操作:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", horizontalalignment="left")`

