欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python使用reportlab画图示例(含中文汉字)

程序员文章站 2023-01-13 15:09:51
准备工作 开发环境:python2.6,reportlab 准备中文字体文件:simsun.ttc 代码: 复制代码 代码如下:#!/usr/bin/env pyt...

准备工作

开发环境:python2.6,reportlab

准备中文字体文件:simsun.ttc

代码:

复制代码 代码如下:

#!/usr/bin/env python2.6
#coding:utf-8

import traceback

from reportlab.graphics.shapes import drawing
from reportlab.graphics.charts.lineplots import lineplot
from reportlab.graphics.charts.textlabels import label
from reportlab.graphics import renderpdf
from reportlab.graphics.widgets.markers import makemarker
from reportlab.pdfbase import pdfmetrics, ttfonts

#注意data的类型,
#每一个数据点是一个元组
#一条曲线对应一个存储数据点元组的元组
#一个图形可以包含多条曲线,用列表存储曲线元组
data=[((1,100),(2,200),(3,300),(4,400),(5,500)),((1,50),(2,80),(3,400),(4,40),(5,70))]

drawing = drawing(500, 300)

lp = lineplot()
lp.x = 50 #坐标轴中心坐标
lp.y = 30
lp.height = 250
lp.width = 400
lp.data = data
lp.joinedlines = 1
lp.lines.symbol = makemarker('filledcircle')

lp.xvalueaxis.valuemin = 1
lp.xvalueaxis.valuemax = 5
lp.xvalueaxis.valuestep = 1

lp.yvalueaxis.valuemin = 0
lp.yvalueaxis.valuemax = 500
lp.yvalueaxis.valuestep = 100
drawing.add(lp)

title = label()
#若需要显示中文,需要先注册一个中文字体
pdfmetrics.registerfont(ttfonts.ttfont("haha", "simsun.ttc"))
title.fontname   = "haha"
title.fontsize   = 12
title_text = unicode('你好','gbk')
#title_text = "abc"
title._text = title_text
title.x          = 250
title.y          = 280
title.textanchor ='middle'
drawing.add(title)

xlabel = label()
xlabel._text = 'x'
xlabel.fontsize   = 12
xlabel.x          = 480
xlabel.y          = 30
xlabel.textanchor ='middle'
drawing.add(xlabel)

ylabel = label()
ylabel._text = "y"
ylabel.fontsize   = 12
ylabel.x          = 40
ylabel.y          = 295
ylabel.textanchor ='middle'
drawing.add(ylabel)

try:
     drawing.save(formats=['gif'],outdir=".",fnroot="abc")
except:
     traceback.print_exc()