事前準備:
下載並安裝:
Cairo:
http://www.lfd.uci.edu/~gohlke/pythonlibs/bux9zozk/pycairo-1.10.0.win32-py2.7.exe
Pycha:
https://bitbucket.org/lgs/pycha/get/e3e270a0e7ae.zip
簡單的程序示例如下(包括餅圖和直方圖):
#!/usr/bin/env python
# -*-coding:utf-8-*-
import pycha.pie
import pycha.bar
import pycha.stackedbar
import pycha.scatter
#設置畫布
def set_surface():
width,height=700,700
surface=cairo.ImageSurface(cairo.FORMAT_ARGB32,width,height)[A2]
return surface
#餅圖
def draw_pie(surface,options,dataSet):
chart=pycha.pie.PieChart(surface,options)
chart.addDataset(dataSet)
surface.write_to_png('D:\\Pie.png')
#垂直立方圖
defdraw_vertical_bar(surface,options,dataSet):
chart=pycha.bar.HorizontalBarChart(surface,options)
chart.addDataset(dataSet)
chart.render()
surface.write_to_png('d:\\VerticalBar.png')
if __name__=='__main__':
#設置數據
dataSet=(
('IBM',((1,3),(2,4),(3,6))),
('HP',((1,3.3),(2.1,4.3),(2,5))),
('DELL',((2,3.3),(3.1,3.3),(3,5))),
)
#設置圖像屬性
options={
'legend':{'hide':False},
'title':'服務器銷售分佈圖(design byWoody)',
'titleColor':'#0000ff',
'titleFont':'字體',
'background':{'chartColor':'#00fff0'},
'axis':{'labelColor':'#ff000'},
}
surface=set_surface()
#調用不同的方法生成相應的銷售圖表
draw_pie(surface,options,dataSet)
draw_vertical_bar(surface,options,dataSet)
運行結果圖如下:
Python isPython!
關於ImageSurface:
Creates an image surface of the specifiedformat and dimensions. Initially the surface contents are all 0. (Specifically,within each pixel, each color or alpha channel belonging to format will be 0.The contents of bits within a pixel, but not belonging to the given format areundefined).
format : |
format of pixels in the surface to create |
width : |
width of the surface, in pixels |
height : |
height of the surface, in pixels |
Returns : |
a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy() when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this. |