Search code examples
pythonmatplotlibscatter-plotx-axis

How to only show portion of x-axis spine on scatterplot


I don't want the x-axis spine between (0,0) and (0,4) to display on the scatterplot below. I still want the distance on the chart, I just don't want the spine to display between those coordinates.

import matplotlib.pyplot as plt
x = range(4,10)
y=x
fig, ax = plt.subplots()
ax.scatter(x=x, y=y)
ax.set_xlim(left=0, right=10)
ax.set_xticks(x)
plt.show()

enter image description here

Ideally something like this:

ax.spines['bottom'].set_visible([4:])

But it yields SyntaxError: invalid syntax.

This hides the entire line:

ax.spines['bottom'].set_visible(False)

I tried set_position():

ax.spines['bottom'].set_position('data',4)

But I could only get error messages. If I supplied one argument it said it wasn't enough, but when I supply two it complained about too many:

TypeError: Spine.set_position() takes 2 positional arguments but 3 were given

What should I try next?


Solution

  • You can use the set_bounds methods of the spine. From the docs:

    set_bounds(low=None, high=None)

    Set the spine bounds.

    Parameters:

    low float or None, optional

    The lower spine bound. Passing None leaves the limit unchanged. The bounds may also be passed as the tuple (low, high) as the first positional argument.

    high float or None, optional

    The higher spine bound. Passing None leaves the limit unchanged.

    So for your plot, to just change the lower bound to 4, you could use:

    ax.spines['bottom'].set_bounds(4)
    

    enter image description here

    If you want to also change the upper bound, you could use something like:

    ax.spines['bottom'].set_bounds(4, 9)