Plotly(离线版)用于Python的点击事件

4

有没有办法在 Python 的离线模式下给 Plotly 散点图添加点击事件?

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

我已经尝试过的方法

我从阅读本站的其他问题(没有明确答案)中了解到,可能需要先生成 HTML,然后通过放入 JavaScript 代码来编辑它。因此,我可以编写一个 JavaScript 函数,将其保存到 my_js.js 中,然后从 HTML 中链接至该函数。

2个回答

3

我一直在使用plotly进行离线绘图,并面临着同样的挑战。

这是我想出来的一个临时解决方法,可能会给其他人提供启示。

一些限制:

  • 假设您将离线输出保存在单个html文件中,用于单个图形。
  • 假设您的on事件与事件处理程序的名称相同。
  • 需要安装Beautiful Soup 4。
  • 假设您已经安装了lxml。
  • 使用Plotly 2.2.2开发。

代码片段:

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

你如何使用这个函数?如果你能展示一个(基本的)例子,那就太好了! - Kristada673
作为报告生成过程的一部分,我生成了一些Plotly散点图(州的聚合和州以下区域的聚合)。由于防火墙的限制,我需要将它们转换为离线图。我使用了onclick功能来在州级别聚合和区域级别聚合之间进行切换。 - Ryan Collingwood

1
根据Plotly社区网站上点击Python离线模式事件?帖子,至少截至2015年12月还不支持此功能。

如果你感到有冒险精神,该帖子中包含了一些实现此功能的提示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接