如何在子图中设置xticks

问题描述 投票:0回答:3

如果我绘制单个

imshow
图,我可以使用

fig, ax = plt.subplots()
ax.imshow(data)
plt.xticks( [4, 14, 24],  [5, 15, 25] )

替换我的 xtick 标签。

现在,我正在使用

 绘制 12 个 
imshow

f, axarr = plt.subplots(4, 3)
axarr[i, j].imshow(data)

如何仅更改这些子图之一的 xticks?我只能使用

axarr[i, j]
访问子图的轴。我如何才能仅针对一个特定的子图访问
plt

python matplotlib subplot
3个回答
216
投票

有两种方法:

  1. 使用子图对象的轴方法(例如
    ax.set_xticks
    ax.set_xticklabels
    )或
  2. 使用
    plt.sca
    设置 pyplot 状态机的当前轴(即
    plt
    接口)。

作为示例(这也说明了使用

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()

enter image description here


49
投票

请参阅 matplotlib 存储库上的(相当)最新的 answer,其中建议使用以下解决方案:

  • 如果您想设置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")`
    

0
投票

自 matplotlib 3.5.0 起,您可以使用

Axes.set_ticks
(类似于
plt.xticks
)在一个函数调用上设置刻度及其标签。因此,使用@Joe Kington 的设置,看起来如下所示:

import matplotlib.pyplot as plt
fig, axes = plt.subplots(3, 4)

# set the xticks and xticklabels of a particular Axes
axes[1,1].set_xticks([0, 1, 2], ['A', 'Big', 'Cat'], color='red', fontsize=12)
#                    ^^^ positions    ^^^^^^ labels

fig.tight_layout()

© www.soinside.com 2019 - 2024. All rights reserved.