Ejemplo n.º 1
0
def drawing_chinese():
    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
    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()
    #����Ҫ��ʾ���ģ���Ҫ��ע��һ����������
    title.fontName = "msyh"
    title.fontSize = 12
    title_text = u'你好吗'
    #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:
        import traceback
        traceback.print_exc()
Ejemplo n.º 2
0
def draw_recent_week_pdf(filename, data_list):
    """
    画最近七天的流量计报表
    :param filename:
    :param data_list
    :return:
    """
    data = []
    max_val = 0
    for index in range(0, len(data_list)):
        data.append((index + 1, data_list[index]))
        max_val = max(max_val, data_list[index])

    drawing = Drawing(500, 800)
    lp = LinePlot()
    lp.x = 50
    lp.y = 80
    lp.height = 600
    lp.width = 400
    lp.data = [data]
    lp.joinedLines = 1
    lp.lines.symbol = makeMarker('FilledCircle')
    lp.xValueAxis.valueMin = 1
    lp.xValueAxis.valueMax = 7
    lp.xValueAxis.valueStep = 1
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = (int(max_val / 100) + 1) * 100
    lp.yValueAxis.valueStep = 100
    drawing.add(lp)

    x_title = Label()
    # 若需要显示中文,需要先注册一个中文字体
    pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc"))
    x_title.fontName = "haha"
    x_title.fontSize = 12
    title_text = '用气量'
    x_title._text = title_text
    x_title.x = 20
    x_title.y = 100
    x_title.textAnchor = 'middle'
    drawing.add(x_title)

    y_title = Label()
    # 若需要显示中文,需要先注册一个中文字体
    pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc"))
    y_title.fontName = "haha"
    y_title.fontSize = 12
    title_text = '最近七天'
    y_title._text = title_text
    y_title.x = 80
    y_title.y = 50
    y_title.textAnchor = 'middle'
    drawing.add(y_title)
    drawing.save(formats=['pdf'],
                 outDir=TMP_FILE_DIRECTORY_PATH,
                 fnRoot=filename)
Ejemplo n.º 3
0
    def colorTest(self):
        from reportlab.graphics.shapes import Rect
        from reportlab.graphics.charts.textlabels import Label
        self.colorRangeStatic(130)

        dim=25
        width = self.PAGE_WIDTH-150
        inrow = 8 #int(width/dim)
        height = int(len(self.colors)/inrow)
        if len(self.colors)%inrow > 0:
            height +=1
        height *= dim
        drawing = Drawing(width, height)
        for i,col in enumerate(self.colors):
            x = (i%inrow)*dim
            y = int(i/inrow)*dim
            rec = Rect(x=x,y=y,width=dim,height=dim)
            rec.fillColor = col
            drawing.add(rec)
            lab = Label()
            lab.x=x+dim/2
            lab.y=y+dim/2
            lab.setText('%d'%i)
            drawing.add(lab)
        return drawing
Ejemplo n.º 4
0
 def _drawLabels(self, label, labelCenter, y, width):
     """
     Draw the label given in a given area originating at (x,y) with width 'width'
     """
     fontName = 'Times-Roman'
     fontSize = 10
     #Limit the length of the label to the boundaries of the chartAreaWidth
     
     strWidth = self._stringWidth(label, fontName, fontSize)
     #Calculate the area taken by one character
     oneCharWidth = self._stringWidth(label[0], fontName, fontSize)
     #If the given string needs more size, reduce the string to a length which fits
     #in the given area
     if strWidth > width:
         maxPossibleLen = int(width/oneCharWidth)
         label = label[:maxPossibleLen]
         strWidth = self._stringWidth(label, fontName, fontSize)
         
     x = (labelCenter - ((strWidth)/2))
     Label_Graph = Label()
     Label_Graph.fontName = fontName
     Label_Graph.fontSize = fontSize
     #Label_Graph.angle = 0
     Label_Graph.boxAnchor = 'n'
     Label_Graph.x = x
     Label_Graph.y = y
     Label_Graph.setText(label)
     self.drawing.add(Label_Graph)
Ejemplo n.º 5
0
    def draw(self):
        ascent = getFont(self.xValueAxis.labels.fontName).face.ascent
        if ascent == 0:
            ascent = 0.718  # default (from helvetica)
        ascent = ascent * self.xValueAxis.labels.fontSize  # normalize

        # basic LinePlot - does the Axes, Ticks etc
        lp = LinePlot.draw(self)

        xLabel = self.xLabel
        if xLabel:  # Overall label for the X-axis
            xl = Label()
            xl.x = (self.x + self.width) / 2.0
            xl.y = 0
            xl.fontName = self.xValueAxis.labels.fontName
            xl.fontSize = self.xValueAxis.labels.fontSize
            xl.setText(xLabel)
            lp.add(xl)

        yLabel = self.yLabel
        if yLabel:  # Overall label for the Y-axis
            yl = Label()
            yl.angle = 90
            yl.x = 0
            yl.y = self.y + self.height / 2.0
            yl.fontName = self.yValueAxis.labels.fontName
            yl.fontSize = self.yValueAxis.labels.fontSize
            yl.setText(yLabel)
            lp.add(yl)

        # do a bounding box - in the same style as the axes
        if self.outerBorderOn:
            lp.add(
                Rect(
                    self.x,
                    self.y,
                    self.width,
                    self.height,
                    strokeColor=self.outerBorderColor,
                    strokeWidth=self.yValueAxis.strokeWidth,
                    fillColor=None,
                )
            )

        lp.shift(self.leftPadding, self.bottomPadding)

        return lp
Ejemplo n.º 6
0
def comparison_graphs(comparison_values, location, emission, default_emissions,
                      default_location):
    s = Spacer(9 * inch, .2 * inch)
    Elements.append(s)
    drawing = Drawing(0, 0)

    if not default_location:
        bc = gen_bar_graphs(comparison_values, location, emission)
        bc.y = -120
        bc.height = 125
        bc.width = 300
        drawing.add(bc)
    else:
        bc1 = gen_bar_graphs(default_emissions[:3], location, emission)
        bc2 = gen_bar_graphs(default_emissions[3:6], location, emission)
        bc3 = gen_bar_graphs(default_emissions[6:], location, emission)

        offset = -257
        bc1.x = -10 + offset
        bc2.x = 190 + offset
        bc3.x = 390 + offset
        drawing.add(bc1)
        drawing.add(bc2)
        drawing.add(bc3)

        label_offset = offset + 80
        label1, label2, label3 = Label(), Label(), Label()
        label1.setText("Global (excluding Europe and US)")
        label1.x, label1.y = -17 + label_offset, -160
        label1.fontName = "Times-Bold"

        label2.setText("Europe")
        label2.x, label2.y = 185 + label_offset, -160
        label2.fontName = "Times-Bold"

        label3.setText("United States")
        label3.x, label3.y = 385 + label_offset, -160
        label3.fontName = "Times-Bold"

        drawing.add(label1)
        drawing.add(label2)
        drawing.add(label3)

    if_elsewhere_para = Paragraph(
        '<font face="times" size=12>Kilograms of CO<sub rise = -10 size' +
        ' = 8>2 </sub> emissions for the function if the computation had been performed elsewhere</font>',
        style=styles["Normal"])
    graph_data = [['Emission Comparison'], [if_elsewhere_para], [drawing]]
    graph_table = Table(graph_data, [6.5 * inch],
                        [.25 * inch, .25 * inch, .25 * inch],
                        hAlign="CENTER")
    graph_table.setStyle(
        TableStyle([('FONT', (0, 0), (0, 0), "Times-Bold"),
                    ('FONT', (0, 1), (0, 1), "Times-Roman"),
                    ('FONTSIZE', (0, 0), (0, 0), 13),
                    ('FONTSIZE', (0, 1), (0, 1), 12),
                    ('ALIGN', (0, 0), (-1, -1), "CENTER")]))

    Elements.append(graph_table)
Ejemplo n.º 7
0
 def header_draw(self, x, y, text):
     chart_title = Label()
     chart_title.x = x
     chart_title.y = y
     chart_title.fontName = 'RobotoBold'
     chart_title.fontSize = 9
     chart_title.textAnchor = 'middle'
     chart_title.setText(text)
     return chart_title
Ejemplo n.º 8
0
 def title_draw(self, x, y, text):
     chart_title = Label()
     chart_title.x = x
     chart_title.y = y
     chart_title.fontName = 'FreeSansBold'
     chart_title.fontSize = 16
     chart_title.textAnchor = 'middle'
     chart_title.setText(text)
     return chart_title
Ejemplo n.º 9
0
 def title_draw(self, x, y, text):
     chart_title = Label()
     chart_title.x = x
     chart_title.y = y
     chart_title.fontName = 'FreeSansBold'
     chart_title.fontSize = 16
     chart_title.textAnchor = 'middle'
     chart_title.setText(text)
     return chart_title
Ejemplo n.º 10
0
    def draw(self):
        ascent = getFont(self.xValueAxis.labels.fontName).face.ascent
        if ascent == 0:
            ascent = 0.718  # default (from helvetica)
        ascent = ascent * self.xValueAxis.labels.fontSize  # normalize

        #basic LinePlot - does the Axes, Ticks etc
        lp = LinePlot.draw(self)

        xLabel = self.xLabel
        if xLabel:  #Overall label for the X-axis
            xl = Label()
            xl.x = (self.x + self.width) / 2.0
            xl.y = 0
            xl.fontName = self.xValueAxis.labels.fontName
            xl.fontSize = self.xValueAxis.labels.fontSize
            xl.setText(xLabel)
            lp.add(xl)

        yLabel = self.yLabel
        if yLabel:  #Overall label for the Y-axis
            yl = Label()
            yl.angle = 90
            yl.x = 0
            yl.y = (self.y + self.height / 2.0)
            yl.fontName = self.yValueAxis.labels.fontName
            yl.fontSize = self.yValueAxis.labels.fontSize
            yl.setText(yLabel)
            lp.add(yl)

        # do a bounding box - in the same style as the axes
        if self.outerBorderOn:
            lp.add(
                Rect(self.x,
                     self.y,
                     self.width,
                     self.height,
                     strokeColor=self.outerBorderColor,
                     strokeWidth=self.yValueAxis.strokeWidth,
                     fillColor=None))

        lp.shift(self.leftPadding, self.bottomPadding)

        return lp
Ejemplo n.º 11
0
    def cn_process(self, text, x, y, pathnow) :
        pdfmetrics.registerFont(ttfonts.TTFont("font1",'simsun.ttc'))
        title = Label()
        title.fontName = "font1"
        title.fontSize = 14
        title_text = text
        title._text = title_text
        title.x = x
        title.y = y

        return (title)
Ejemplo n.º 12
0
 def setDescription(self):
     desc = Label()        
     desc.fontName = 'Helvetica'
     desc.fontSize = 12
     desc.x = 230
     desc.y = 10
     desc._text = self._data_dict.get('description', '')
     desc.maxWidth = 280
     desc.height = 20
     desc.textAnchor ='middle'
     self.add(desc, name='Description')
Ejemplo n.º 13
0
 def setTitle(self):
     title = Label()        
     title.fontName = 'Helvetica-Bold'
     title.fontSize = 12
     title.x = 300
     title.y = 335
     title._text = self._data_dict.get('title', '')
     title.maxWidth = 180
     title.height = 20
     title.textAnchor ='middle'
     self.add(title, name='Title')
Ejemplo n.º 14
0
    def addLabels(self,drawing,title=None,xlabel=None,ylabel=None):
        from reportlab.graphics.charts.textlabels import Label
        if not title is None:
            Title = Label()
            Title.fontName = 'Helvetica-Bold'
            Title.fontSize = 7
            Title.x = drawing.width/2
            Title.y = drawing.height-25
            Title._text = title
            Title.maxWidth = 180
            Title.height = 20
            Title.textAnchor ='middle'
            drawing.add(Title)

        if not xlabel is None:
            XLabel = Label()
            XLabel.fontName = 'Helvetica'
            XLabel.fontSize = 7
            XLabel.x = drawing.width/2
            XLabel.y = 10
            XLabel.textAnchor ='middle'
            XLabel.maxWidth = 100
            XLabel.height = 20
            XLabel._text = xlabel
            drawing.add(XLabel)

        if not ylabel is None:
            YLabel = Label()
            YLabel.fontName = 'Helvetica'
            YLabel.fontSize = 7
            YLabel.x = 12
            YLabel.y = drawing.height/2
            YLabel.angle = 90
            YLabel.textAnchor ='middle'
            YLabel.maxWidth = 100
            YLabel.height = 20
            YLabel._text = ylabel
            drawing.add(YLabel)
Ejemplo n.º 15
0
    def setAxesLabels(self):
        xlabel = Label()
        xlabel.fontName = 'Helvetica'
        xlabel.fontSize = 12
        xlabel.x = 450
        xlabel.y = 40
        xlabel._text = self._data_dict.get('xlabel', '')
        xlabel.maxWidth = 180
        xlabel.height = 20
        xlabel.textAnchor ='middle'
        self.add(xlabel, name='xlabel')

        ylabel = Label()
        ylabel.fontName = 'Helvetica'
        ylabel.fontSize = 12
        ylabel.x = 20
        ylabel.y = 210
        ylabel.angle = 90
        ylabel._text = self._data_dict.get('ylabel', '')
        ylabel.maxWidth = 180
        ylabel.height = 20
        ylabel.textAnchor ='middle'
        self.add(ylabel, name='ylabel')
Ejemplo n.º 16
0
def autoLegender( chart,title=''):
    width = 448
    height = 230
    d = Drawing(width,height)
    lab = Label()
    lab.x = 220  #x和y是文字的位置坐标
    lab.y = 210
    lab.setText(title)
    # lab.fontName = 'song' #增加对中文字体的支持
    lab.fontSize = 20
    d.add(lab)
    d.background = Rect(0,0,width,height,strokeWidth=1,strokeColor="#868686",fillColor=None) #边框颜色
    d.add(chart)

    return d
Ejemplo n.º 17
0
def autoLegender(chart,
                 title='',
                 width=448,
                 height=230,
                 order='off',
                 categories=[],
                 use_colors=[]):
    d = Drawing(width, height)
    d.add(chart)
    lab = Label()
    lab.x = width / 2  #x和y是title文字的位置坐标
    lab.y = 21 / 23 * height
    lab.fontName = 'song'  #增加对中文字体的支持
    lab.fontSize = 20
    lab.setText(title)
    d.add(lab)
    #颜色图例说明等
    if categories != [] and use_colors != []:
        leg = Legend()
        leg.x = 500  # 说明的x轴坐标
        leg.y = 0  # 说明的y轴坐标
        leg.boxAnchor = 'se'
        # leg.strokeWidth = 4
        leg.strokeColor = None
        leg.subCols[1].align = 'right'
        leg.columnMaximum = 10  # 图例说明一列最多显示的个数
        leg.fontName = 'song'
        leg.alignment = 'right'
        leg.colorNamePairs = list(zip(use_colors, tuple(categories)))
        d.add(leg)
    if order == 'on':
        d.background = Rect(0,
                            0,
                            width,
                            height,
                            strokeWidth=1,
                            strokeColor="#868686",
                            fillColor=None)  #边框颜色
    return d
Ejemplo n.º 18
0
    def draw_line(self, line_data, *args, **kw):
        drawing = Drawing(400, 200)
        lp = LinePlot()
        lp.x = 30
        lp.y = -20
        lp.height = 200
        lp.width = 400
        lp.data = line_data
        lp.xValueAxis.labels.fontName = 'Helvetica'
        lp.xValueAxis.labels.fontSize = 7
        lp.xValueAxis.forceZero = 0
        lp.xValueAxis.avoidBoundFrac = 1
        lp.xValueAxis.gridEnd = 115
        lp.xValueAxis.tickDown = 3
        lp.xValueAxis.labelTextFormat = lambda x: time.strftime(
            '%Y-%m-%d %H:%M:%S', time.localtime(int(x) / 1000))

        lp.yValueAxis.tickLeft = 3
        lp.yValueAxis.labels.fontName = 'Helvetica'
        lp.yValueAxis.labels.fontSize = 7
        for i in range(len(line_data)):
            lp.lines[i].strokeColor = colors.toColor('hsl(%s,80%%,40%%)' %
                                                     (i * 60))
        drawing.add(lp)

        title = Label()
        title.fontName = 'Helvetica-Bold'
        title.fontSize = 14
        title.x = 200
        title.y = 180
        title._text = 'Chart Title'
        title.maxWidth = 180
        title.height = 20
        title.textAnchor = 'middle'
        drawing.add(title)

        return drawing
Ejemplo n.º 19
0
        legend.colorNamePairs = [(self.Color[i], names[i])
                                 for i in range(len(names))]
        legend.fontName = 'Helvetica'
        legend.fontSize = 8
        legend.dxTextSpace = 5
        legend.dy = 5
        legend.dx = 5
        legend.deltay = 5
        legend.alignment = 'right'

        drawing.add(lp)
        drawing.add(legend)

        if title != None:
            label = Label()
            label.x = w
            label.y = h - 25
            label.boxAnchor = 'se'
            label.fontName = 'Helvetica'
            label.fontSize = 10
            label.setText(title)
            drawing.add(label)
        return drawing

    def drawTable(self, data):
        t = Table(data, None, None, None, 1, 1, 1)
        extraStyle = []
        for i in range(len(data[1:])):
            if data[1:][i][0] == 'Free' or data[1:][i][0] == 'Used':
                extraStyle.append(
                    ('BACKGROUND', (0, i + 1), (-1, i + 1), colors.orange))
Ejemplo n.º 20
0
def bar_chart(data, labels, **kw):
    """
    :param data:    contains a two dimentional array of values, e.g. [[d11, d21, x1], [d12, d22, x2]]
    :type data:     list[list[numbers],...]
    :param labels:  can contain, but must not ["xlabel", "ylabel", ["data label0", ...]]
                    third item can also be an interger stating the iteration start as label
    :type lables:   ???
    :param ylim:    limit the y axis to these values, e.g. (0, 100)
    :type ylim:     ???
    :param bars:    list of colors we should use for the bars, refer to PDF_CHART_COLORS as an example
    :type bars:     ???
    :param size:    size in pixels, e.g. (8 * cm, 4 * cm) or pixels, e.g. (400, 200)
    :type size:     ???
    :param title:   title of bar chart
    :type title:    string
    :param stacked: weather to do a stacked bar plot or std column plot
    :type stacked:  ???
    """
    title = kw.pop('title', None)
    stacked = kw.pop('stacked', False)
    bars = kw.pop('bars', PDF_CHART_COLORS)
    size = kw.pop('plotSize', (18 * cm, 9 * cm))
    ylim = kw.pop('ylim', None)

    # Create the drawing
    drawing = Drawing(size[0], size[1])

    # Create the Chart
    chart = VerticalBarChart()

    for key, val in list(kw.items()):
        setattr(chart, key, val)

    if title is not None:
        drawing.add(String(20, size[1] - 20, title), name='title')
        chart.y -= 10

    chart.width = drawing.width - 20
    chart.height = drawing.height - 40

    chart.data = data
    max_y = 0
    min_y = maxsize
    for i in range(len(data)):
        chart.bars[i].fillColor = HexColor(bars[i % len(bars)])
        max_y = max(data[i] + [max_y])
        min_y = min(data[i] + [min_y])
    chart.valueAxis.valueMax = max_y * 1.1
    chart.valueAxis.valueMin = min_y * 0.9

    if ylim is not None:
        chart.valueAxis.valueMin = ylim[0]
        chart.valueAxis.valueMax = ylim[1]

    if len(data) > 1:
        chart.barSpacing = 2

    if labels is not None:
        if len(labels) > 0:
            xlabel = Label()
            xlabel._text = labels[0]  # pylint: disable=W0212
            xlabel.textAnchor = 'middle'
            xlabel.x = drawing.width / 2
            xlabel.y = 0
            chart.y += 15
            drawing.add(xlabel, name="xlabel")

        if len(labels) > 1:
            ylabel = Label()
            ylabel._text = labels[1]  # pylint: disable=W0212
            xlabel.textAnchor = 'middle'
            ylabel.angle = 90
            ylabel.x = 0
            ylabel.y = drawing.height / 2
            chart.x += 10
            drawing.add(ylabel, name="ylabel")

        if len(labels) > 2:
            if len(labels[2]) == max([len(x) for x in data]):
                chart.categoryAxis.categoryNames = labels[2]
                chart.categoryAxis.labels.angle = 30
            elif type(labels[2]) == int:
                chart.categoryAxis.categoryNames = range(labels[2], max([len(x) for x in data]) + labels[2])

    if stacked:
        chart.categoryAxis.style = 'stacked'

    drawing.add(chart, name='chart')

    return drawing
Ejemplo n.º 21
0
def line_chart(data, labels, **kw):
    """
    :param data:    contains a three dimensional array of values (list of lists of points)
                    or just a list of datapoint lists (it will be auto-transposed to start at 0)
    :type data:     list
    :param labels:  can contain, but must not ["xlabel", "ylabel", ["data label0", ...]]
                    third item can also be an interger stating the iteration start as label
                    when of same size as data, then a legend is added instead
    :type lables:   ???
    :param xlim:    limit the x axis to these values, e.g. (0, 100)
    :type xlim:     Tuple(Number, Number)
    :param ylim:    limit the y axis to these values, e.g. (0, 50)
    :type ylim:     Tuple(Number, Number)
    :param size:    size in pixels, e.g. (18*cm, 9*cm)
    :type size:     Tuple(Number, Number)
    :param title:   title of bar chart
    :type title:    string
    :param lines:   list of colors we should use to paint lines
    :type lines:    list[???]
    :param markers: list of markers we should use to draw markers
    :type markers:  list[`PDF_LINE_MARKERS`,...]
    :param scatter: weather to do a scatter plot or line chart
    :type scatter:  boolean
    """
    # Get all arguments from the keywordargs
    title = kw.pop('title', None)
    scatter = kw.pop('scatter', False)
    size = kw.pop('plotSize', (18 * cm, 9 * cm))
    lines = kw.pop('lines', PDF_CHART_COLORS)
    markers = kw.pop('markers', PDF_LINE_MARKERS)
    xlim = kw.pop('xlim', None)
    ylim = kw.pop('ylim', None)

    drawing = Drawing(size[0], size[1])

    chart = None

    if(scatter):
        chart = ScatterPlot()
    else:
        chart = LinePlot()

    for key, val in list(kw.items()):
        setattr(chart, key, val)

    if title is not None:
        drawing.add(String(20, size[1] - 10, title), name='title')
        chart.y -= 10

    chart.width = drawing.width - 20
    chart.height = drawing.height - 40
    chart.x = 10
    chart.y = 10

    chart.data = data if type(data[0][0]) in (tuple, list) else [list(zip(list(range(len(i))), i)) for i in data]

    max_y = 0
    min_y = maxsize
    for i in range(len(data)):
        chart.lines[i].strokeColor = HexColor(lines[i % len(lines)])
        if markers is not None:
            chart.lines[i].symbol = makeMarker(markers[i % len(markers)])
            chart.lines[i].symbol.size = 3
        max_y = max([k[1] for k in chart.data[i]] + [max_y])
        min_y = min([k[1] for k in chart.data[i]] + [min_y])
    chart.yValueAxis.valueMax = max_y * 1.1
    chart.yValueAxis.valueMin = min_y * 0.9

    chart.xValueAxis.visibleGrid = True
    chart.yValueAxis.visibleGrid = True

    if xlim is not None:
        chart.xValueAxis.valueMin = xlim[0]
        chart.xValueAxis.valueMax = xlim[1]
    if ylim is not None:
        chart.yValueAxis.valueMin = ylim[0]
        chart.yValueAxis.valueMax = ylim[1]

    if scatter:
        chart.xLabel = ''
        chart.yLabel = ''
        chart.y -= 10
        chart.lineLabelFormat = None

    if labels is not None:
        if len(labels) > 0:
            xlabel = Label()
            xlabel._text = labels[0]  # pylint: disable=W0212
            xlabel.textAnchor = 'middle'
            xlabel.x = drawing.width / 2
            xlabel.y = 5
            chart.y += 15
            drawing.add(xlabel, name="xlabel")

        if len(labels) > 1:
            ylabel = Label()
            ylabel._text = labels[1]  # pylint: disable=W0212
            xlabel.textAnchor = 'middle'
            ylabel.angle = 90
            ylabel.x = 0
            ylabel.y = drawing.height / 2
            chart.x += 12
            drawing.add(ylabel, name="ylabel")

        if len(labels) > 2:
            # when labels are of same size as max nr of data point, use as x axis labels
            if len(labels[2]) == max([len(x) for x in data]):
                chart.categoryAxis.categoryNames = labels[2]  # pylint: disable=E1101
                chart.xValueAxis.labels.angle = 30  # pylint: disable=E1101
            # otherwise when integer use the counter
            elif type(labels[2]) == int:
                temp = range(labels[2], max([len(x) for x in data]) + labels[2])
                chart.categoryAxis.categoryNames = temp  # pylint: disable=E1101
            # or we could add a legend when of same size as data
            elif len(labels[2]) == len(data):
                legend = Legend()
                chart.height -= 8
                chart.y += 8
                xlabel.y += 8
                legend.boxAnchor = 'sw'
                legend.x = chart.x + 8
                legend.y = -2
                legend.columnMaximum = 1
                legend.deltax = 50
                legend.deltay = 0
                legend.dx = 10
                legend.dy = 1.5
                legend.fontSize = 7
                legend.alignment = 'right'
                legend.dxTextSpace = 5
                legend.colorNamePairs = [(HexColor(lines[i]), labels[2][i]) for i in range(len(chart.data))]
                legend.strokeWidth = 0
                drawing.add(legend, name='legend')

    drawing.add(chart, name='chart')

    return drawing
Ejemplo n.º 22
0
    def draw(self):
        g = Group()

        #box
        g.add(
            Rect(self.x,
                 self.y,
                 len(self.xlabels) * self.gridDivWidth,
                 len(self.ylabels) * self.gridDivWidth,
                 strokeColor=self.gridColor,
                 strokeWidth=self.strokeWidth,
                 fillColor=None))

        #internal gridding
        for f in range(1, len(self.ylabels)):
            #horizontal
            g.add(
                Line(strokeColor=self.gridColor,
                     strokeWidth=self.strokeWidth,
                     x1=self.x,
                     y1=self.y + f * self.gridDivWidth,
                     x2=self.x + len(self.xlabels) * self.gridDivWidth,
                     y2=self.y + f * self.gridDivWidth))
        for f in range(1, len(self.xlabels)):
            #vertical
            g.add(
                Line(strokeColor=self.gridColor,
                     strokeWidth=self.strokeWidth,
                     x1=self.x + f * self.gridDivWidth,
                     y1=self.y,
                     x2=self.x + f * self.gridDivWidth,
                     y2=self.y + len(self.ylabels) * self.gridDivWidth))

        # draw the 'dot'
        g.add(
            Circle(strokeColor=self.gridColor,
                   strokeWidth=self.strokeWidth,
                   fillColor=self.dotColor,
                   cx=self.x + (self.dotXPosition * self.gridDivWidth),
                   cy=self.y + (self.dotYPosition * self.gridDivWidth),
                   r=self.dotDiameter / 2.0))

        #used for centering y-labels (below)
        ascent = getFont(self.labelFontName).face.ascent
        if ascent == 0:
            ascent = 0.718  # default (from helvetica)
        ascent = ascent * self.labelFontSize  # normalize

        #do y-labels
        if self.ylabels != None:
            for f in range(len(self.ylabels) - 1, -1, -1):
                if self.ylabels[f] != None:
                    g.add(
                        String(strokeColor=self.gridColor,
                               text=self.ylabels[f],
                               fontName=self.labelFontName,
                               fontSize=self.labelFontSize,
                               fillColor=_PCMYK_black,
                               x=self.x - self.labelOffset,
                               y=self.y + (f * self.gridDivWidth +
                                           (self.gridDivWidth - ascent) / 2.0),
                               textAnchor='end'))

        #do x-labels
        if self.xlabels != None:
            for f in range(0, len(self.xlabels)):
                if self.xlabels[f] != None:
                    l = Label()
                    l.x = self.x + (f * self.gridDivWidth
                                    ) + (self.gridDivWidth + ascent) / 2.0
                    l.y = self.y + (len(self.ylabels) *
                                    self.gridDivWidth) + self.labelOffset
                    l.angle = 90
                    l.textAnchor = 'start'
                    l.fontName = self.labelFontName
                    l.fontSize = self.labelFontSize
                    l.fillColor = _PCMYK_black
                    l.setText(self.xlabels[f])
                    l.boxAnchor = 'sw'
                    l.draw()
                    g.add(l)

        return g
Ejemplo n.º 23
0
        legend.boxAnchor = 'sw'
        legend.colorNamePairs = [(self.Color[i], names[i]) for i in range(len(names))]
        legend.fontName = 'Helvetica'
        legend.fontSize = 8
        legend.dxTextSpace = 5
        legend.dy = 5
        legend.dx = 5
        legend.deltay = 5
        legend.alignment ='right'

        drawing.add(lp)
        drawing.add(legend)

        if title != None:
            label = Label()
            label.x = w
            label.y = h - 25
            label.boxAnchor = 'se'
            label.fontName = 'Helvetica'
            label.fontSize = 10
            label.setText(title)
            drawing.add(label)
        return drawing

    def drawTable(self, data):
        t = Table(data, None, None, None, 1, 1, 1)
        extraStyle = []
        for i in range(len(data[1:])):
            if data[1:][i][0] == 'Free' or data[1:][i][0] == 'Used':
                extraStyle.append(('BACKGROUND', (0, i + 1), (-1, i + 1), colors.orange))
            if data[1:][i][0] == 'SwapUsage' or data[1:][i][0] == 'LMK File':
Ejemplo n.º 24
0
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 = '你好'
#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
Ejemplo n.º 25
0
    def draw(self):
        g = Group()

        #box
        g.add(Rect(self.x,self.y,len(self.xlabels)*self.gridDivWidth,len(self.ylabels)*self.gridDivWidth,
                   strokeColor=self.gridColor,
                   strokeWidth=self.strokeWidth,
                   fillColor=None))

        #internal gridding
        for f in range (1,len(self.ylabels)):
            #horizontal
            g.add(Line(strokeColor=self.gridColor,
                       strokeWidth=self.strokeWidth,
                       x1 = self.x,
                       y1 = self.y+f*self.gridDivWidth,
                       x2 = self.x+len(self.xlabels)*self.gridDivWidth,
                       y2 = self.y+f*self.gridDivWidth))
        for f in range (1,len(self.xlabels)):
            #vertical
            g.add(Line(strokeColor=self.gridColor,
                       strokeWidth=self.strokeWidth,
                       x1 = self.x+f*self.gridDivWidth,
                       y1 = self.y,
                       x2 = self.x+f*self.gridDivWidth,
                       y2 = self.y+len(self.ylabels)*self.gridDivWidth))

        # draw the 'dot'
        g.add(Circle(strokeColor=self.gridColor,
                     strokeWidth=self.strokeWidth,
                     fillColor=self.dotColor,
                     cx = self.x+(self.dotXPosition*self.gridDivWidth),
                     cy = self.y+(self.dotYPosition*self.gridDivWidth),
                     r = self.dotDiameter/2.0))

        #used for centering y-labels (below)
        ascent=getFont(self.labelFontName).face.ascent
        if ascent==0:
            ascent=0.718 # default (from helvetica)
        ascent=ascent*self.labelFontSize # normalize

        #do y-labels
        if self.ylabels != None:
            for f in range (len(self.ylabels)-1,-1,-1):
                if self.ylabels[f]!= None:
                    g.add(String(strokeColor=self.gridColor,
                             text = self.ylabels[f],
                             fontName = self.labelFontName,
                             fontSize = self.labelFontSize,
                             fillColor=_PCMYK_black,
                             x = self.x-self.labelOffset,
                             y = self.y+(f*self.gridDivWidth+(self.gridDivWidth-ascent)/2.0),
                             textAnchor = 'end'))

        #do x-labels
        if self.xlabels != None:
            for f in range (0,len(self.xlabels)):
                if self.xlabels[f]!= None:
                    l=Label()
                    l.x=self.x+(f*self.gridDivWidth)+(self.gridDivWidth+ascent)/2.0
                    l.y=self.y+(len(self.ylabels)*self.gridDivWidth)+self.labelOffset
                    l.angle=90
                    l.textAnchor='start'
                    l.fontName = self.labelFontName
                    l.fontSize = self.labelFontSize
                    l.fillColor = _PCMYK_black
                    l.setText(self.xlabels[f])
                    l.boxAnchor = 'sw'
                    l.draw()
                    g.add(l)

        return g