Exemplo 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()
Exemplo 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)
Exemplo n.º 3
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)
Exemplo n.º 4
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')
Exemplo n.º 5
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')
Exemplo n.º 6
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)
Exemplo n.º 7
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')
Exemplo n.º 8
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
Exemplo n.º 9
0
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 = '你好'
#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"
Exemplo n.º 10
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
Exemplo n.º 11
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