Python Matplotlib:在基本图上查找给定 y 值对应的 x 值

sus*_*sko 7 python matplotlib roc

我有一个使用 Matplotlib 生成的图(它最初是直方图的精确回忆曲线),我需要计算与 y = 0.9 的 y 值相对应的正确 x 值。数据是从列中存在的文本文件加载的。这是用于创建绘图的代码:

import numpy as np
import matplotlib.pyplot as plt
import pylab
from sklearn import metrics

data1 = np.loadtxt('text1.txt')
data2 = np.loadtxt('text2.txt')

background = 1 - (1 + y) / 2.
signal = 1 - (1 + x) / 2.

classifier_output = np.concatenate([background,signal])
true_value = np.concatenate([np.zeros_like(background, dtype=int), np.ones_like(signal,  dtype=int)])

precision, recall, threshold = metrics.precision_recall_curve(true_value, classifier_output)
plt.plot(threshold, precision[:-1])
plt.savefig('Plot.pdf', dpi = 2000)
plt.show()
Run Code Online (Sandbox Code Playgroud)

有没有办法计算 x 轴上对应于 y = 0.9 的正确值? 在此输入图像描述

コリン*_*コリン 1

参考:https://numpy.org/doc/stable/reference/ generated/numpy.interp.html

您可以使用np.interp()的形式x_interp = np.interp(y_val, y, x)来解释x值。

如果您想解释一个y值,则需要切换到y_interp = np.interp(x_val, x, y).

我还在图中添加了虚线和注释,以便更好地可视化结果。由于没有提供数据,我为了演示目的而编造了数据。

import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics

# make up some data
background = np.linspace(0, 1, 400)
signal = np.linspace(0, 2, 400)

classifier_output = np.concatenate([background, signal])
true_value = np.concatenate([np.zeros_like(background, dtype=int), np.ones_like(signal, dtype=int)])

fig, ax = plt.subplots()
precision, recall, threshold = metrics.precision_recall_curve(true_value, classifier_output)
plt.plot(threshold, precision[:-1])

# interpreting x value based on y value
y_val = 0.9
x_interp = round(np.interp(y_val, precision[:-1], threshold), 4)  # x_interp = np.interp(y_vals, y, x)

# place a marker on point (x_interp, y_val)
plt.plot(x_interp, y_val, 'o', color='k')

# draw dash lines
plt.plot([x_interp, threshold[0]], [y_val, y_val], '--', color='k')
plt.plot([x_interp, x_interp], [precision[:-1][0], y_val], '--', color='k')

# add annotation on point (x_interp, y_val)
ax.annotate(f'(x={x_interp}, y={y_val})', (x_interp, y_val), size=14, xytext=(x_interp * 1.05, y_val))

# remove the margin around the starting point (depending on the data's lower bound, adjust or remove if necessary)
ax.set_xlim(threshold[0])
ax.set_ylim(precision[:-1][0])
plt.tight_layout()
print(f'y = {y_val}, x = {x_interp}')
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述