[英]Python Matplotlib: Find the corresponding x value of a given y value on a basic plot
I have a plot generated using Matplotlib (it is a precision-recall curve of a histogram originally) and I need to compute the correct x value which corresponds to the y value with y = 0.9.我有一个使用 Matplotlib 生成的 plot(它最初是直方图的精确召回曲线),我需要计算正确的 x 值,它对应于 y = 0.9 的 y 值。 The data are loaded from text files which are present in columns.
数据是从列中存在的文本文件加载的。 This is the code which is used to create the plot:
这是用于创建 plot 的代码:
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()
Is there any way to compute the correct value on the x axis which corresponds to y = 0.9?有什么方法可以计算出 x 轴上对应于 y = 0.9 的正确值吗?
You can use np.interp()
in the form of x_interp = np.interp(y_vals, y, x)
to interpret an x
value.您可以使用
np.interp()
x_interp = np.interp(y_vals, y, x)
来解释x
值。
If you want to interpret a y
value instead, you need to switch to y_interp = np.interp(x_vals, x, y)
.如果您想改为解释
y
值,则需要切换到y_interp = np.interp(x_vals, x, y)
。
I also added some annotations to the plot to better visualize the result.我还向 plot 添加了一些注释,以更好地可视化结果。 Since the data were not provided, I made up the data for demonstration purposes.
由于没有提供数据,我自己编了个数据做演示。
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])
# added code
y_interp = 0.9
x_interp = round(np.interp(y_interp, precision[:-1], threshold), 4) # x_interp = np.interp(y_vals, y, x)
plt.plot(x_interp, y_interp, 'o')
ax.annotate(f'(x={x_interp}, y={y_interp})', (x_interp, y_interp), size=14, xytext=(x_interp * 1.05, y_interp))
print(f'y = {y_interp}, x = {x_interp}')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.