虽然它还没有达到可用的稳定状态,但请看一下matplotlib的html5画布后端。无论如何,它看起来很有趣,并且可能是未来完成这种事情(具有matplotlib图的交互式网页)的最佳方式。
与此同时,正如@Mark所建议的那样,动态生成饼图楔形区域的图像映射并不太难。
这里有一个粗略的示例,我相信您可以根据自己使用的任何Web框架进行适应。
import matplotlib.pyplot as plt
def main():
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.."""
im_filename = 'temp.png'
fig.savefig(im_filename, dpi=fig.dpi)
_, _, fig_width, fig_height = fig.bbox.bounds
coords = []
for wedge in wedges:
xy = wedge.get_verts()
xy = fig.get_transform().transform(xy)
xy = ', '.join(['%0.2f,%0.2f' % (x, fig_height - y) for x, y in xy])
coords.append(xy)
header = """
<html>
<body>
<img src="{0}" alt="Pie Chart" usemap="#pie_map" width="{1}" height="{2}" />
""".format(im_filename, fig_width, fig_height)
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>"""
with file(html_filename, 'w') as outfile:
outfile.write(header + map + footer)
if __name__ == '__main__':
main()
编辑:我刚意识到你可能不是在指将图表嵌入网页...(我假设你是从你的问题中的“显示另一页”那一点上得出的结论。)如果你想要更像桌面应用程序,而不必去烦恼一个“完整”的 GUI 工具包,你可以像这样做:
import matplotlib.pyplot as plt
def main():
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))
for wedge in wedges:
wedge.set_picker(True)
fig.canvas.mpl_connect('pick_event', on_pick)
if __name__ == '__main__':
main()
这将打开一个浏览器窗口,搜索以楔子标记的任何内容的谷歌图片...
<img src="filename.png" />
,然后基于饼图中的楔形生成已保存图像的映像。 (Stackoverflow的语法突出显示在所有具有嵌套"
,'
和"""
的字符串中都有点问题)关键是在“#-获取每个楔形的坐标...
”下面的循环。 我只是抓取每个楔形的顶点,将它们转换为已保存图像的像素坐标,并生成包含这些坐标的字符串。希望这可以帮助! - Joe Kington