0

Following on from this question and some similar situations here, and here, how does one place the x- and y-axis tick marks and labels at the outside of the plot? There is one hack here, that attempts to address the problem since as @whatitis notes, you cannot know the pad in advance in all situations (e.g. ax.get_xaxis().set_tick_params(pad=5)); so it seems there must be a native API approach, but none of the attempts (commented) in the following MWE work

import numpy as np
import matplotlib.pyplot as plt

#data generation
x = np.arange(-10,20,0.2)
y = 1.0/(1.0+np.exp(-x)) # numpy does the calculation elementwise for you

fig, ax = plt.subplots()

ax.plot(x,y)

# Eliminate upper and right axes
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# Show ticks on the left and lower axes only (and let them protrude in both directions)
ax.xaxis.set_tick_params(bottom='on', top=False, direction='inout')
ax.yaxis.set_tick_params(left='on', right=False, direction='inout')

# Make spines pass through zero of the other axis
ax.spines['bottom'].set_position('zero')
ax.spines['left'].set_position('zero')

ax.set_ylim(-0.4,1.0)

ax.set_ylabel(r'y-axis label')
ax.set_xlabel(r'x-axis label')

#
# How to place labels and ticks on the outside of the axes area
#

# Attempt 1 - has no effect
# ax.xaxis.tick_bottom()
# ax.yaxis.tick_left()

# Attempt 2 - has no effect - is this a bug? Why isn't 'top' & 'bottom' where it should be?
ax.yaxis.set_label_position('left')
ax.xaxis.set_label_position('bottom')

plt.show() 
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Colin
  • 453
  • 4
  • 16
  • 1
    Is this what you want to do? `ax.set_ylabel(r'y-axis label', labelpad=80);ax.set_xlabel(r'x-axis label', labelpad=50)` – r-beginners Oct 10 '21 at 14:04
  • Yes, that has the right effect, but as stated in the question, you cannot know how much to pad it when the data changes. The lines `ax.xaxis.set_label_position('bottom')` and `ax.yaxis.set_label_position('left')` don't seem to do what they should. – Colin Oct 10 '21 at 23:53

0 Answers0