Python之PyChart画图方法


其实,Python绘图的方式很多,也有很多开源不错的模块可以选择,比如常用于科学计算的MatplotlibCairoplot(需要翻墙)、ChacoPython Google ChartPyChapyOFC2PyChartPLplotReportLabVPython等等。

    这里,我们介绍下PyChart模块,其绘图还是比较方便的,而且绘出的图像也还不错。我们除了需要安装PyChart模块之外,还需要安装Ghostscript和GSview,为了方便大家,PyChart与 GSview下载地址:

免费下载地址在 http://linux.bkjia.com/

用户名与密码都是www.bkjia.com

具体下载目录在 /2012年资料/5月/29日/Python之PyChart画图方法/

    OK,安装完之后,看一个简单的示例代码:

  1. # http://www.bkjia.com/
  2. from pychart import *  
  3.  
  4. class zap_y_coord(linear_coord.T):  
  5.     def get_canvas_pos(self, size, val, minmax):  
  6.         if val <= 70:  
  7.             return linear_coord.T.get_canvas_pos(self, size, val, 0, 110)  
  8.         elif val <= 240:  
  9.             return linear_coord.T.get_canvas_pos(self, size, 70, 0, 110)  
  10.         else:  
  11.             return linear_coord.T.get_canvas_pos(self, size, val - 170, 0, 110)  
  12.     def get_tics(self, minmax, interval):  
  13.         tics = linear_coord.T.get_tics(self, minmax, interval)  
  14.         return [x for x in tics if x < 65 or x > 256]  
  15.  
  16. # can = canvas.default_canvas()  
  17. can = canvas.init('flykite.png')  
  18. theme.scale_factor=3  
  19. theme.use_color=True 
  20. theme.reinitialize()  
  21. data = [(10, 20, 30, 5), (20, 265, 33, 5),  
  22.         (30, 255, 30, 5), (40, 45, 51, 7), (50, 25, 27, 3)]  
  23.  
  24. chart_object.set_defaults(area.T, size = (150, 120), y_range = (0, 280),  
  25.                           y_coord = zap_y_coord(),  
  26.                           x_coord = category_coord.T(data, 0))  
  27. chart_object.set_defaults(bar_plot.T, data = data)  
  28.  
  29. bar_plot.fill_styles.reset();  
  30. plot1=bar_plot.T(label="foo", cluster=(0,3))  
  31. plot2=bar_plot.T(label="bar", hcol=2, cluster=(1,3))  
  32. plot3=bar_plot.T(label="baz", hcol=3, cluster=(2,3))  
  33.  
  34. ar = area.T(loc=(250,0),  
  35.             x_axis=axis.X(label="X label", format="/a-30{}%d"),  
  36.             y_axis=axis.Y(label="Y label", tic_interval=10))  
  37. ar.add_plot(plot1, plot2, plot3)  
  38. ar.draw()  
  39. for x in (ar.x_pos(10) - 20, ar.x_pos(20)- 10, ar.x_pos(30) - 10):  
  40.     zap.zap_horizontally(can, line_style.default, fill_style.white,  
  41.                          x, ar.y_pos(65), x+16, ar.y_pos(65) + 4, 4, 4) 

    为了生成png图片,使用以下命令运行程序:

  1. python flykite.py --format=png 

    图片效果如下:

相关内容