0

The MWE below comes from this great answer by tcaswell, stripped down to the bare minimum code needed to reproduce the issue.

The output of the MWE is this:

enter image description here

Notice how the 15 in the top x axis is larger than the rest of the tick values. As far as I can tell it has something to do with the combination of limits set for the y axis, the scatter plot, and the position of the ticks in the top x axis.

Is this a bug? How can I prevent this?


MWE

import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt


# some random data.
b_x_axis = [0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4.]
t_x_axis = [45, 36, 30, 28, 25, 19, 15, 13, 9]
y = np.random.uniform(0., 10., 9)

fig = plt.figure()
gs = gridspec.GridSpec(2, 2)

for i in range(4):

    ax = plt.subplot(gs[i])
    ax2 = ax.twiny()

    # Set limit on x,y axis.
    ax.set_xlim(-0.5, max(b_x_axis)+0.5)
    plt.ylim(0., 230.)

    # Scatter plot.
    plt.scatter(b_x_axis, y)

    # Set font size for both x axis.
    ax.set_xticklabels(ax.get_xticks(), fontsize=8)
    ax2.set_xticklabels(ax2.get_yticks(), fontsize=8)

    # Set range, ticks, and label for the second x axis.
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(b_x_axis)
    ax2.set_xticklabels(t_x_axis)

plt.savefig('del.png', dpi=150)
Community
  • 1
  • 1
Gabriel
  • 40,504
  • 73
  • 230
  • 404

1 Answers1

2

This line causes the issue:

ax2.set_xticklabels(ax2.get_yticks(), fontsize=8)

because it should be ax2.get_xticks, not yticks. Anyway this line should be deleted all together, because the xticklabels are set again just 3 lines bellow. You can specify the fontsize there:

ax2.set_xticks(b_x_axis)
ax2.set_xticklabels(t_x_axis, fontsize=8)
Mel
  • 5,837
  • 10
  • 37
  • 42