Skip to main content
 首页 » 编程设计

python之如何从 matplotlib ginput 中切片列表

2024年10月01日6kevingrace

我有一个 Python 值列表,我正在使用 matplotlib 绘制它。然后我尝试在 matplotlib 中使用 ginput 单击图形上的两个点,从中获取 X 坐标,在它们之间切分我的原始列表。但是,我似乎无法找到执行此操作的方法。

我已经有一个名为 MIList 的号码列表,但以下代码对我不起作用:

startinput = plt.ginput(2) 
print("clicked", startinput) 
startinputxvalues = [x[0] for x in startinput] 
print(startinputxvalues) 
x1 = startinputxvalues[0] 
print(x1) 
x2 = startinputxvalues[1] 
print(x2) 
slicedMIList = [MIList[int(x1):int(x2)]] 
plt.plot(slicedMIList) 

这给了我一个数组,但它没有在我的图表上绘制这些值 - 有人对我做错了什么有任何意见吗?

谢谢

请您参考如下方法:

要点是,一旦对 Canvas 进行了更改,您就需要重新绘制 Canvas 。因此,为了让新情节变得可见,您可以调用

plt.gcf().canvas.draw() 

这是一个完整的工作代码:

import matplotlib.pyplot as plt 
import numpy as np 
 
X = np.arange(10) 
Y = np.sin(X) 
plt.plot(X, Y) 
 
startinput = plt.ginput(2) 
x, y = zip(*startinput) 
 
Ysliced = Y[int(x[0]):int(x[1])+1] 
Xsliced = X[int(x[0]):int(x[1])+1] 
plt.plot(Xsliced, Ysliced, color="C3", linewidth=3) 
 
#draw the canvas, such that the new plot becomes visible 
plt.gcf().canvas.draw() 
 
plt.show()