添加描述绘图点的matlib

2024-09-27 19:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

plt.figure(figsize=(12,8))

plt.plot(range(0, 60), cum_var,'g--', label='explained ratio')
plt.plot(range(0, 60), 1 - cum_var, 'r--', label='error ratio')

thre_95 = 0.95 * np.ones(60)
thre_99 = 0.99 * np.ones(60)
plt.plot(range(0, 60), thre_95, 'k_', label='0.95 threshold')
plt.plot(range(0, 60), thre_99, 'k_', label='0.99 threshold')

idx = np.argwhere(np.isclose(thre_95, cum_var, atol=0.001)).reshape(-1)
idx[0] += 1
plt.plot(idx, thre_95[idx], 'ro')

idx = np.argwhere(np.isclose(thre_99, cum_var, atol=0.0005)).reshape(-1)
idx[0] += 1
plt.plot(idx, thre_99[idx], 'ro')

plt.legend(loc='center right')
plt.xlabel('Reduced Dimensionality')
plt.ylabel('Variance Ratio')
plt.title('Explained Ratio Curve')
plt.axis([0, 60, 0, 1])
plt.grid(True)
plt.show()

它绘制了以下图表:

enter image description here

现在我需要从相交点向下添加x线和y线,以便清楚地显示相交点是什么。我该怎么做?在

编辑:我得到了答案,并设法画出了线,现在我的问题是如何使添加线的x值出现在轴上?在

另一个编辑:找到Answer for edit question


Tags: thresholdplotvarnponesrangepltlabel
1条回答
网友
1楼 · 发布于 2024-09-27 19:33:19

那么,您需要找到两个函数(y_1 = cum_vary_2 = 1 - cum_var)交叉的位置。因为其中一个是一减去另一个,所以当它们交叉时,我们知道它们的值是0.5。所以我们可以做些类似的事情

# Find the index at which `cum_var` is nearest to 0.5
ind_cross = np.argmin(np.fabs(cum_var - 0.5))
# Plot vertical line there
plt.axvline(ind_cross, color='0.5', ls=':')

如果你只想让队伍走到他们交叉的地方,你可以做到

^{pr2}$

如果您想使其更精确,那么您可以创建一个插入式并精确地找到与0.5相交的cum_var最接近的位置,您可以创建一个插入式,并精确地找到与0.5相交的位置(这称为“寻根”),例如:

import scipy as sp
import scipy.interpolate
import scipy.optimize

# Create interpolation function from y-vales to x-vales
interp_func = sp.interpolate.interp1d(cum_var, np.arange(60))
# Find the root (so that interp_func(root) = 0.5)
root = sp.optimize.root(lamda xx: interp_func(xx) - 0.5, 4)

相关问题 更多 >

    热门问题