2017-03-16 123 views
2

我有一個Python值的列表,我正在用matplotlib繪圖。然後,我嘗試在matplotlib中使用ginput來單擊圖上的兩個點,從中獲取X座標,並在這兩個點之間切割我的原始列表。但是,我似乎無法找到辦法做到這一點。如何從matplotlib ginput切片清單?

我已經有一個名爲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) 

這給了我一個數組,但它並不在我的圖表繪製這些值 - 有沒有人有任何意見我做錯了什麼?

謝謝

回答

2

重點是您需要重畫畫布,一旦對畫布進行了更改。因此,爲了使新的圖形變得可見,你可以撥打

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() 
+0

感謝您的解決方案,它清楚地解釋了! – KittenMittons