【问题标题】:how to create hyperlink in piechart如何在饼图中创建超链接
【发布时间】:2011-04-15 02:12:44
【问题描述】:

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

这很容易做到:)

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

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

有人知道怎么做吗?如果可以使用 matplotlib 或您推荐什么程序。

谢谢!

【问题讨论】:

    标签: javascript jquery python matplotlib hyperlink


    【解决方案1】:

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

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

    Here's a rough example,我相信你可以适应你正在使用的任何网络框架。

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

    这会打开一个浏览器窗口,用于谷歌图像搜索任何楔形标记为...

    【讨论】:

    • 谢谢乔,很多细节和例子。非常好:) 我正在尝试用 django 和 html 来实现它。但我真的不明白你的html。通常我把链接放到图片或保存位置
    • @Patricia - 这就是我在第一个示例中所做的一切......它只是将图像保存到磁盘,插入&lt;img src="filename.png" /&gt;,然后为保存的图像生成图像映射基于饼图中的楔形。 (Stackoverflow 的语法突出显示对于嵌套 "'""" 的所有字符串来说有点不稳定)关键是“#-- Get the coords of each wedge...”位下方的 for 循环。我只是抓取每个楔形的顶点,将它们转换为保存图像的像素坐标,并使用这些坐标生成一个字符串。希望有帮助!
    • 好吧,我认为我的错误在某个地方,因为当我将变量传递给模板时,它什么也没做
    • @Patricia - 第一个示例应创建两个文件...“temp.png”,以及您作为文件名传递给函数的任何内容(示例中为“temp.html”)...
    • 谢谢乔。仍然无法做到,但我会尝试:)
    【解决方案2】:

    您可以使用由 JavaScript/jQuery 控制的图像映射或 HTML 元素覆盖来做到这一点。

    本质上就是把你的图表数据和图表图片一起发送到页面,根据数据的规范用JS创建带有链接的元素。

    这比我以前做过的条形图要难一些,但应该可以正常工作。

    【讨论】:

    • 如果数据总是相同的,那真的很容易,一张图像地图就可以了。但数据可能会有所不同,因此必须单独计算。 js 或 jq 会这样做吗?
    • 是的,您可以使用 javascript/jquery 以任何可以想象的方式创建和修改元素。稍后我会看看是否可以提供代码示例。
    猜你喜欢
    • 2013-08-07
    • 2020-04-18
    • 2016-10-16
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    相关资源
    最近更新 更多