【问题标题】:How to add text to a graph in python如何在python中将文本添加到图形中
【发布时间】:2022-01-10 04:08:59
【问题描述】:

我正在尝试使用 figtext() 在下图中添加文本,但下面的书面代码不起作用。我很感激任何帮助。

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
x = np.array([0.00161, 0.00322, 0.00483, 0.00645, 0.00806])
y = np.array([0.005, 0.006, 0.007, 0.008, 0.013])

a, b = np.polyfit(x, y, 1)
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
slope = round(slope, 4)
intercept = round(intercept, 4)
r_value = r_value
r_squared = round(r_value ** 2, 4)

plt.scatter(x, y, color='purple')
plt.figtext(-25, 25, f"y={slope}x+{intercept}")
plt.figtext(-25, 25, f"R^2={r_squared}")
plt.text(1, 17, 'y = ' + '{:.2f}'.format(b) + ' + {:.2f}'.format(a) + 'x', size=14)
plt.xlabel("Concentration")
plt.ylabel("Absorbance")
plt.title("Phosphorus Calibration Curve")
plt.plot(x, a*x+b, color='steelblue', linestyle='--', linewidth=2)

plt.show()

【问题讨论】:

  • 您是否尝试先阅读figtext 文档,特别是围绕xy 参数的预期? plt.text 也是如此。
  • ax = plt.gca()ax.text(...) 可能更合适。

标签: python python-3.x numpy matplotlib scipy.stats


【解决方案1】:

我认为问题在于您使用的 xy 坐标。

plt.figtext 中的坐标(未转换)在 figure 中 坐标,即在 01 之间浮动。 这个细节在 plt.text 中看起来是另一种方式,默认是 数据坐标。

在我看来,你不应该“混合”这两种方法。

仅使用 figure 坐标和调用 plt.figtext 我改变了你的 绘制代码到:

plt.scatter(x, y, color='purple')
plt.xlabel('Concentration')
plt.ylabel('Absorbance')
plt.title('Phosphorus Calibration Curve')
plt.plot(x, a * x + b, color='steelblue', linestyle='--', linewidth=2)
plt.figtext(0.15, 0.83, f'y = {slope}x + {intercept}')
plt.figtext(0.15, 0.77, f'R^2 = {r_squared}')
plt.figtext(0.15, 0.7,  f'y = {b:.4f} + {a:.4f}x', size=14)
plt.show()

得到:

任意调整上述坐标。

但如果您想使用 plt.text,请使用 data 坐标。 例如。将最后一个 plt.figtext 更改为

plt.text(0.0015, 0.0112,  f'y = {b:.4f} + {a:.4f}x', size=14)

你会得到类似的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多