9

I am trying to change the displayed length of the axis of matplotlib plot. This is my current code:

import matplotlib.pyplot as plt
import numpy as np

linewidth = 2
outward = 10
ticklength = 4
tickwidth = 1

fig, ax = plt.subplots()

ax.plot(np.arange(100))

ax.tick_params(right="off",top="off",length = ticklength, width = tickwidth, direction = "out")
ax.spines["top"].set_visible(False), ax.spines["right"].set_visible(False)

for line in ["left","bottom"]:
    ax.spines[line].set_linewidth(linewidth)
    ax.spines[line].set_position(("outward",outward))

Which generates the following plot:

enter image description here

I would like my plot to look like the following with axis line shortened:

enter image description here

I wasn't able to find this in ax[axis].spines method. I also wasn't able to plot this nicely using ax.axhline method.

Matt
  • 2,289
  • 6
  • 29
  • 45

1 Answers1

11

You could add these lines to the end of your code:

ax.spines['left'].set_bounds(20, 80)
ax.spines['bottom'].set_bounds(20, 80)

for i in [0, -1]:
    ax.get_yticklabels()[i].set_visible(False)
    ax.get_xticklabels()[i].set_visible(False)

for i in [0, -2]:
    ax.get_yticklines()[i].set_visible(False)
    ax.get_xticklines()[i].set_visible(False)

To get this:

enter image description here

Primer
  • 10,092
  • 5
  • 43
  • 55
  • I struggled to find how to do it for minor ticks, as `ax.get_ytickminorlines` does not exist, even though `ax.get_yminorticklabels` does. It can be fiddled with through `ax.yaxis.get_minorticklines`. – Aubergine Sep 14 '22 at 19:26