首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Plotly (脱机) for Python单击事件

Plotly (脱机) for Python单击事件
EN

Stack Overflow用户
提问于 2017-01-13 01:45:04
回答 2查看 1.8K关注 0票数 4

是否可以将单击事件添加到Plotly散点图(Python中的离线模式)?

例如,我想在单击时更改一组散点的形状。

我到目前为止所尝试的

我从网站上读到的其他问题(没有明确的答案)的理解是,我可能必须生成html,然后在事实发生后通过输入javascript代码进行编辑?这样我就可以编写一个javascript函数,将其保存到my_js.js,然后从html链接到它?

EN

回答 2

Stack Overflow用户

发布于 2018-07-05 09:10:42

我在plots中做了一些离线绘图的工作,也遇到了同样的挑战。

这是我想出的一个技巧,我证明它是对其他人的启发。

一些限制:

对于单个绘图,

  • 假定您在单个html文件中具有脱机输出。
  • 假定on事件的名称与事件handlers.
  • Requires美丽汤4的名称相同。
  • 假定您具有带有Plotly 2.2.2

的lxml lxml

代码片段:

代码语言:javascript
复制
import bs4

def add_custom_plotly_events(
    filename, 
    events = {
        "plotly_click": "function plotly_click(data) { console.log(data); }",
        "plotly_hover": "function plotly_hover(data) { console.log(data); }"
    },
    prettify_html = True
):

    # what the value we're looking for the javascript
    find_string = "Plotly.newPlot"

    # stop if we find this value
    stop_string = "then(function(myPlot)"

    def locate_newplot_script_tag(soup):    
        scripts = soup.find_all('script')
        script_tag = soup.find_all(string=re.compile(find_string))

        if len(script_tag) == 0:
            raise ValueError("Couldn't locate the newPlot javascript in {}".format(filename))
        elif len(script_tag) > 1:
            raise ValueError("Located multiple newPlot javascript in {}".format(filename))

        if script_tag[0].find(stop_string) > -1:
            raise ValueError("Already updated javascript, it contains:", stop_string)

        return script_tag[0]

    def split_javascript_lines(new_plot_script_tag):
        return new_plot_script_tag.string.split(";")

    def find_newplot_creation_line(javascript_lines):
        for index, line in enumerate(javascript_lines):
            if line.find(find_string) > -1:
                return index, line
        raise ValueError("Missing new plot creation in javascript, couldn't find:", find_string)

    def join_javascript_lines(javascript_lines):
        # join the lines with javascript line terminator ;    
        return ";".join(javascript_lines)

    def register_on_events(events):
        on_events_registration = []
        for function_name in events:
            on_events_registration.append("myPlot.on('{}', {})".format(
                function_name, function_name
            ))
        return on_events_registration

    # load the file
    with open(filename) as inf:
        txt = inf.read()
        soup = bs4.BeautifulSoup(txt, "lxml")

    new_plot_script_tag = locate_newplot_script_tag(soup)

    javascript_lines = split_javascript_lines(new_plot_script_tag)

    line_index, line_text = find_newplot_creation_line(javascript_lines)    

    on_events_registration = register_on_events(events)

    # replace whitespace characters with actual whitespace
    # using + to concat the strings as {} in format
    # causes fun times with {} as the brackets in js
    # could possibly overcome this with in ES6 arrows and such
    line_text = line_text + ".then(function(myPlot) { " + join_javascript_lines(on_events_registration) +"  })".replace('\n', ' ').replace('\r', '')

    # now add the function bodies we've register in the on handles
    for function_name in events:
        javascript_lines.append(events[function_name])

    # update the specific line
    javascript_lines[line_index] = line_text

    # update the text of the script tag
    new_plot_script_tag.string.replace_with(join_javascript_lines(javascript_lines))

    # save the file again
    with open(filename, "w") as outf:
        # tbh the pretty out is still ugly af
        if prettify_html:
            for line in soup.prettify(formatter = None):
                outf.write(str(line))
        else:
            outf.write(str(soup))
票数 3
EN

Stack Overflow用户

发布于 2017-04-19 12:37:32

根据Plotly的community site上的Click events in python offline mode?,这是不支持的,至少从2015年12月开始。

这篇文章确实包含了一些关于如何自己实现这个功能的提示,如果你想冒险的话。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41619708

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档