Уже занятая тема, но из того, что я прочитал здесь, следующее помогло мне понять, как она работает внутри:
def bar(a=[]):
print id(a)
a = a + [1]
print id(a)
return a
>>> bar()
4484370232
4484524224
[1]
>>> bar()
4484370232
4484524152
[1]
>>> bar()
4484370232 # Never change, this is 'class property' of the function
4484523720 # Always a new object
[1]
>>> id(bar.func_defaults[0])
4484370232
Из http://matplotlib.sourceforge.net/examples/event_handling/pick_event_demo.html :
from matplotlib.pyplot import figure, show
import numpy as npy
from numpy.random import rand
if 1: # picking on a scatter plot (matplotlib.collections.RegularPolyCollection)
x, y, c, s = rand(4, 100)
def onpick3(event):
ind = event.ind
print 'onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind)
fig = figure()
ax1 = fig.add_subplot(111)
col = ax1.scatter(x, y, 100*s, c, picker=True)
#fig.savefig('pscoll.eps')
fig.canvas.mpl_connect('pick_event', onpick3)
show()
print
также должен использовать parens для совместимости с python 3
– nealmcb
30 April 2017 в 03:15
mplcursors работали для меня. mplcursors предоставляет интерактивную аннотацию для matplotlib. Он сильно вдохновлен mpldatacursor ( https://github.com/joferkington/mpldatacursor ) с гораздо упрощенным API
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
data = np.outer(range(10), range(1, 5))
fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
"Annotations can be dragged.")
mplcursors.cursor(lines) # or just mplcursors.cursor()
plt.show()
mpld3 решает это для меня. EDIT (CODE ADDED):
import matplotlib.pyplot as plt
import numpy as np
import mpld3
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100
scatter = ax.scatter(np.random.normal(size=N),
np.random.normal(size=N),
c=np.random.random(size=N),
s=1000 * np.random.random(size=N),
alpha=0.3,
cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')
ax.set_title("Scatter Plot (with tooltips!)", size=20)
labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)
mpld3.show()
Вы можете проверить пример
TypeError: array([1.]) is not JSON serializable
.
– P-Gn
16 February 2018 в 10:31
Я знаю, что это старый вопрос, но я продолжал прибывать сюда, ища решение для зависания (не нажимать) строки.
import matplotlib.pyplot as plt
fig = plt.figure()
plot = fig.add_subplot(111)
# create some curves
for i in range(4):
plot.plot(
[i*1,i*2,i*3,i*4],
gid=i)
def on_plot_hover(event):
for curve in plot.get_lines():
if curve.contains(event)[0]:
print "over %s" % curve.get_gid()
fig.canvas.mpl_connect('motion_notify_event', on_plot_hover)
plt.show()
matplotlib
...) - работает ли это с ipython
/ jupyter
ноутбуками? Это также работает, когда есть несколько подзаговоров? А как насчет на диаграмме, а не в линейном графике?
– dwanderson
24 January 2017 в 21:17
Небольшое редактирование на примере, представленном в http://matplotlib.org/users/shell.html :
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')
line, = ax.plot(np.random.rand(100), '-', picker=5) # 5 points tolerance
def onpick(event):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print 'onpick points:', zip(xdata[ind], ydata[ind])
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
Это график прямой линии, так как Сохаиб спрашивал