Как заставить mpld3 работать с Seaborn (интерактивные подсказки)

Кажется, я не могу заставить интерактивные всплывающие подсказки, основанные на mpld3, работать с фантастическими графиками рассеяния, похожими на lmplot, от Seaborn.

Я хотел бы любой указатель на то, как заставить это работать! Спасибо!

Пример кода:

# I'm running this in an ipython notebook.
%matplotlib inline
import matplotlib.pyplot as plt, mpld3
mpld3.enable_notebook()
import seaborn as sns


N=10
data = pd.DataFrame({"x": np.random.randn(N),
                     "y": np.random.randn(N), 
                     "size": np.random.randint(20,200, size=N),
                     "label": np.arange(N)
                     })


scatter_sns = sns.lmplot("x", "y", 
           scatter_kws={"s": data["size"]},
           robust=False, # slow if true
           data=data, size=8)
fig = plt.gcf()

tooltip = mpld3.plugins.PointLabelTooltip(fig, labels=list(data.label))
mpld3.plugins.connect(fig, tooltip)

mpld3.display(fig)

Я получаю морской сюжет вместе со следующей ошибкой:

Javascript error adding output!
TypeError: obj.elements is not a function
See your browser Javascript console for more details.

Консоль показывает:

TypeError: obj.elements is not a function
    at mpld3_TooltipPlugin.draw (https://mpld3.github.io/js/mpld3.v0.2.js:1161:9)
    at mpld3_Figure.draw (https://mpld3.github.io/js/mpld3.v0.2.js:1400:23)
    at Object.mpld3.draw_figure (https://mpld3.github.io/js/mpld3.v0.2.js:18:9)
    at eval (eval at <anonymous> (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231), <anonymous>:14:14)
    at eval (eval at <anonymous> (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231), <anonymous>:15:5)
    at eval (native)
    at Function.x.extend.globalEval (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231)
    at x.fn.extend.domManip (https://mbcomp1:9999/static/components/jquery/jquery.min.js:5:21253)
    at x.fn.extend.append (https://mbcomp1:9999/static/components/jquery/jquery.min.js:5:18822)
    at OutputArea._safe_append (https://mbcomp1:9999/static/notebook/js/outputarea.js:336:26)
outputarea.js:319 Javascript error adding output! TypeError: obj.elements is not a function
    at mpld3_TooltipPlugin.draw (https://mpld3.github.io/js/mpld3.v0.2.js:1161:9)
    at mpld3_Figure.draw (https://mpld3.github.io/js/mpld3.v0.2.js:1400:23)
    at Object.mpld3.draw_figure (https://mpld3.github.io/js/mpld3.v0.2.js:18:9)
    at eval (eval at <anonymous> (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231), <anonymous>:14:14)
    at eval (eval at <anonymous> (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231), <anonymous>:15:5)
    at eval (native)
    at Function.x.extend.globalEval (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231)
    at x.fn.extend.domManip (https://mbcomp1:9999/static/components/jquery/jquery.min.js:5:21253)
    at x.fn.extend.append (https://mbcomp1:9999/static/components/jquery/jquery.min.js:5:18822)
    at OutputArea._safe_append (https://mbcomp1:9999/static/notebook/js/outputarea.js:336:26)
outputarea.js:338 TypeError: obj.elements is not a function
    at mpld3_TooltipPlugin.draw (https://mpld3.github.io/js/mpld3.v0.2.js:1161:9)
    at mpld3_Figure.draw (https://mpld3.github.io/js/mpld3.v0.2.js:1400:23)
    at Object.mpld3.draw_figure (https://mpld3.github.io/js/mpld3.v0.2.js:18:9)
    at eval (eval at <anonymous> (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231), <anonymous>:14:14)
    at eval (eval at <anonymous> (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231), <anonymous>:15:5)
    at eval (native)
    at Function.x.extend.globalEval (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231)
    at x.fn.extend.domManip (https://mbcomp1:9999/static/components/jquery/jquery.min.js:5:21253)
    at x.fn.extend.append (https://mbcomp1:9999/static/components/jquery/jquery.min.js:5:18822)
    at OutputArea._safe_append (https://mbcomp1:9999/static/notebook/js/outputarea.js:336:26)
outputarea.js:319 Javascript error adding output! TypeError: obj.elements is not a function
    at mpld3_TooltipPlugin.draw (https://mpld3.github.io/js/mpld3.v0.2.js:1161:9)
    at mpld3_Figure.draw (https://mpld3.github.io/js/mpld3.v0.2.js:1400:23)
    at Object.mpld3.draw_figure (https://mpld3.github.io/js/mpld3.v0.2.js:18:9)
    at eval (eval at <anonymous> (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231), <anonymous>:14:14)
    at eval (eval at <anonymous> (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231), <anonymous>:15:5)
    at eval (native)
    at Function.x.extend.globalEval (https://mbcomp1:9999/static/components/jquery/jquery.min.js:4:4231)
    at x.fn.extend.domManip (https://mbcomp1:9999/static/components/jquery/jquery.min.js:5:21253)
    at x.fn.extend.append (https://mbcomp1:9999/static/components/jquery/jquery.min.js:5:18822)
    at OutputArea._safe_append (https://mbcomp1:9999/static/notebook/js/outputarea.js:336:26)

person Tim    schedule 17.07.2015    source источник


Ответы (3)


Я не думаю, что в настоящее время есть простой способ сделать это. Я могу получить некоторые всплывающие подсказки, заменив ваш конструктор tooltip следующим:

ax = plt.gca()
pts = ax.get_children()[3]
tooltip = mpld3.plugins.PointLabelTooltip(pts, labels=list(data.label))

Однако это работает только для точек вне интервала неопределенности. Я думаю, что было бы возможно расширить seaborn, чтобы сделать эти точки самыми высокими в zorder и сохранить их где-то в экземпляре, чтобы вам не нужно было вытаскивать их из списка дочерних элементов оси. Возможно, стоит попросить функцию.

person Abraham D Flaxman    schedule 29.07.2015
comment
Вот блокнот, показывающий, как это выглядит. - person Abraham D Flaxman; 29.07.2015

Мне удалось заставить всплывающие подсказки работать, используя стандартный разброс matplotlib поверх графика морского происхождения и очень низкую альфу (вы не можете использовать ноль)

data_tip_points = ax.scatter(x_points, y_points, alpha=0.001)
tooltip = plugins.PointLabelTooltip(data_tip_points, labels)

Это немного хак, но он работает, как показано здесь.

http://nbviewer.ipython.org/urls/bitbucket.org/jeff_mcgehee/cds_presentation_intro/raw/49cc7808ec26adebec94ffa83973bb5db13017d7/CDS%20Intro%20Presentation.ipynb

person Jeff M.    schedule 13.08.2015

Ваш код работает для меня на ipython (без блокнота) при сохранении рисунка в файл с помощью mpld3.save_html(fig,"./out.html"). Может быть проблема с совместимостью ipython notepad/mpld3 или mpld3.display (что вызывает у меня ошибку, хотя я думаю, что это связано со старой версией matplotlib на моем компьютере).

Полный код, который работал у меня,

import numpy as np
import matplotlib.pyplot as plt, mpld3
import seaborn as sns
import pandas as pd

N=10
data = pd.DataFrame({"x": np.random.randn(N),
                     "y": np.random.randn(N), 
                     "size": np.random.randint(20,200, size=N),
                     "label": np.arange(N)
                     })


scatter_sns = sns.lmplot("x", "y", 
           scatter_kws={"s": data["size"]},
           robust=False, # slow if true
           data=data, size=8)
fig = plt.gcf()

tooltip = mpld3.plugins.PointLabelTooltip(fig, labels=list(data.label))
mpld3.plugins.connect(fig, tooltip)

mpld3.save_html(fig,"./out.html")
person Ed Smith    schedule 17.07.2015
comment
К сожалению, я получаю ту же ошибку даже при экспорте в html. В случае, если это проблема версии. Я использую: mpld3 0.2 matplotlib 1.4.3 seaborn 0.5.1 - person Tim; 17.07.2015