使用 hlines、vlines 和 matplotlib 创建形状,使外角完整

Create shape using hlines, vlines with matplotlib so that the exterior corners are complete

示例代码:

fig, ax = plt.subplots()

ax.vlines(x=0.6, ymin=0.2, ymax=0.8, linewidth=10)
ax.hlines(y=0.2, xmin=0.2, xmax=0.6, linewidth=10)
ax.hlines(y=0.8, xmin=.6, xmax=0.8, linewidth=10)
ax.vlines(x=0.8, ymin=0.8, ymax=1.1, linewidth=10)
ax.hlines(y=1.1, xmin=.5, xmax=0.8, linewidth=10)
ax.vlines(x=0.5, ymin=0.4, ymax=1.1, linewidth=10)
ax.hlines(y=.4, xmin=.2, xmax=0.5, linewidth=10)

产生:

虽然角落里有缝隙,但我希望它们齐平。

明确地说,角落目前看起来像:

而我希望它们看起来像:

# 编辑

旁注 - 如果只创建一个矩形,可以使用以下方法:

import matplotlib.patches as pt 
fig, ax = plt.subplots() 
frame = pt.Rectangle((0.2,0.2),0.4,0.6, lw=10,facecolor='none', edgecolor='k') 
ax.add_patch(frame)

有关编辑的更多信息,请点击此处:

除了将线绘制为一条分段曲线外,一个想法是在每条线段的起点和终点放置一个散点。散点的大小是二次方测量的; 10 的线宽对应于大约 70 的散点大小。Matplotlib 还支持 capstyle='round',它以圆角帽开始和结束线。 (对于 ax.plot,参数名为 solid_capstyle='round', while for ax.vlinesit is justcapstyle='round')。`

capstyle 的其他允许值是 'projecting'(将线的宽度延长一半)和 'butt'(在终点处停止线)。

import matplotlib.pyplot as plt

fig, axs = plt.subplots(ncols=3, figsize=(15, 4))
for ax, capstyle in zip(axs, ['round', 'projecting', 'butt']):
    ax.vlines(x=0.6, ymin=0.2, ymax=0.8, linewidth=10, capstyle=capstyle)
    ax.hlines(y=0.2, xmin=0.2, xmax=0.6, linewidth=10, capstyle=capstyle)
    ax.hlines(y=0.8, xmin=.6, xmax=0.8, linewidth=10, capstyle=capstyle)
    ax.vlines(x=0.8, ymin=0.8, ymax=1.1, linewidth=10, capstyle=capstyle)
    ax.hlines(y=1.1, xmin=.5, xmax=0.8, linewidth=10, capstyle=capstyle)
    ax.vlines(x=0.5, ymin=0.4, ymax=1.1, linewidth=10, capstyle=capstyle)
    ax.hlines(y=.4, xmin=.2, xmax=0.5, linewidth=10, capstyle=capstyle)
    ax.set_title(f"capstyle='{capstyle}'")
plt.show()