Search code examples
pythonmatplotliblinewidth

How to eliminate padding at each end of a line segment


I'm tring to create a sort of horizontal bar chart superimposed on an existing matplotlib plot. I'd like a legend for the bars.

Here's an example

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
y_data = (0,0,1,0)
ax.step((0., 0.1, 0.2, 0.6, 0.8, 1.), (0., 0., 0.5, 1., 0.5, 0.), where='pre')
ax.plot((0.1,0.6),(0.1,0.1), color = 'red', linewidth = 10, label = "line 1")
ax.plot((0.2,0.8),(0.2,0.2), color = 'green', linewidth = 10, label = "line 2")
ax.set_ylim(0,1); ax.set_xlim(0,1)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.tight_layout()

The line segments begin a little before and end a little after the coordinates of the ends of the lines. The amount appears to depend on the line thickness. How to eliminate the extra at the beginning and end? I thought about drawing rectangles, but then how do I do the legend?


Solution

  • Use Axes.hlines:

    ax.hlines(0.1, 0.1, 0.6, color='red', lw=10, label='line1')
    ax.hlines(0.2, 0.2, 0.8, color='green', lw=10, label='line2')
    

    Output:

    enter image description here