在matplotlib中共享轴时显示刻度标签

时间:2015-03-25 21:34:02

标签: python matplotlib

我正在运行以下功能:

def plot_variance_analysis(indices, stat_frames, legend_labels, shape):
    x = np.linspace(1, 5, 500)
    fig, axes = plt.subplots(shape[0], shape[1], sharex=True sharey=True)
    questions_and_axes = zip(indices, axes.ravel())
    frames_and_labels = zip(stat_frames, legend_labels)
    for qa in questions_and_axes:
        q = qa[0]
        ax = qa[1]
        for fl in frames_and_labels:
            frame = fl[0]
            label = fl[1]
            ax.plot(x, stats.norm.pdf(x, frame['mean'][q], frame['std'][q]), label=label)
            ax.set_xlabel(q)
            ax.legend(loc='best')
    plt.xticks([1,2,3,4,5])
    return fig, axes

以下是我自己的一些示例数据:

enter image description here

我正在尝试维持轴之间的共享状态,但同时在所有子图(包括前两个)上显示x轴的刻度标签。我找不到任何方法在文档中关闭它。有什么建议?或者我应该逐轴设置x刻度标签?

我正在运行matplotlib 1.4.0,如果这很重要的话。

3 个答案:

答案 0 :(得分:20)

缺少的刻度已将visible属性设置为False。这在plt.subplot的文档中有所指出。解决这个问题的最简单方法可能是:

for ax in axes.flatten():
    for tk in ax.get_yticklabels():
        tk.set_visible(True)
    for tk in ax.get_xticklabels():
        tk.set_visible(True)

在这里,我已经绕过了你不一定需要做的所有轴,但代码更简单。如果您愿意,也可以在丑陋的班轮中使用列表推导来执行此操作:

[([tk.set_visible(True) for tk in ax.get_yticklabels()], [tk.set_visible(True) for tk in ax.get_yticklabels()]) for ax in axes.flatten()]

答案 1 :(得分:13)

在Matplotlib 2.2中,可以使用以下命令重新打开刻度标签:

ax.xaxis.set_tick_params(labelbottom=True)

答案 2 :(得分:3)

您可以在此处找到有关matplotlib标签的其他信息: https://matplotlib.org/3.1.3/api/_as_gen/matplotlib.axes.Axes.tick_params.html

就我而言,我需要打开所有x和y标签,并且此解决方案有效:

for ax in axes.flatten():
    ax.xaxis.set_tick_params(labelbottom=True)
    ax.yaxis.set_tick_params(labelleft=True)