简体   繁体   English

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

[英]Show tick labels when sharing an axis in matplotlib

I'm running the following function:我正在运行以下功能:

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

Here's what I get with some of my own sample data:以下是我使用自己的一些示例数据得到的结果:

在此处输入图片说明

I'm trying to maintain the shared state between axes, but at the same time display the tick labels for the x axis on all subplots (including the top two).我试图保持轴之间的共享状态,但同时在所有子图(包括前两个)上显示 x 轴的刻度标签。 I can't find any means to turn this off in the documentation.我在文档中找不到任何方法来关闭它。 Any suggestions?有什么建议么? Or should I just set the x tick labels axis by axis?还是我应该逐轴设置 x 刻度标签?

I'm running matplotlib 1.4.0, if that's important.如果这很重要,我正在运行 matplotlib 1.4.0。

在 Matplotlib 2.2 及更高版本中,可以使用以下方法重新打开刻度标签:

ax.xaxis.set_tick_params(labelbottom=True)

The ticks that are missing have had their visible property set to False .丢失的刻度的visible属性设置为False This is pointed out in the documentation for plt.subplot . plt.subplot的文档中指出了这一点。 The simplest way to fix this is probably to do:解决此问题的最简单方法可能是:

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)

Here I've looped over all axes, which you don't necessarily need to do, but the code is simpler this way.在这里,我循环了所有轴,您不一定需要这样做,但这种方式的代码更简单。 You could also do this with list comprehensions in an ugly one liner if you like:如果您愿意,您也可以在丑陋的单行中使用列表理解来执行此操作:

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

You can find extra information about labels of matplotlib here: https://matplotlib.org/3.1.3/api/_as_gen/matplotlib.axes.Axes.tick_params.html您可以在此处找到有关 matplotlib 标签的额外信息: https ://matplotlib.org/3.1.3/api/_as_gen/matplotlib.axes.Axes.tick_params.html

In my case, I need to turn on all the x and y labels and this solution works:就我而言,我需要打开所有 x 和 y 标签,此解决方案有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM