如何在matplotlib中绘制位于坐标轴外的线(以图形坐标为单位)

21 投票
1 回答
20157 浏览
提问于 2025-04-16 11:57

Matplotlib有一个功能,可以在图形的坐标位置写文字(.figtext())。

有没有办法做到类似的事情,用来画线呢?

我特别想要画一些线,把y轴上的一些刻度线分组在一起。

1 个回答

21
  • python 3.8.12matplotlib 3.4.3 中测试过
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

x = np.linspace(0,10,100)
y = np.sin(x)*(1+x)

fig, ax = plt.subplots()
ax.plot(x,y,label='a')

# new clear axis overlay with 0-1 limits
ax2 = plt.axes([0,0,1,1], facecolor=(1,1,1,0))

x,y = np.array([[0.05, 0.1, 0.9], [0.05, 0.5, 0.9]])
line = Line2D(x, y, lw=5., color='r', alpha=0.4)
ax2.add_line(line)

plt.show()

在这里输入图片描述

但是如果你想和刻度对齐,那为什么不使用绘图坐标呢?

撰写回答