如何在Matplot绘图中显示数据 [英] How to display data in a matplot plot
问题描述
我正在尝试在jupyter notebook
中进行交互式绘制,但我不知道确切如何实现它.有一个数据框,我运行一个简单的回归,然后绘制该回归以查看分布.我希望能够将鼠标悬停在这些点之一上并获取与此点相关的数据.我怎样才能做到这一点?现在我只能产生一个静态图
I'm trying to make an interactive plot in the jupyter notebook
but i don't know exactly how to implement it. Having a dataframe i run a simple regression that is then plotted to see the distribution. I'd like to be able to hover one of the points and get data associated with this point. How can i do that? Right now i can only produce a static plot
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()
推荐答案
首先,很明显,%matplotlib inline
后端不允许进行交互,因为它是内联的(在某种意义上,图解是图像).
First of all it's clear that the %matplotlib inline
backend does not allow for interaction, as it is inline (in the sense that the plots are images).
但是,即使在笔记本电脑中,您也可以使用%matplotlib notebook
后端进行交互.基本的悬停功能已经实现:在画布上移动鼠标会在右下角的数据坐标中显示当前的鼠标位置.
However even in the notebook you can get interaction using the %matplotlib notebook
backend. A basic hover took is already implemented: Moving the mouse in the canvas shows the current mouse position in data coordinates in the lower right corner.
当然,您可以通过编写一些自定义代码来获得更复杂的功能.例如.我们可以对选择示例进行如下修改: :
Of course you can obtain more sophisticated functionality by writing some custom code. E.g. we can modify the picking example a little bit as follows:
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()
现在显示鼠标单击的点的数据坐标.
This now shows the data coordinates of the point the mouse has clicked.
您可以自由地将其适应任何情况,并使用标准的matplotlib工具使其更美观.
You're pretty free to adapt this to any case you like and make it more pretty using the standard matplotlib tools.
这篇关于如何在Matplot绘图中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!