Show tick labels when sharing an axis in matplotlib

Question:

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:

enter image description here

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). 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?

I’m running matplotlib 1.4.0, if that’s important.

Asked By: James Kelleher

||

Answers:

The ticks that are missing have had their visible property set to False. This is pointed out in the documentation for 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()]
Answered By: farenorth

In Matplotlib 2.2 and above the tick labels can be turned back on using:

ax.xaxis.set_tick_params(labelbottom=True)
Answered By: David Stansby

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

In my case, I need to turn on all the x and y labels and this solution works:

for ax in axes.flatten():
    ax.xaxis.set_tick_params(labelbottom=True)
    ax.yaxis.set_tick_params(labelleft=True)
Answered By: ÁlvaroFernandez
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.