Search code examples
pythonmatplotlibstem-plot

stem plot is clipped on the axis


I drew the plot in the image below but the axis cuts off the marker. I do not want the horizontal axis to extend beyond 0 but I want the marker to be fully visible at 0. I have seen setting clip_on=True to solve the problem but have not been able to do that with a stem plot. Thanks!

Plot

Here is my code below:

x = np.linspace(0, 6, 7)
y = np.ones(7)

fig, ax = plt.subplots(figsize=(3, 1.8))
ax.spines[["left", "bottom"]].set_position(("data", 0))
ax.spines[["top", "right"]].set_visible(False)
ax.spines['bottom'].set_color('gray')
ax.spines['left'].set_color('gray')
ax.tick_params(left=False, bottom=False)

for k, spine in ax.spines.items():
    spine.set_clip_on(True)

ax.stem(x, y, 'black', markerfmt='ko', basefmt=' ')
ax.set_ylim(0, 1.15)
ax.set_xlim(0, 6.5)
plt.show()

Solution

  • You are on the right lines with set_clip_on, but you need to apply it to the artist you want to show above the axes. The stem method returns a container with a few artists in it, which we can loop through:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 6, 7)
    y = np.ones(7)
    
    fig, ax = plt.subplots(figsize=(3, 1.8))
    ax.spines[["left", "bottom"]].set_position(("data", 0))
    ax.spines[["top", "right"]].set_visible(False)
    ax.spines['bottom'].set_color('gray')
    ax.spines['left'].set_color('gray')
    ax.tick_params(left=False, bottom=False)
    
    stems = ax.stem(x, y, 'black', markerfmt='ko', basefmt=' ')
    for artist in stems.get_children():
        artist.set_clip_on(False)
        
    ax.set_ylim(0, 1.15)
    ax.set_xlim(0, 6.5)
    plt.show()
    

    enter image description here