How to display data in a matplot plot

落花浮王杯 提交于 2019-12-08 02:04:47

问题


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

回答1:


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).

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.

You're pretty free to adapt this to any case you like and make it more pretty using the standard matplotlib tools.



来源:https://stackoverflow.com/questions/42703278/how-to-display-data-in-a-matplot-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!