What is the length of the line cap in data units?

Viewed 103

When plotting a line using matplotlib, I used solid_capstyle="round". I see that the line extended beyond the assigned length. That is fine for what I want to do. But could I possibly know by how much the line is extended?

Essentially I would like to know the length of the cap.

Demo code:

from matplotlib import pyplot as plt

ax=plt.subplot()
ax.plot([0, 100], [15, 15], linewidth=50, linestyle="-", c="red",
         solid_capstyle="round")
ax.axvline(x=100, c="black")
ax.set_xlim(0, 125)
ax.set_ylim(0, 30)

enter image description here

In this example I want to know the length of the cap in terms of the data units. Visually it looks like 9 units (i.e. line extends upto x=109), but I would like to calculate that computationally.

1 Answers

The radius of the circle is half the width of the line. The linewidth uses "points" as unit (using 72 points in an inch; "points" are also the unit of font size, e.g. a 12 point font size). Note that the units are different in the x and in the y direction and depend on factors such as figure size, xlims and subplot padding.

You can use the data transform to calculate the radius from points to dots to distance on the x-axis:

from matplotlib import pyplot as plt

ax = plt.subplot()
linewidth = 50
ax.plot([0, 100], [15, 15], linewidth=linewidth, linestyle="-", c="red",
        solid_capstyle="round")
ax.axvline(x=100, c="black")
ax.set_xlim(0, 125)
ax.set_ylim(0, 30)
radius = linewidth / 2

ppd = 72. / ax.figure.dpi  # points per dot
trans = ax.transData.inverted().transform
x_radius = ((trans((radius / ppd, 0)) - trans((0, 0))))[0]
y_radius = ((trans((0, radius / ppd)) - trans((0, 0))))[1]
print("The radius in the x-direction is", x_radius)
print("The radius in the y-direction is", y_radius)
ax.axvline(x=100 + x_radius, c="black", ls='--')
ax.axhline(y=15 + y_radius, c="black", ls='--')
plt.show()
The radius in the x-direction is 8.750560035842293
The radius in the y-direction is 2.818362193362194

showing cap-radius in data coordinates

Related