2017-03-09 83 views
1

我試圖在jupyter notebook中創建一個交互式圖,但我不知道如何實現它。有一個數據框我運行一個簡單的迴歸,然後繪製看到分佈。我希望能夠懸停其中的一點並獲得與這一點相關的數據。我怎樣才能做到這一點?現在我只能產生靜態情節 enter image description here如何在matplot圖中顯示數據

import pandas as pd 
from sklearn import linear_model 
%matplotlib inline 
import matplotlib 
import matplotlib.pyplot as plt 

net = pd.read_csv("network_ver_64.csv") 
net = net[net.AWDT12 > 0] 

x = net.LOAD_DAILY.values 
y = net.AWDT12.values 
x_lenght = int(x.shape[0]) 
y_lenght = int(y.shape[0]) 
x = x.reshape(x_lenght, 1) 
y = y.reshape(y_lenght,1) 
regr = linear_model.LinearRegression() 
regr.fit(x, y) 

plt.scatter(x, y, color='black') 
plt.plot(x, regr.predict(x), color='blue', linewidth=1) 
plt.xticks(()) 
plt.yticks(()) 
plt.show() 
+1

據我所知,你不能用matplotlib獲得懸停功能。你必須嘗試[d3.js](https://d3js.org/)或[bokeh](http://bokeh.pydata.org/en/latest/) –

+0

@MainulIslam很好。是的,我不知道這些模塊,虐待他們瞭解他們 –

+0

[Plot.ly](https://plot.ly/python/)也值得檢查你想做什麼。 – gcalmettes

回答

4

首先,很明顯的是,後端%matplotlib inline不允許進行互動,因爲它是內聯(在這個意義上,該地塊是圖像)。

但即使在筆記本中,您也可以使用%matplotlib notebook後端進行交互。已經實現了基本的懸停功能:在畫布中移動鼠標可以在右下角的數據座標中顯示當前的鼠標位置。

enter image description here

當然你也可以通過編寫一些自定義代碼獲得更先進的功能。例如。我們可以通過修改picking example有點如下:

import matplotlib.pyplot as plt 
%matplotlib notebook 
import numpy as np 

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.set_title('click on points') 

line, = ax.plot(np.random.rand(100), 'o', picker=5) # 5 points tolerance 
text = ax.text(0,0,"") 
def onpick(event): 
    thisline = event.artist 
    xdata = thisline.get_xdata() 
    ydata = thisline.get_ydata() 
    ind = event.ind 
    text.set_position((xdata[ind], ydata[ind])) 
    text.set_text(zip(xdata[ind], ydata[ind])) 

fig.canvas.mpl_connect('pick_event', onpick) 

plt.show() 

現在,這顯示了鼠標點擊了點的座標數據。

enter image description here

你很自由地這個適應任何你喜歡的情況下,它更漂亮使用標準matplotlib工具使。