如何计算matplotlib中round类型线帽在数据单位下的延伸长度
Matplotlib round线帽延伸长度计算方法
核心原理
- 使用
solid_capstyle="round"时,线条两端圆形线帽沿线条走向的延伸绝对值等于线宽的1/2,单位为point(1point = 1/72英寸) - 要获取数据坐标系下的长度,需要完成「point→英寸→像素→数据坐标」的单位与坐标系变换
完整实现代码
from matplotlib import pyplot as plt fig, ax = plt.subplots() # 接收plot返回的线条对象 line, = 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) # 必须先触发一次绘制,确保坐标变换参数完全生效 fig.canvas.draw() # 1. 获取线宽,计算point单位下的线帽延伸长度 line_width = line.get_linewidth() cap_length_point = line_width / 2 # 2. 转换为英寸单位 cap_length_inch = cap_length_point / 72 # 3. 转换为像素单位 dpi = fig.dpi cap_length_pixel = cap_length_inch * dpi # 4. 转换为数据坐标系下的长度,本例线条为水平走向,直接取x方向差值即可 inv_transform = ax.transData.inverted() x_start, _ = inv_transform.transform((0, 0)) x_end, _ = inv_transform.transform((cap_length_pixel, 0)) cap_length_data = x_end - x_start print(f"数据坐标系下的线帽延伸长度:{cap_length_data:.2f}") print(f"当前示例中线条最右端x坐标:{100 + cap_length_data:.2f}") # 验证:在计算得到的最右端绘制虚线 ax.axvline(x=100 + cap_length_data, c="blue", linestyle="--") plt.show()
注意事项
- 若线条为任意角度,上述计算得到的
cap_length_data就是沿线条走向的延伸长度,无需额外做投影换算 - 若修改了画布dpi、坐标轴范围、画布尺寸,需要重新计算该值,坐标变换参数会随上述配置变化
内容的提问来源于stack exchange,提问作者user3521099
相关产品推荐
相关产品推荐

