Reportlab生成PDF文件

 

带动态标签的面积曲线图:

        - y轴标签最后一个的格式跟其他不同

        - 选定的图表数据在图表上的位置和标签

        - x轴属性chart.xValueAxis.specialTickClear=True的效果

        - 用self.chart.xValueAxis.xLabelFormat = '{dd}/{mm}/{yyyy}'设置x轴刻度标签的格式

代码与注释:

"带动态标签的面积图"
# 面积曲线图
from reportlab.graphics.charts.lineplots import AreaLinePlot
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String, Line
from reportlab.lib.colors import PCMYKColor, black, blue, red, purple
from reportlab.graphics.charts.axes import NormalDateXValueAxis
from reportlab.graphics.charts.textlabels import Label
from myStyle import *
class DynamicLabel(Label):
    def __init__(self,text,ux,uy,**kw):
        """
        text: 标签内容
        ux:   标签在坐标轴上的x坐标
        uy:   标签在坐标轴上的y坐标
        """
        Label.__init__(self,**kw)
        self._text = text
        self._ux = ux
        self._uy = uy

    def asAnnotation(self,chart,xscale,yscale):
        # 见名知意,这个函数相当于annotation属性赋值经常用到的lambda表达式
        self.x = xscale(self._ux)
        self.y = yscale(self._uy)
        # 动态标签的位置

class AreaChart_WithDynamicLabel(_DrawingEditorMixin,Drawing):
    def __init__(self,width=400,height=150,*args,**kw):
        Drawing.__init__(self, width, height, *args, **kw)

        fontName = 'Helvetica'
        gridStickOut = 4
        strokeDashArray = (0.4,0.4)

        # 图表
        self._add(self,AreaLinePlot(),name='chart',validate=None,desc=None)
        self.chart.x                                = 50
        self.chart.y                                = 30
        # 图表左下角坐标
        self.chart.width                            = 305
        self.chart.height                           = 100
        # 图表宽高
        self.chart.lines[0].strokeColor             = PCMYKColor(100, 0, 90, 50, alpha=40)
        # 既决定图表上数据线的颜色又决定面积图内的填充颜色

        # x轴
        self.chart.xValueAxis = NormalDateXValueAxis()
        # x轴是日期轴
        self.chart.xValueAxis.labels.boxAnchor      ='autox'
        self.chart.xValueAxis.labels.fontName       = fontName
        self.chart.xValueAxis.labels.fontSize       = 6
        self.chart.xValueAxis.labels.topPadding     = 3
        # x轴上刻度标签的锚点、字体、字体大小、上留白
        # 刻度标签的日期格式
        self.chart.xValueAxis.strokeWidth           = 0.5
        self.chart.xValueAxis.strokeDashArray       = strokeDashArray
        # x轴线和刻度线的宽度和样式
        self.chart.xValueAxis.visibleTicks          = True
        # 刻度可见
        # self.chart.xValueAxis.forceEndDate          = 1
        # 图表数据的最后一个日期刻度标签要显示在轴线上
        # self.chart.xValueAxis.forceFirstDate        = 1
        # 图表数据第一个日期的刻度标签显示在x轴上        
        # self.chart.xValueAxis.specialTickClear      = 1
        # 如果属性forceFirstDate/forceEndDate为1,为了标第一个或最后一个标签。
        # 第一第二或最后两个刻度标签之间有时会清掉原来的刻度线
        # 如果specialTickClear属性设为1,则显示那个临近刻度线。
        self.chart.xValueAxis.maximumTicks          = 6
        # 属性注释上说最多六个刻度线,现在明明显示7个,是不是最多六个刻度标签?

        # y轴
        self.chart.yValueAxis.labels.fontName       = fontName
        self.chart.yValueAxis.labels.fontSize       = 6
        self.chart.yValueAxis.labels.rightPadding   = 0
        # 刻度标签的字体、大小和右留白
        self.chart.yValueAxis.labelTextFormat       = lambda v,a=self.chart.yValueAxis: (abs(v-a._valueMax)<1e-6 and '¥{}' or '{}').format(v)
        # 刻度标签的格式是动态的,最大值的标签的格式与其他不同
        # 用<1e-6而不是<0,是因为计算机存储的实数是一个“近似值”,相等的判断也要用近似法。
        # 以下是逻辑运算符连接字符串和True/False的运算结果
        # True and 'cat'     'cat'
        # False and 'cat'    'False'
        # True or 'cat'      'True'
        # False or 'cat'     'cat'
        # 'dog' or 'cat'     'dog'
        # 'dog' and 'cat'    'cat'
        # 所以lambda表达式首先判断刻度值是不是最大值,最大值有自己的格式
        self.chart.yValueAxis.forceZero             = 1
        self.chart.yValueAxis.strokeWidth           = 0
        self.chart.yValueAxis.strokeDashArray       = strokeDashArray
        self.chart.yValueAxis.origShiftIPC          = 0
        # self.chart.yValueAxis.origShiftIPC          = 0.5
        # self.chart.yValueAxis.origShiftIPC          = 1
        # y轴上0坐标的位置,单位是刻度比例
        self.chart.yValueAxis.visibleTicks          = True
        # 刻度可见
        self.chart.yValueAxis.maximumTicks          = 6
        # 最多6个刻度
        self.chart.yValueAxis.rangeRound            ='both'
        # 刻度上下值如何取值,None、ceiling、floor和both
        self.chart.yValueAxis.visibleGrid           = 1
        # 格子线设置
        self.chart.yValueAxis.gridStrokeColor             = blue
        self.chart.yValueAxis.gridStrokeDashArray   = strokeDashArray
        self.chart.yValueAxis.gridStart             = self.chart.x-gridStickOut
        self.chart.yValueAxis.gridEnd               = self.chart.x+self.chart.width+gridStickOut
        # 格子线可见、样式、起点和终点
        # 设置子格子线和子刻度线
        self.chart.yValueAxis.visibleSubTicks       = True
        # self.chart.yValueAxis.subTickLo = 3
        # self.chart.yValueAxis.subTickHi = 0
        # 子刻度线可见以及左右各伸出多长
        self.chart.yValueAxis.subTickNum            = 2
        # 格子间的子刻度和子格子线有几条,这个值如果不设,子格子线不显示
        self.chart.yValueAxis.visibleSubGrid        = True
        self.chart.yValueAxis.subGridStrokeWidth    = self.chart.yValueAxis.gridStrokeWidth
        # self.chart.yValueAxis.subGridStrokeColor = purple
        self.chart.yValueAxis.subGridStrokeDashArray= strokeDashArray
        self.chart.yValueAxis.subGridStart              = self.chart.yValueAxis.gridStart
        self.chart.yValueAxis.subGridEnd                = self.chart.yValueAxis.gridEnd
        # 子格子线可见、宽度、颜色、样式、起点和终点

        # 图表数据
        self.chart.data = [(20030220, 10020.0), (20030331, 9910.0), (20030430, 10240.0), (20030530, 10660.0), (20030630, 10680.0), (20030731, 10690.0), (20030829, 10850.0), (20030930, 10760.0), (20031031, 11170.0), (20031128, 11280.0), (20031231, 11553.190000000001),
                           (20040130, 11635.57), (20040227, 11707.65), (20040331, 11635.57), (20040430, 11388.440000000001), (20040528, 11460.52), (20040630, 11651.870000000001), (20040730, 11233.110000000001), (20040831, 11306.4), (20040930, 11358.74), (20041029, 11536.709999999999), (20041130, 11945.0), (20041231, 12295.450000000001),
                           (20050131, 11966.209999999999), (20050228, 12102.450000000001), (20050331, 11932.15), (20050429, 11716.440000000001), (20050531, 12034.33), (20050630, 11991.209999999999), (20050729, 12426.84), (20050831, 12254.879999999999), (20050930, 12289.280000000001), (20051031, 12128.780000000001), (20051130, 12564.41), (20051230, 12584.99),
                           (20060131, 12967.76), (20060228, 12921.360000000001), (20060331, 13257.74), (20060428, 13338.93), (20060531, 12874.969999999999), (20060630, 12857.6), (20060731, 12834.35), (20060831, 12985.48), (20060929, 13171.49), (20061031, 13555.120000000001), (20061130, 13776.0), (20061229, 13886.870000000001),
                           (20070131, 14053.4), (20070228, 13848.43), (20070330, 13925.299999999999), (20070430, 14335.24), (20070531, 14655.51), (20070629, 14460.98), (20070731, 14190.08), (20070831, 14319.08), (20070928, 14770.59), (20071031, 14925.389999999999), (20071130, 14460.98), (20071231, 14494.120000000001),
                           (20080131, 13829.26), (20080229, 13637.18), (20080331, 13651.959999999999)]
        # 图表左的垂直线
        self.chart.annotations=[lambda c,cA,vA: Line(c.x,c.y-gridStickOut,c.x,c.y+c.height+gridStickOut,strokeColor=black,strokeWidth=0.5)]
        # 图表右的垂直线
        self.chart.annotations.append(lambda c,cA,vA: Line(c.x+c.width,c.y-gridStickOut,c.x+c.width,c.y+c.height+gridStickOut,strokeColor=black,strokeWidth=0.5))

        # 选一数据,显示图表上的位置和标签
        num = 28        # 索引
        pointX = self.chart.data[num][0]
        pointY = self.chart.data[num][1]
        # 索引为num的坐标
        self.chart.annotations.append(lambda c, cA, vA: Line(cA(pointX), vA(pointY), c.x, vA(pointY),strokeColor=red,strokeWidth=0.5))
        self.chart.annotations.append(lambda c, cA, vA: Line(cA(pointX), vA(pointY), cA(pointX), c.y,strokeColor=red,strokeWidth=0.5))
        # 从选定的坐标点花两条直线落在坐标轴上

        import datetime
        pointXdate = datetime.datetime.strptime('{}'.format(pointX), '%Y%m%d').strftime('%d/%m/%y')
        # 将x坐标转成指定的日期格式dd/mm/yy
        self._add(self,DynamicLabel('X坐标: {}\nY坐标: {}'.format(pointXdate, pointY), pointX,pointY),name='label',validate=None,desc=None)
        # 添加一个动态标签,标签位置跟选中的数据点坐标有关
        self.label.fontName   = 'apple'
        self.label.fontSize   = 7
        self.label.fillColor  = red
        self.label.boxFillColor   = None
        # 标签字体、字体大小、颜色、无背景填充色
        self.label.textAnchor = 'start'     # 左对齐
        self.label.boxAnchor  ='sw'         # 锚点
        self.chart.annotations.append(self.label.asAnnotation)
        # self.label.asAnnotation的作用是设置标签的锚点坐标为数据点的坐标
        self.label.dx         = -20
        self.label.dy         = 5
        # x轴y轴方向对位置进行微调

if __name__=="__main__": 
    AreaChart_WithDynamicLabel().save(formats=['pdf'],outDir='.',fnRoot=None)