如何在饼图中创建超链接

发布于 2024-09-24 06:33:43 字数 257 浏览 2 评论 0原文

我想在 matplotlib 中做一个饼图。
该饼图将表示两个变量:男性和女性。

这很容易做到:)

接下来我想做的事,我什至不确定是否可以使用 matplotlib,我想让这两个变量可点击,所以如果我点击male,我会看到另一个页面有关于此的信息,女性也是如此。

图像映射不是解决方案,因为这些变量将来可能会发生变化。

任何人都知道如何做到这一点?如果可以使用 matplotlib 或您推荐什么程序。

谢谢你!

I want to do a pie chart in matplotlib.
This pie chart will be a representation of two variables: male and female.

That's easy to do :)

What I would like to do next, I'm not even sure if it's possible to do with matplotlib, I would like to make these two variables clickable so if I click on male, I would see another page with information about this, same thing with female.

Image map isn't a solution since this variables may change in the future.

Anyone has any idea how to do this? If it's possible with matplotlib or what program would you recommend.

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里°也失望 2024-10-01 06:33:43

虽然它尚未真正处于稳定的工作状态,但请查看 matplotlib 的 html5 canvas 后端。无论如何,它看起来很有趣,并且可能是将来做这类事情(带有 matplotlib 绘图的交互式网页)的最佳方式。

与此同时,正如 @Mark 所建议的,为饼图的楔形动态生成图像映射并不太难。

这是一个粗略的示例,我相信您可以适应任何网络您正在使用的框架。

import matplotlib.pyplot as plt

def main():
    # Make an example pie plot
    fig = plt.figure()
    ax = fig.add_subplot(111)

    labels = ['Beans', 'Squash', 'Corn']
    wedges, plt_labels = ax.pie([20, 40, 60], labels=labels)
    ax.axis('equal')

    make_image_map(fig, wedges, labels, 'temp.html')

def make_image_map(fig, wedges, labels, html_filename):
    """Makes an example static html page with a image map of a pie chart.."""
    #-- Save the figure as an image and get image size ------------------------
    # Be sure to explictly set the dpi when saving the figure
    im_filename = 'temp.png'
    fig.savefig(im_filename, dpi=fig.dpi)

    # Get figure size...
    _, _, fig_width, fig_height = fig.bbox.bounds

    #-- Get the coordinates of each wedge as a string of x1,y2,x2,y2... -------
    coords = []
    for wedge in wedges:
        xy = wedge.get_verts() 

        # Transform to pixel coords
        xy = fig.get_transform().transform(xy) 

        # Format into coord string and convert to <0,0> in top left...
        xy = ', '.join(['%0.2f,%0.2f' % (x, fig_height - y) for x, y in xy])
        coords.append(xy)

    #-- Build web page --------------------------------------------------------
    header = """
    <html>
    <body>
    <img src="{0}" alt="Pie Chart" usemap="#pie_map" width="{1}" height="{2}" />
    """.format(im_filename, fig_width, fig_height)

    # Make the image map
    map = '<map name="pie_map">\n'
    for label, xy in zip(labels, coords):
        href = 'http://images.google.com/images?q={0}'.format(label)
        area = '<area shape="poly" coords="{0}" href="{1}" alt="{2}" />'
        area = area.format(xy, href, label)
        map += '    ' + area + '\n'
    map += '</map>\n'

    footer = """
    </body>
    </html>"""

    # Write to a file...
    with file(html_filename, 'w') as outfile:
        outfile.write(header + map + footer)

if __name__ == '__main__':
    main()

编辑:我刚刚意识到您可能不是指将绘图嵌入到网页中...(我假设您来自问题中的“显示另一个页面”位。)如果您想要更多桌面应用程序,不必搞乱“完整”的 GUI 工具包,你可以做这样的事情:

import matplotlib.pyplot as plt

def main():
    # Make an example pie plot
    fig = plt.figure()
    ax = fig.add_subplot(111)

    labels = ['Beans', 'Squash', 'Corn']
    wedges, plt_labels = ax.pie([20, 40, 60], labels=labels)
    ax.axis('equal')

    make_picker(fig, wedges)
    plt.show()

def make_picker(fig, wedges):
    import webbrowser
    def on_pick(event):
        wedge = event.artist
        label = wedge.get_label()
        webbrowser.open('http://images.google.com/images?q={0}'.format(label))

    # Make wedges selectable
    for wedge in wedges:
        wedge.set_picker(True)

    fig.canvas.mpl_connect('pick_event', on_pick)

if __name__ == '__main__':
    main()

这会打开一个浏览器窗口,用于谷歌图像搜索,无论楔子被标记为...

While it's not really in a workably stable state yet, have a look at the html5 canvas backend for matplotlib. It looks interesting, anyway, and will probably be the best way to do this sort of thing (interactive webpage with a matplotlib plot) in the future.

In the meantime, as @Mark suggested, it's not too hard to dynamically generate an imagemap for the wedges of a pie plot.

Here's a rough example, that I'm sure you could adapt to whatever web framework you're using.

import matplotlib.pyplot as plt

def main():
    # Make an example pie plot
    fig = plt.figure()
    ax = fig.add_subplot(111)

    labels = ['Beans', 'Squash', 'Corn']
    wedges, plt_labels = ax.pie([20, 40, 60], labels=labels)
    ax.axis('equal')

    make_image_map(fig, wedges, labels, 'temp.html')

def make_image_map(fig, wedges, labels, html_filename):
    """Makes an example static html page with a image map of a pie chart.."""
    #-- Save the figure as an image and get image size ------------------------
    # Be sure to explictly set the dpi when saving the figure
    im_filename = 'temp.png'
    fig.savefig(im_filename, dpi=fig.dpi)

    # Get figure size...
    _, _, fig_width, fig_height = fig.bbox.bounds

    #-- Get the coordinates of each wedge as a string of x1,y2,x2,y2... -------
    coords = []
    for wedge in wedges:
        xy = wedge.get_verts() 

        # Transform to pixel coords
        xy = fig.get_transform().transform(xy) 

        # Format into coord string and convert to <0,0> in top left...
        xy = ', '.join(['%0.2f,%0.2f' % (x, fig_height - y) for x, y in xy])
        coords.append(xy)

    #-- Build web page --------------------------------------------------------
    header = """
    <html>
    <body>
    <img src="{0}" alt="Pie Chart" usemap="#pie_map" width="{1}" height="{2}" />
    """.format(im_filename, fig_width, fig_height)

    # Make the image map
    map = '<map name="pie_map">\n'
    for label, xy in zip(labels, coords):
        href = 'http://images.google.com/images?q={0}'.format(label)
        area = '<area shape="poly" coords="{0}" href="{1}" alt="{2}" />'
        area = area.format(xy, href, label)
        map += '    ' + area + '\n'
    map += '</map>\n'

    footer = """
    </body>
    </html>"""

    # Write to a file...
    with file(html_filename, 'w') as outfile:
        outfile.write(header + map + footer)

if __name__ == '__main__':
    main()

Edit: I just realized that you might not be referring to embedding the plot into a web page... (I assumed that you were from the "display another page" bit in your question.) If you want more of a desktop app, without having to mess with a "full" gui toolkit, you can do something like this:

import matplotlib.pyplot as plt

def main():
    # Make an example pie plot
    fig = plt.figure()
    ax = fig.add_subplot(111)

    labels = ['Beans', 'Squash', 'Corn']
    wedges, plt_labels = ax.pie([20, 40, 60], labels=labels)
    ax.axis('equal')

    make_picker(fig, wedges)
    plt.show()

def make_picker(fig, wedges):
    import webbrowser
    def on_pick(event):
        wedge = event.artist
        label = wedge.get_label()
        webbrowser.open('http://images.google.com/images?q={0}'.format(label))

    # Make wedges selectable
    for wedge in wedges:
        wedge.set_picker(True)

    fig.canvas.mpl_connect('pick_event', on_pick)

if __name__ == '__main__':
    main()

Which opens a browser window for a google image search of whatever the wedge is labeled as...

最笨的告白 2024-10-01 06:33:43

您可以使用由 JavaScript/jQuery 控制的图像映射或 HTML 元素覆盖来实现此目的。

本质上,将图表数据与图表图像一起发送到页面,并根据数据的规范使用 JS 创建带有链接的元素。

这比我之前做过的条形图有点难,但应该可以正常工作。

You can do this with an imagemap or HTML element overlay controlled by JavaScript/jQuery.

Essentially, send your chart data to the page along with the chart image, and use JS to create the elements with the links according to the specification of the data.

It's a bit harder than the bar graphs I've done this to before, but should work fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文