如何旋转 Matplotlib 注解以与线匹配?


要旋转 matplotlib 注解以匹配一条线,我们可以采取以下步骤 -

  • 使用 figure() 方法创建一个新图形或激活一个现有的图形。
  • 使用 add_subplot() 方法将一个 '~.axes.Axes' 添加到图形中作为子图布局的一部分。
  • 初始化变量,m(斜率)和 c(截距)。
  • 使用 numpy 创建 x 和 y 数据点。
  • 计算 theta 以进行文本旋转。
  • 使用 plot() 方法并使用 x 和 y绘制线条。
  • 使用 text() 方法在行上放置文本。
  • 要显示该图形,请使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot()
m = 1
c = 1
x = np.linspace(-2, 2, 10)
y = m*x + c
theta = np.arctan(m)
line, = ax.plot(x, y)
ax.text(x=x[2], y=y[2]+.25, s="y=mx+c", rotation=180.0*(1-theta), fontsize=15, color='green')
plt.show()

输出

更新于: 2021 年 5 月 15 日

3K+ 浏览

启动你的职业生涯

通过完成该课程获得认证

开始
广告
© . All rights reserved.