Matplotlib: draw lines with width given in data coordinates

I am trying to figure out how to draw lines with a width in units of data. For example, in the following code snippet, I would like the horizontal part of the line of width 80 to always extend from y = -40 to the label y = + 40 and stay the same, even if the limits of the coordinate system change. Is there a way to achieve this using Line2D objects in matplotlib? Any other way to get a similar effect?

from pylab import figure, gca, Line2D

figure()
ax = gca()
ax.set_xlim(-50, 50)
ax.set_ylim(-75, 75)

ax.add_line(Line2D([-50, 0, 50], [-50, 0, 0], linewidth=80))

ax.grid()

line width in screen coordinates

+5
source share
2 answers

You can use fill_between :

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim(-50, 50)
ax.set_ylim(-75, 75)
x = [-50, 0, 50]
y = np.array([-50, 0, 0])

ax.fill_between(x,y-30,y+30)

ax.grid()
plt.show()

gives

enter image description here

but unlike the line generated

ax.add_line(Line2D([-50, 0, 50], [-50, 0, 0], linewidth=80))

the vertical line thickness will always be constant in the data coordinates.

. .

+6

, .

data_linewidth_plot, plt.plot().

l = data_linewidth_plot( x, y, ax=ax, label='some line', linewidth = 1, alpha = 0.4)

(y-).

+1

All Articles