用Python创建信息图表

5 投票
3 回答
8458 浏览
提问于 2025-04-15 15:36

我想用Python制作一个简单的信息图。Matplotlib这个库功能很多,但似乎没有直接能帮我做出我想要的简单热力图的例子。

这个信息图是一个简单的5 x 5的网格,里面的数字范围是从0到1。网格的方块颜色是这样的:0是白色,1是蓝色,0.5是淡蓝色。

我觉得Matplotlib可能可以用,但我找不到合适的例子,也不知道怎么把这些例子结合起来,来生成我想要的效果。

如果有人能提供一些建议、示例代码或者推荐一些库,那就太好了。

谢谢,

马特

3 个回答

2

一种可能的方法是用Python生成SVG文件。你可以在Firefox浏览器或者Inkscape这个软件中查看SVG文件。

下面是一个简单粗糙的例子:

import random

def square(x, y, value):
    r, g, b = value * 255, value * 255, 255
    s = '<rect x="%d" y="%d" width="1" height="1" style="fill:rgb(%d,%d,%d);"/>' % (x, y, r, g, b)
    t = '<text x="%d" y="%d" font-size=".2" fill="yellow">%f</text>' % (x, y + 1, value)
    return s + '\n' + t

print('''
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="100%" height="100%" version="1.1" viewBox="0 0 5 5"
xmlns="http://www.w3.org/2000/svg">
''')
for x in range(0, 5):
    for y in range(0, 5):
        print(square(x, y, random.random()))

print('</svg>')

点击这里查看图片 http://www.imagechicken.com/uploads/1257184721026098800.png

2

PyCairo 是你的好帮手。这里有个简单的例子:

from __future__ import with_statement
import cairo
img = cairo.ImageSurface(cairo.FORMAT_ARGB32,100,100)
g = cairo.Context(img)
for x in range(0,100,10):
    for y in range(0,100,10):
        g.set_source_rgb(.1 + x/100.0, 0, .1 + y/100.0)
        g.rectangle(x,y,10,10)
        g.fill()
with open('test.png','wb') as f:
    img.write_to_png(f)

output

你可能会觉得 这个教程 很有帮助。

4

这要看你想用图表做什么。Matplotlib 让你可以在屏幕上互动地展示图表,还可以把它保存为矢量图、PDF或位图格式,功能很多。

如果你选择这个框架,imshow 就能满足你的需求,下面是一个例子:

# Just some data to test:
from random import gauss
a = [[gauss(0, 10) for i in xrange(0, 5)] for j in xrange(0,5)]

from pylab import * # or just launch "IPython -pylab" from the command line

# We create a custom colormap:
myblue = cm.colors.LinearSegmentedColormap("myblue", {
    'red':   [(0, 1, 1), (1, 0, 0)], 
    'green': [(0, 1, 1), (1, 0, 0)],
    'blue':  [(0, 1, 1), (1, 1, 1)]})

# Plotting the graph:
imshow(a, cmap=myblue)

想了解更多关于颜色映射的信息,可以查看这个链接,还有这个关于 imshow 的链接 - 或者直接使用 help(colors.LinearSegmentedColormap)help(imshow) 来获取帮助。

这里有个图片链接 http://img522.imageshack.us/img522/6230/bluep.png

(注意,这个是使用标准选项得到的结果,你可以添加网格、改变过滤方式等等)。


编辑

不过我想在网格上显示数字。

为了简单起见:

for i in xrange(0,5):
    for j in xrange(0,5):
        text(i, j,
             "{0:5.2f}".format(a[i][j]),
             horizontalalignment="center",
             verticalalignment="center")

撰写回答