def subtest(sa, d):
     pc = Pie()
     pc.direction = d
     pc.startAngle = sa
     arcs = _makeSideArcDefs(sa, d)
     A = [x[1] for x in pc.makeAngles()]
     arcsum = sum([a[2] - a[1] for a in arcs])
     isum = intSum(arcs, A)
     mi = max([a[2] - a[1] for a in arcs])
     ni = min([a[2] - a[1] for a in arcs])
     l = []
     s = arcsum - 360
     if s > 1e-8:
         l.append("Arc length=%s != 360" % s)
     s = abs(isum - 360)
     if s > 1e-8:
         l.append("interval intersection length=%s != 360" % s)
     if mi > 360:
         l.append("max interval intersection length=%s >360" % mi)
     if ni < 0:
         l.append("min interval intersection length=%s <0" % ni)
     if l:
         l.append("sa: %s d: %s" % (sa, d))
         l.append("sidearcs: %s" % str(arcs))
         l.append("Angles: %s" % A)
         raise ValueError("piecharts._makeSideArcDefs failure\n%s" % "\n".join(l))
Exemplo n.º 2
0
def sample4pie():
    width = 300
    height = 150
    d = Drawing(width, height)
    pc = Pie()
    pc.x = 150
    pc.y = 50
    pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50]
    pc.labels = ['0','a','b','c','d','e','f','g','h','i']
    pc.slices.strokeWidth=0.5
    pc.slices[3].popout = 20
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2,2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    d.add(pc)
    legend = Legend()
    legend.x = width-5
    legend.y = height-5
    legend.dx = 20
    legend.dy = 5
    legend.deltax = 0
    legend.boxAnchor = 'nw'
    legend.colorNamePairs=Auto(chart=pc)
    d.add(legend)
    return d
def sample4pie():
    width = 300
    height = 150
    d = Drawing(width, height)
    pc = Pie()
    pc.x = 150
    pc.y = 50
    pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50]
    pc.labels = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i"]
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 20
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    d.add(pc)
    legend = Legend()
    legend.x = width - 5
    legend.y = height - 5
    legend.dx = 20
    legend.dy = 5
    legend.deltax = 0
    legend.boxAnchor = "nw"
    legend.colorNamePairs = Auto(chart=pc)
    d.add(legend)
    return d
Exemplo n.º 4
0
    def test0(self, isFast=0):
        """Hello World, on a rectangular background.

        The rectangle's fillColor is yellow.
        The string's fillColor is red.
        """
        reportlab.rl_config.shapeChecking = not isFast

        pdfPath = outputfile('test_graphics_speed_fast.pdf')
        c = Canvas(pdfPath)
        t0 = time.time()

        d = Drawing(400, 200)
        num = 100
        for i in range(num):
            pc = Pie()
            pc.x = 150
            pc.y = 50
            pc.data = [10,20,30,40,50,60]
            pc.labels = ['a','b','c','d','e','f']
            pc.slices.strokeWidth=0.5
            pc.slices[3].popout = 20
            pc.slices[3].strokeWidth = 2
            pc.slices[3].strokeDashArray = [2,2]
            pc.slices[3].labelRadius = 1.75
            pc.slices[3].fontColor = colors.red
            d.add(pc)
        d.drawOn(c, 80, 500)

        t1 = time.time()

        result = 'drew %d pie charts in %0.4f' % (num, t1 - t0)
        open(outputfile('test_graphics_speed_test%s.log' % (isFast+1)), 'w').write(result)
Exemplo n.º 5
0
def make_chart(stats):
    drawing = Drawing()
    pc = Pie()
    pc.x = 150
    pc.y = 50
    pc.data = stats
    pc.labels = ['Heavily Damaged: %s' % stats[0],'Serverly Damaged: %s' % stats[1]]
    drawing.add(pc, '')
    return drawing
Exemplo n.º 6
0
def gopie():
    doc = SimpleDocTemplate("products.pdf")
    Catalog = []
    style = styles["Normal"]
    p = Paragraph("Cranberry Sauce Sales", styles["Heading1"])
    Catalog.append(p)
    d = Drawing(100, 125)
    cht = Pie()
    cht.data = sales[0]
    cht.labels = months
    cht.slices[0].popout = 10
    d.add(cht)
    Catalog.append(d)
    doc.build(Catalog)
Exemplo n.º 7
0
    def __add_graph(self):
        drawing = Drawing(200, 100)
        data = list()
        labels = list()

        self.c.drawString(370, 730, 
            'Distribucion en pesos'.encode('utf-8'))

        for acc in self.accounts:
            balance = acc.balance
            if acc.currency == 'USD':
                balance = balance * self.dolar

            data.append(balance)
            labels.append(acc.name)

        pie = Pie()
        pie.x = 280
        pie.y = 630
        pie.height = 100
        pie.width = 100
        pie.data = data
        pie.labels = labels
        pie.simpleLabels = 1
        pie.slices.strokeWidth = 1
        pie.slices.strokeColor = black
        pie.slices.label_visible = 0

        legend = Legend()
        legend.x = 400
        legend.y = 680
        legend.dx              = 8
        legend.dy              = 8
        legend.fontName        = 'Helvetica'
        legend.fontSize        = 7
        legend.boxAnchor       = 'w'
        legend.columnMaximum   = 10
        legend.strokeWidth     = 1
        legend.strokeColor     = black
        legend.deltax          = 75
        legend.deltay          = 10
        legend.autoXPadding    = 5
        legend.yGap            = 0
        legend.dxTextSpace     = 5
        legend.alignment       = 'right'
        legend.dividerLines    = 1|2|4
        legend.dividerOffsY    = 4.5
        legend.subCols.rpad    = 30
        n = len(pie.data)
        self.__setItems(n,pie.slices,
            'fillColor',self.pdf_chart_colors)

        legend.colorNamePairs = [(pie.slices[i].fillColor, 
            (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)]


        drawing.add(pie)
        drawing.add(legend)
        x, y = 0, 0
        renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
Exemplo n.º 8
0
def sample4pie():
    d = Drawing(400, 200)
    pc = Pie()
    pc.x = 150
    pc.y = 50
    pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50]
    pc.labels = ['0','a','b','c','d','e','f','g','h','i']
    pc.slices.strokeWidth=0.5
    pc.slices[3].popout = 20
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2,2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    d.add(pc)
    return d
Exemplo n.º 9
0
    def test_24_PieCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.piecharts import Pie

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title']))
        elements.append(Spacer(1,1*inch))

        d = Drawing(400,200)
        data = [13,5,20,22,37,45]
        pc = Pie()
        pc.x = 65
        pc.y = 15
        pc.width = 150
        pc.height = 150
        pc.data = data
        pc.labels = ['a','b','c','d','e','f']
        d.add(pc)

        elements.append(d)

        doc.build(elements)
Exemplo n.º 10
0
def draw_time_repartition(mandate):
    drawing = Drawing(width=180*mm, height=120*mm)
    pdf_chart_colors = [HexColor("#fa9d00"), HexColor("#006884"), HexColor("#00909e"), HexColor("#ffd08d"), ]
    pie = Pie()
    pie.x = 60*mm
    pie.y = 35*mm
    pie.width = 60*mm
    pie.height = 60*mm
    pie.slices.strokeWidth = 0.5
    pie.slices.fontName = 'Helvetica'
    pie.slices.fontSize = 8
    pie.data = []
    pie.labels = []
    titles = []
    add_data_and_titles_to_pie(pie, titles, mandate.research_percent, 'research_percent')
    add_data_and_titles_to_pie(pie, titles, mandate.tutoring_percent, 'tutoring_percent')
    add_data_and_titles_to_pie(pie, titles, mandate.service_activities_percent, 'service_activities_percent')
    add_data_and_titles_to_pie(pie, titles, mandate.formation_activities_percent, 'formation_activities_percent')
    if len(pie.data) > 0:
        drawing.add(pie)
        add_legend_to_pie(drawing)
        n = len(pie.data)
        set_items(n, pie.slices, 'fillColor', pdf_chart_colors)
        drawing.legend.colorNamePairs = \
            [(pie.slices[i].fillColor, (titles[i], '%0.f' % pie.data[i] + '%')) for i in range(n)]
    return drawing
Exemplo n.º 11
0
    def __init__(self, width, height, labels, data):
        IRender.__init__(self, width, height, labels, data)

        #self.w = self.width
        #self.h = self.height
        #data = {}
        #for value in self.data:
        #    data[value[0]] = int(value[1])

        #plot = cairoplot.PiePlot('/tmp/tmp.png', data, self.w*2, self.h*2, gradient=True)
        ##plot.font_size *= 2
        #plot.render()
        #plot.commit()
        #with open('/tmp/tmp.png') as f:
        #    self.image = Image(StringIO(f.read()), self.w, self.h)
        pc = Pie()
        pc.width = min(self.height,self.width - 150)
        pc.height = min(self.height - 50,self.width)
        pc.width = pc.height = min(pc.height, pc.width)
        pc.x = self.width / 2 - pc.width / 2
        pc.y = self.height / 2 - pc.height / 2
        pc.data = [int(line[1]) for line in self.data]
        pc.labels = [line[0] for line in self.data]

        for i in xrange(len(self.data)):
            pc.slices[i].fillColor = COLORS[i % len(COLORS)]
            pc.slices[i].strokeColor = COLORS[i % len(COLORS)]
        self.drawing = Drawing(self.width, self.height)
        self.drawing.add(pc)
Exemplo n.º 12
0
 def __init__(self,width=400,height=200,*args,**kw):
     Drawing.__init__(self,width,height,*args,**kw)
     self._add(self,Pie(),name='pie',validate=None,desc=None)
     self.pie.sideLabels       = 1
     self.pie.labels           = ['A', 'C', 'B', 'E','D','F','S']
     self.pie.data             = arr
     self.pie.width            = 140
     self.pie.height           = 140
     self.pie.y                = 35
     self.pie.x                = 125
Exemplo n.º 13
0
def draw_pass_fail_piechart(passed_data: List[int]) -> Drawing:
    passed_data_labels = ['Passed', 'Failed', 'Not run']
    d = Drawing(width=200, height=200)
    pc = Pie()
    pc.x = 50
    pc.y = 50
    pc.width = 80
    pc.height = 80
    pc.slices[0].fillColor = COLOR_GREEN
    pc.slices[1].fillColor = COLOR_RED
    pc.slices[2].fillColor = COLOR_GRAY
    pc.direction = 'anticlockwise'
    pc.data = passed_data
    pc.labels = passed_data_labels
    pc.sideLabels = True
    pc.slices.fontName = MAIN_FONT_NAME
    pc.slices.fontSize = AXIS_FONT_SIZE
    d.add(pc)
    return d
Exemplo n.º 14
0
 def __init__(self, width=400, height=200, *args, **kw):
     Drawing.__init__(self, width, height, *args, **kw)
     self._add(self, Pie(), name='pie', validate=None, desc=None)
     self.pie.sideLabels = 1
     self.pie.labels = ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5']
     self.pie.data = [20, 10, 5, 5, 5]
     self.pie.width = 140
     self.pie.height = 140
     self.pie.y = 35
     self.pie.x = 125
Exemplo n.º 15
0
def draw_Pie(story, ProjectID):
    d = Drawing(140, 180)
    pie = Pie()
    pie.sideLabels = 1
    pie.labels= get_story_name_list(ProjectID)
    pie.data = get_story_count_list(ProjectID)
    pie.width = 140
    pie.height = 140
    pie.y = 0
    pie.x = 150
    d.add(pie)
    story.append(d)
def graphout(prod_catnames, data):
    drawing = Drawing(500, 200)
    pie = Pie()

    pie.sideLabels = 1
    pie.labels = prod_catnames
    pie.data = data[0]
    pie.width = 140
    pie.height = 140
    pie.y = 35
    pie.x = 125
    pie.slices.popout = 5

    drawing.add(pie)

    return drawing
    def create_pie_chart(self, data_list, label_list, user_color=None):
        # print data_list
        # print label_list

        label_list = map(lambda item: item.upper(), label_list)

        data = [(item / (sum(data_list) * 1.0)) * 100 for item in data_list]

        if user_color != None:
            usage_color = user_color
        else:
            random_range = [randint(0, 100) for i in range(len(data_list))]
            usage_color = map(
                lambda item: PCMYKColor(randint(0, item), randint(0, item),
                                        randint(0, item), randint(0, item)),
                random_range)
            print user_color

        # u_color = [colors.lawngreen, colors.red, colors.gray]
        # color = [colors.lawngreen, colors.red, colors.gray]
        # u_master = [randint(0, 100) for i in range(4)]
        # u_color = [PCMYKColor(randint(0, u_master[0]), randint(0, u_master[1]), randint(0, u_master[2]), randint(0, u_master[3])) for i in range(3)]
        # print u_color
        # color = u_color

        d = Drawing()
        pie = Pie()
        pie.x = 200
        pie.y = 85
        pie.data = data
        pie.labels = label_list

        for i, color in enumerate(usage_color):
            pie.slices[i].fillColor = color

        pie.slices.strokeWidth = 0.5
        pie.slices.popout = 1.5
        pie._seriesCount = 3
        pie.sideLabels = 1

        legend = Legend()
        legend.alignment = 'right'
        legend.x = 0
        legend.y = 75
        legend.colorNamePairs = [
            (z, (x, '     {val:.2f}%'.format(val=y)))
            for x, y, z in zip(pie.labels, data, usage_color)
        ]
        d.add(legend)
        d.add(pie)

        self.flowables.append(d)
Exemplo n.º 18
0
def generate(filename, title, additional_info, table_data, data, labels):
    styles = getSampleStyleSheet()
    report = SimpleDocTemplate(filename)
    report_title = Paragraph(title, styles["h1"])
    report_info = Paragraph(additional_info, styles["BodyText"])
    table_style = [('GRID', (0, 0), (-1, -1), 1, colors.black),
                   ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                   ('ALIGN', (0, 0), (-1, -1), 'CENTER')]
    report_table = Table(data=table_data, style=table_style, hAlign="LEFT")
    empty_line = Spacer(1, 20)
    report_pie = Pie(width=3 * 30, height=3 * 30)
    empty_line = Spacer(1, 20)
    report_pie.data = data
    report_pie.labels = labels
    report_chart = Drawing()
    report_chart.add(report_pie)
    report.build([
        report_title, empty_line, report_info, empty_line, report_table,
        report_chart
    ])
Exemplo n.º 19
0
 def diagrammKostenartVonBis(self, aPfad, aDateiname, aData, aLabels):
     d = Drawing(800, 800)
     pie = Pie()
     pie.x = 360
     pie.y = 360
     pie.xradius = 300
     pie.yradius = 300
     pie.data = aData
     pie.labels = aLabels
     pie.slices.strokeWidth = 0.5
     # pie.slices[3].popout = 20
     d.add(pie)
     d.save(formats=['png'], outDir=aPfad, fnRoot=aDateiname)
Exemplo n.º 20
0
    def add_pie_chart(self, width, height, labels, data, side_labels=False):
        pad = 15

        pc = Pie()
        pc.x = pad * mm
        pc.y = pad * mm
        pc.width = (width - 2 * pad) * mm
        pc.height = (height - 2 * pad) * mm

        pc.labels = labels
        pc.data = data
        pc.sideLabels = side_labels

        drawing = Drawing(width * mm, height * mm)
        drawing.hAlign = "CENTER"
        drawing.add(pc)
        self.story.append(drawing)
Exemplo n.º 21
0
 def __init__(self,width=200,height=150,*args,**kw):
     Drawing.__init__(self,width,height,*args,**kw)
     self._add(self,Pie(),name='chart',validate=None,desc="The main chart")
     self.chart.width      = 100
     self.chart.height     = 100
     self.chart.x          = 25
     self.chart.y          = 25
     self.chart.slices[0].fillColor = color01
     self.chart.slices[1].fillColor = color02
     self.chart.slices[2].fillColor = color03
     self.chart.slices[3].fillColor = color04
     self.chart.slices[4].fillColor = color05
     self.chart.slices[5].fillColor = color06
     self.chart.slices[6].fillColor = color07
     self.chart.slices[7].fillColor = color08
     self.chart.slices[8].fillColor = color09
     self.chart.slices[9].fillColor = color10
     self.chart.data                = (100, 150, 180)
     self.chart.startAngle          = -90
     self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart")
     self.Title.fontName   = 'Helvetica-Bold'
     self.Title.fontSize   = 7
     self.Title.x          = 100
     self.Title.y          = 135
     self.Title._text      = 'Chart Title'
     self.Title.maxWidth   = 180
     self.Title.height     = 20
     self.Title.textAnchor ='middle'
     self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart")
     self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'), (color03, 'Central')]
     self.Legend.fontName       = 'Helvetica'
     self.Legend.fontSize       = 7
     self.Legend.x              = 160
     self.Legend.y              = 85
     self.Legend.dxTextSpace    = 5
     self.Legend.dy             = 5
     self.Legend.dx             = 5
     self.Legend.deltay         = 5
     self.Legend.alignment      ='right'
     self.Legend.columnMaximum  = 10
     self.chart.slices.strokeWidth  = 1
     self.chart.slices.fontName     = 'Helvetica'
     self.background                = ShadedRect()
     self.background.fillColorStart = backgroundGrey
     self.background.fillColorEnd   = backgroundGrey
     self.background.numShades      = 1
     self.background.strokeWidth    = 0.5
     self.background.x              = 20
     self.background.y              = 20
     self.chart.slices.popout       = 5
     self.background.height         = 110
     self.background.width          = 110
     self._add(self,0,name='preview',validate=None,desc=None)
Exemplo n.º 22
0
    def get2PieChart():
        legend = Legend()
        a = df2.iloc[i, 13]
        b = df2.iloc[i, 14]
        c = df2.iloc[i, 15]
        d = df2.iloc[i, 16]
        e = df2.iloc[i, 17]
        da = [a, b, c, d, e]

        x = 0
        y = 0
        for i5 in da:
            if i5 == "Attempted":
                x = x + 1
            else:
                y = y + 1
        data = [x, y]
        u = round(x * 100 / 5)
        v = round(y * 100 / 5)
        h = [u, v]
        d = []
        l = ["%.2f" % i5 for i5 in h]
        for i5 in l:
            k = i5.split(".")
            d.append(k[0])
        e = []
        j = 0
        for i5 in d:
            #w=i5+"%"
            j = j + 1
            w = i5 + "%"
            if j == 1:
                w = w + " (Attempted)"
            if j == 2:
                w = w + " (Unattempted)"
            e.append(w)
        drawing = Drawing(width=400, height=200)
        my_title = String(170, 40, 'Attempts', fontSize=14)
        pie = Pie()
        pie.sideLabels = True
        pie.slices.popout = 3
        pie.x = 140
        pie.y = 60
        pie.data = data
        pie.labels = [letter for letter in e]
        pie.slices.strokeWidth = 0.5
        drawing.add(my_title)
        n = len(pie.data)
        setItems(n, pie.slices, 'fillColor', pdf_chart_colors)
        legend.colorNamePairs = [(pie.slices[i5].fillColor,
                                  (pie.labels[i5][0:20],
                                   '%0.2f' % pie.data[i5])) for i5 in range(n)]
        drawing.add(pie)
        add_legend(drawing, pie, data)
        return drawing
Exemplo n.º 23
0
def makePie(pdf, SeBAz_contents, total):
    pdf.saveState()
    d = Drawing(A4[0] * 6 / 12, A4[1] * 5 / 17)
    pc = Pie()
    pc.x = A4[0] * 4 / 12
    pc.y = A4[1] * 5 / 17
    pc.width = A4[0] * 4 / 12
    pc.height = A4[0] * 4 / 12
    passd = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'PASS'])
    faild = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'FAIL'])
    check = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'CHEK'])
    excluded = total - (passd + faild + check)
    pc.data = [passd, faild, excluded, check]
    pc.simpleLabels = 0
    pc.slices.strokeWidth = 0.5
    pc.slices.fontName = 'SF-Pro-Rounded-Heavy'
    pc.slices.fontSize = 8
    pc.slices.labelRadius = 1.1
    pc.slices[0].popout = 10
    pc.slices[0].fillColor = Color(colorPass[0] / 256, colorPass[1] / 256,
                                   colorPass[2] / 256, 1)
    pc.slices[0].fontColor = Color(colorPass[0] / 256, colorPass[1] / 256,
                                   colorPass[2] / 256, 1)
    pc.slices[
        0].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) Passed,'.format(
            (passd / total) * 100, passd, (passd + faild + check),
            (passd / (passd + faild + check)) * 100)
    pc.slices[1].fillColor = Color(colorFail[0] / 256, colorFail[1] / 256,
                                   colorFail[2] / 256, 1)
    pc.slices[1].fontColor = Color(colorFail[0] / 256, colorFail[1] / 256,
                                   colorFail[2] / 256, 1)
    pc.slices[
        1].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) Failed,'.format(
            (faild / total) * 100, faild, (passd + faild + check),
            (faild / (passd + faild + check)) * 100)
    pc.slices[2].fillColor = darkgray
    pc.slices[2].fontColor = darkgray
    pc.slices[2].label_text = '{} of {} tests ({:.0f}%) Excluded'.format(
        excluded, total, (excluded / total) * 100)
    pc.slices[3].fillColor = Color(colorWarn[0] / 256, colorWarn[1] / 256,
                                   colorWarn[2] / 256, 1)
    pc.slices[3].fontColor = Color(colorWarn[0] / 256, colorWarn[1] / 256,
                                   colorWarn[2] / 256, 1)
    pc.slices[
        3].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) are to be Checked,'.format(
            (check / total) * 100, check, (passd + faild + check),
            (check / (passd + faild + check)) * 100)
    d.add(pc)
    renderPDF.draw(d, pdf, -A4[0] / 52, -A4[1] / 6)
    pdf.restoreState()
Exemplo n.º 24
0
def sample4pie():
    width = 300
    height = 150
    d = Drawing(width, height)
    pc = Pie()
    pc.x = 150
    pc.y = 50
    pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50]
    pc.labels = u'0 \xe4 b c d e f g h i'.split()
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 20
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    pc.slices[1].fontName = fontName
    d.add(pc)
    legend = Legend()
    legend.x = width - 5
    legend.y = height - 5
    legend.dx = 20
    legend.dy = 5
    legend.deltax = 0
    legend.boxAnchor = 'nw'
    legend.colorNamePairs = Auto(chart=pc)
    d.add(legend)
    return d
Exemplo n.º 25
0
def build_pdf():
    fruit = {"elderberries": 1,"figs": 1,"apples": 2,"durians": 3,"bananas": 5,"cherries": 8,"grapes": 13}
    report = SimpleDocTemplate("/home/scottdavis/eclipse-workspace/module1/report.pdf")
    styles = getSampleStyleSheet()
    report_title = Paragraph("A Complete Inventory of My Fruit", styles["h1"])
    table_data = []
    for k, v in fruit.items():
        table_data.append([k, v])
    
    table_style = [('GRID', (0,0), (-1,-1), 1, colors.black)]
    report_table = Table(data=table_data, style=table_style, hAlign="LEFT")
    
    
    report_pie = Pie()
    #width=3*inch, height=3*inch
    report_pie.width = 180
    report_pie.height = 180
    report_pie.data = []
    report_pie.labels = []
    
    for fruit_name in sorted(fruit):
        report_pie.data.append(fruit[fruit_name])
        report_pie.labels.append(fruit_name)
    
    report_chart = Drawing()
    report_chart.add(report_pie)
    
    report.build([report_title, report_table, report_chart])
Exemplo n.º 26
0
def sample4pie():
    width = 300
    height = 150
    d = Drawing(width, height)
    pc = Pie()
    pc.x = 150
    pc.y = 50
    pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50]
    pc.labels = ['0','a','b','c','d','e','f','g','h','i']
    pc.slices.strokeWidth=0.5
    pc.slices[3].popout = 20
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2,2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    d.add(pc)
    legend = Legend()
    legend.x = width-5
    legend.y = height-5
    legend.dx = 20
    legend.dy = 5
    legend.deltax = 0
    legend.boxAnchor = 'nw'
    legend.colorNamePairs=Auto(chart=pc)
    d.add(legend)
    return d
Exemplo n.º 27
0
    def test0(self, isFast=0):
        """Hello World, on a rectangular background.

        The rectangle's fillColor is yellow.
        The string's fillColor is red.
        """
        reportlab.rl_config.shapeChecking = not isFast

        pdfPath = outputfile('test_graphics_speed_fast.pdf')
        c = Canvas(pdfPath)
        t0 = time.time()

        d = Drawing(400, 200)
        num = 100
        for i in range(num):
            pc = Pie()
            pc.x = 150
            pc.y = 50
            pc.data = [10, 20, 30, 40, 50, 60]
            pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
            pc.slices.strokeWidth = 0.5
            pc.slices[3].popout = 20
            pc.slices[3].strokeWidth = 2
            pc.slices[3].strokeDashArray = [2, 2]
            pc.slices[3].labelRadius = 1.75
            pc.slices[3].fontColor = colors.red
            d.add(pc)
        d.drawOn(c, 80, 500)

        t1 = time.time()

        result = 'drew %d pie charts in %0.4f' % (num, t1 - t0)
        open(outputfile('test_graphics_speed_test%s.log' % (isFast + 1)),
             'w').write(result)
Exemplo n.º 28
0
def pie_chart_with_legend(doc, FI, Equity):
    data = ['Bond (' + str(FI[-1]) + '%)', 'Equity (' + str(Equity[-1]) + '%)']
    drawing = Drawing(width=doc.width / 2, height=250)
    my_title = String(140, -70, 'Asset-wise Allocation', fontSize=14)
    pie = Pie()
    pie.sideLabels = False
    pie.slices.label_visible = False
    pie.x = 100
    pie.y = -40
    pie.width = 200
    pie.height = 200
    pie.data = [FI[-1], Equity[-1]]
    pie.labels = data
    pie.slices.strokeWidth = 0.5
    drawing.add(my_title)
    drawing.add(pie)
    add_legend(drawing, pie, data, doc)
    return drawing
Exemplo n.º 29
0
 def subtest(sa,d):
     pc = Pie()
     pc.direction=d
     pc.startAngle=sa
     arcs = _makeSideArcDefs(sa,d)
     A = [x[1] for x in pc.makeAngles()]
     arcsum = sum([a[2]-a[1] for a in arcs])
     isum = intSum(arcs,A)
     mi = max([a[2]-a[1] for a in arcs])
     ni = min([a[2]-a[1] for a in arcs])
     l = []
     s = (arcsum-360)
     if s>1e-8: l.append('Arc length=%s != 360' % s)
     s = abs(isum-360)
     if s>1e-8: l.append('interval intersection length=%s != 360' % s)
     if mi>360: l.append('max interval intersection length=%s >360' % mi)
     if ni<0: l.append('min interval intersection length=%s <0' % ni)
     if l:
         l.append('sa: %s d: %s' % (sa,d))
         l.append('sidearcs: %s' % str(arcs))
         l.append('Angles: %s' % A)
         raise ValueError('piecharts._makeSideArcDefs failure\n%s' % '\n'.join(l))
Exemplo n.º 30
0
    def __init__(self, width=100, height=100, *args, **kwargs):
        Drawing.__init__(self, width, height, *args, **kwargs)
        self.add(Pie(), name='chart')
        #transparent = colors.Color(255, 255, 255, alpha=0.5)
        #print dir(transparent)
        #print dir(self)
        #self.setFillColor(transparent)

        for i in range(10):
            self.chart.slices[i].fillColor = PIE_CHART_COLORS[i]
            self.chart.slices[i].labelRadius = 1.4
            self.chart.slices[i].fontName = 'Helvetica'
            self.chart.slices[i].fontSize = 8
 def _add_pie_chart(
     self,
     expense_stats: Dict[str, Tuple],
     size: int,
     padding: int,
 ):
     if expense_stats:
         figure = Drawing(self.width, min(size + 2 * padding, self.height))
         pie_chart = Pie()
         pie_chart.x = (self.width - size) / 2
         pie_chart.y = padding
         pie_chart.width = size
         pie_chart.height = size
         pie_chart.data = [i[0] for i in expense_stats.values()]
         pie_chart.labels = list(expense_stats.keys())
         pie_chart.slices.strokeWidth = 0.5
         pie_chart.sideLabels = True
         figure.add(pie_chart)
         self.report_elements.append(figure)
def graphout(prod_catnames, data):
    drawing = Drawing(500, 200)
    pie = Pie()

    pie.sideLabels       = 1
    pie.labels           = prod_catnames
    pie.data             =  data[0]
    pie.width            = 140
    pie.height           = 140
    pie.y                = 35
    pie.x                = 125
    pie.slices.popout = 5 
    
    drawing.add(pie)
        
    return drawing
Exemplo n.º 33
0
def pie_chart(car_data):
    report_pie = Pie()
    report_pie.width = 380
    report_pie.height = 380
    report_pie.x = 42
    report_pie.y = -230
    report_pie.data = []
    report_pie.labels = []
    car_make = {}
    for item in car_data:
        car_info = format_car(item["car"])
        report_pie.data.append(item["total_sales"])
        report_pie.labels.append(car_info)
    report_chart = Drawing()
    report_chart.add(report_pie)
    return (report_chart)
Exemplo n.º 34
0
    def __init__(self, data, labels):
        super(PieChart, self).__init__(400, 200)

        colors = [
            HexColor("#0000e5"),
            HexColor("#ff0011"),
            HexColor("#800000"),
            HexColor("#e05897"),
            HexColor("#a08ff7"),
            HexColor("#8f8ff5"),
            HexColor("#c7c7fa"),
            HexColor("#800000"),
            HexColor("#eb8585"),
            HexColor("#d60a0a"),
            HexColor("#ffff00"),
            HexColor("#1f1feb"),
        ]

        # Create pie chart
        pieChart = Pie()
        pieChart.x = 40
        pieChart.y = 30
        pieChart.width = 120
        pieChart.height = 120
        pieChart.slices.strokeWidth = 0.5
        data = json.loads(data)
        pieChart.data = data
        pieChart.labels = []
        labels = json.loads(labels.replace("'", '"'))
        for d in data:
            pieChart.labels.append(str(d))

        # Create legend
        legend = Legend()
        legend.x = 380
        legend.y = 60
        legend.boxAnchor = 'se'
        legend.subCols[1].align = 'right'
        legend.colorNamePairs = []

        len_data = len(data)
        for i in range(0, len_data):
            pieChart.slices[i].fillColor = colors[i]
            legend.colorNamePairs.append((colors[i], labels[i]))

        self.add(pieChart, "pie chart")
        self.add(legend, "legend")
Exemplo n.º 35
0
    def __init__(self, width=600, height=400, *args, **kw):
        apply(Drawing.__init__, (self, width, height) + args, kw)
        # adding a pie chart to the drawing
        self._add(self, Pie(), name='pie', validate=None, desc=None)
        self.pie.width = 350
        self.pie.height = self.pie.width
        self.pie.x = 20
        self.pie.y = (height - self.pie.height) / 2

        t = MacroObject.objects.all()
        list1 = []
        list2 = []
        for l in t:
            list1.append(l.valu)
            list2.append(l.text)
        self.pie.data = list1
        self.pie.labels = list2
        self.pie.simpleLabels = 1
        self.pie.slices.label_visible = 0
        self.pie.slices.fontColor = None
        self.pie.slices.strokeColor = white
        self.pie.slices.strokeWidth = 1
        # adding legend
        self._add(self, Legend(), name='legend', validate=None, desc=None)
        self.legend.x = 400
        self.legend.y = height / 2
        self.legend.dx = 40
        self.legend.dy = 40
        self.legend.fontName = 'Helvetica'
        self.legend.fontSize = 7
        self.legend.boxAnchor = 'w'
        self.legend.columnMaximum = 10
        self.legend.strokeWidth = 1
        self.legend.strokeColor = black
        self.legend.deltax = 85
        self.legend.deltay = 20
        self.legend.autoXPadding = 5
        self.legend.yGap = 0
        self.legend.dxTextSpace = 5
        self.legend.alignment = 'right'
        self.legend.dividerLines = 1 | 2 | 4
        self.legend.dividerOffsY = 4.5
        self.legend.subCols.rpad = 30
        n = len(self.pie.data)
        setItems(n, self.pie.slices, 'fillColor', pdf_chart_colors)
        self.legend.colorNamePairs = [(self.pie.slices[i].fillColor,
                                       (self.pie.labels[i][0:20],
                                        '%0.2f' % self.pie.data[i]))
                                      for i in xrange(n)]
Exemplo n.º 36
0
    def pie(saidas):
        archive = 'ibc_financeiro/static/chart.pdf'

        PDF = SimpleDocTemplate(archive, pagesize = A4)

        categories, totais = [], []

        for saida in saidas:
            if saida.categoria.nome not in categories:
                categories.append(saida.categoria.nome)
        
        for category in categories:
            total = 0

            for saida in saidas:
                if category == saida.categoria.nome:
                    total += saida.valor

            totais.append(int(total))

        title = String(55, 300, 'Gráficos', fontSize = 24, fontName = 'Times-Bold')
        subtitle = String(30, 255, 'Categorias de Saída', fontSize = 16, fontName = 'Times-Bold')

        chart = Pie()
        chart.data, chart.labels = totais, categories
        chart.sideLabels = True
        chart.height, chart.width = 200, 200

        drawing = Drawing(240, 120)
        drawing.add(title)
        drawing.add(subtitle)
        drawing.add(chart)

        table = Table([[drawing]], 215, 300)

        PDF.build([table])
Exemplo n.º 37
0
def graphout_pie(data, labels, sizeOfDrawing): # data and labels are both lists of same size
	drawing = Drawing(sizeOfDrawing*inch, sizeOfDrawing*inch)
	pc = Pie()
	pc.x = .125*inch
	pc.y = .125*inch
	pc.width = (sizeOfDrawing-0.25)*inch
	pc.height = (sizeOfDrawing-0.25)*inch
	pc.data = data
	pc.labels = None
	pc.slices.strokeWidth = 0.5
	
	# ensure pie chart and legend coloring matches
	for i in range(len(labels)):
		pc.slices[i].fillColor = colorList[i]

	drawing.add(pc)
	return drawing
Exemplo n.º 38
0
def report_pdf(request):
    feedbacks = Feedback.objects.all()
##    import pygraphviz as P
##    A=P.AGraph() # init empty graph
##    # set some default node attributes
##    A.node_attr['style']='filled'
##    A.node_attr['shape']='circle'
##    # Add edges (and nodes)
##    A.add_edge(1,2)
##    A.add_edge(2,3)
##    A.add_edge(1,3)
##    A.layout() # layout with default (neato)
##    png=A.draw(format='png') # draw png
##    return HttpResponse(png, mimetype='image/png')
    pdf_data = open('cfback/feed.pdf','rb').read()
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="feedback.pdf"'
    

    buffer = BytesIO()
   
    p = Drawing(400,200)
##    p.add(String(300,175, "Feedbacks", textAnchor="middle"))
    pc = Pie()
    pc.x = 150
    pc.y = 50
    pc.data = [enumerate([i.title[0]]) for i in feedbacks]
    pc.labels = [str(y.company) for y in feedbacks]
    p.add(pc)
##    p.showPage()
    p.save()

    pdf = buffer.getvalue()
    buffer.close
    response.write(pdf)
    return render_to_response('cfback/feed_report.html', response)
Exemplo n.º 39
0
def pie_chart_with_legend(data, answerKey):
    drawing = Drawing(width=400, height=200)
    my_title = String(170, 40, 'Pie', fontSize=12)
    pie = Pie()
    pie.sideLabels = True
    pie.x = 150
    pie.y = 65
    pie.data = data
    pie.labels = [letter for letter in answerKey]
    pie.slices.strokeWidth = 0.5
    drawing.add(my_title)
    drawing.add(pie)
    add_legend(drawing, pie, data)
    return drawing
Exemplo n.º 40
0
def pie_chart_with_legend():
    data = list(range(15, 105, 15))
    drawing = Drawing(width=400, height=200)
    my_title = String(170, 40, 'My Pie Chart', fontSize=14)
    pie = Pie()
    pie.sideLabels = True
    pie.x = 150
    pie.y = 65
    pie.data = data
    pie.labels = [letter for letter in 'abcdefg']
    pie.slices.strokeWidth = 0.5
    drawing.add(my_title)
    drawing.add(pie)
    add_legend(drawing, pie, data)
    return drawing
Exemplo n.º 41
0
    def _graphout(doc, category_names, data):
        drawing = Drawing(doc.width, 150)
        graph = Pie()
        graph.x = doc.width / 2 - 50
        graph.y = 0
        graph.height = 100
        graph.width = 100
        graph.labels = category_names
        graph.data = data
        graph.slices[0].fillColor = colors.darkcyan
        graph.slices[1].fillColor = colors.blueviolet
        graph.slices[2].fillColor = colors.blue
        graph.slices[3].fillColor = colors.cyan
        graph.slices[4].fillColor = colors.aquamarine
        graph.slices[5].fillColor = colors.cadetblue
        graph.slices[6].fillColor = colors.lightcoral

        drawing.add(graph)
        return drawing
Exemplo n.º 42
0
def simple_pie_chart_side_labels():
    data = list(range(15, 105, 15))
    drawing = Drawing()
    pie = Pie()
    pie.sideLabels = True

    pie.x = 150
    pie.y = 65

    pie.data = data
    pie.labels = [letter for letter in 'abcdefg']
    pie.slices.strokeWidth = 0.5
    drawing.add(pie)
    drawing.save(formats=['pdf'],
                 outDir='.',
                 fnRoot='simple_pie_chart_side_labels')
Exemplo n.º 43
0
    def __init__(self, data, labels):
        super(PieChart, self).__init__(400,200)

        colors = [  
            HexColor("#0000e5"),  
            HexColor("#ff0011"),
            HexColor("#800000"),
            HexColor("#e05897"),   
            HexColor("#a08ff7"),  
            HexColor("#8f8ff5"),  
            HexColor("#c7c7fa"),  
            HexColor("#800000"),  
            HexColor("#eb8585"),   
            HexColor("#d60a0a"),  
            HexColor("#ffff00"),
            HexColor("#1f1feb"),   
        ]  

        # Create pie chart 
        pieChart = Pie()
        pieChart.x = 40
        pieChart.y = 30
        pieChart.width = 120
        pieChart.height = 120
        pieChart.slices.strokeWidth=0.5
        data = json.loads(data)
        pieChart.data = data
        pieChart.labels = []
        labels = json.loads(labels.replace("'",'"'))
        for d in data:
            pieChart.labels.append(str(d))

        # Create legend
        legend = Legend()
        legend.x = 380
        legend.y = 60  
        legend.boxAnchor           = 'se'  
        legend.subCols[1].align    = 'right'
        legend.colorNamePairs = []

        len_data = len(data) 
        for i in range(0,len_data):
            pieChart.slices[i].fillColor = colors[i]
            legend.colorNamePairs.append((colors[i],labels[i]))

        self.add(pieChart, "pie chart")       
        self.add(legend, "legend")
Exemplo n.º 44
0
    def __init__(self, width=200, height=200, *args, **kw):
        Drawing.__init__(self, width, height, *args, **kw)
        self.add(Pie(), name='pie')
        self.add(Legend(), name='legend')

        self.pie.x = 110
        self.pie.y = -50
        self.pie.width = self.width - 20
        self.pie.height = self.height - 40
        self.pie.slices.label_pointer_piePad = 20  # Distance between the wafer and the label
        self.pie.slices.label_pointer_edgePad = 20  # The distance between the label and the outer
        self.pie.simpleLabels = 0  # 0 label on the right side of the label line; 1 on the line
        self.pie.sameRadii = 1  # 0 Pie chart is an ellipse; 1 Pie chart is a circle
        self.pie.pointerLabelMode = 'LeftRight'
        self.legend.x = 300
        self.legend.y = -100
        self.legend.alignment = 'right'
        self.legend.fontSize = 15
Exemplo n.º 45
0
def pie_graph(data, elements):
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = data
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
Exemplo n.º 46
0
def create_pie(pie_data):
    pie_chart = Drawing(400, 200)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 100
    pc.height = 100
    pc.data = pie_data["data"]     	     
    pc.labels = list(pie_data["label"][0]) 
    pc.slices.strokeWidth=0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2,2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    pie_chart.add(pc)
    return pie_chart
def getPieChart(c,
                x,
                y,
                data,
                data_suff,
                labels,
                colors,
                fsize=8.5,
                radius=0.60,
                legdx=180,
                legdy=100):
    """ Function to draw a Pie Chart """

    d = Drawing(200, 200)
    legend = Legend()
    legend.columnMaximum = 99
    legend.alignment = 'right'
    legend.dx = 7
    legend.dy = 7
    legend.dxTextSpace = 5
    legend.deltay = 10
    legend.strokeWidth = 0
    legend.strokeColor = HexColor("0xffffff")
    legend.subCols[0].minWidth = 75
    legend.subCols[0].align = 'left'
    legend.boxAnchor = 'c'
    legend.y = legdy
    legend.x = legdx
    legend.fontName = "MavenPro"
    legend.fontSize = 8.5
    legendList = []
    for k, i in enumerate(colors):
        legendList.append((HexColor(i), labels[k]))

    legend.colorNamePairs = legendList

    pc3 = Pie()
    pc3.x = 10
    pc3.y = 10
    pc3.data = data
    pc3.labels = [str(r) + data_suff if r >= 15 else "" for r in data]
    pc3.slices.strokeColor = HexColor("0xffffff")
    pc3.slices.labelRadius = radius
    pc3.slices.fontName = "MavenPro"
    pc3.slices.fontSize = fsize
    pc3.slices.fontColor = HexColor("0xffffff")
    for k, i in enumerate(colors):
        pc3.slices[k].fillColor = HexColor(i)
    d.add(pc3, 'pie3')
    d.add(legend, 'legend')
    d.drawOn(c, x, y)
Exemplo n.º 48
0
def piegraph(elements):
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = [10, 20, 30, 40, 50, 60]
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.7 * inch))
Exemplo n.º 49
0
 def pie_chart_draw(self, values, llabels):
     d = Drawing(10, 150)
     # chart
     pc = Pie()
     pc.x = 50
     pc.y = 30
     # set data
     pc.data = values
     # set labels
     pc.labels = get_percentage(values)
     # set the link line between slice and it's label
     pc.sideLabels = 1
     # set width and color for slices
     pc.slices.strokeWidth = 1
     pc.slices.strokeColor = None
     d.add(self.title_draw(180, 140, 'Asistencia'))
     d.add(pc)
     d.add(self.legend_draw(llabels, pc, x=290, y=100, boxAnchor='ne',
                            columnMaximum=12, type='pie'))
     return d
 def pie_chart_draw(self, values, llabels):
     d = Drawing(10, 150)
     # chart
     pc = Pie()
     pc.x = 0
     pc.y = 50
     # set data
     pc.data = values
     # set labels
     pc.labels = get_percentage(values)
     # set the link line between slice and it's label
     pc.sideLabels = 1
     # set width and color for slices
     pc.slices.strokeWidth = 0
     pc.slices.strokeColor = None
     d.add(self.title_draw(250, 180,
                           _('Precipitation probability statistics')))
     d.add(pc)
     d.add(self.legend_draw(llabels, pc, x=300, y=150, boxAnchor='ne',
                            columnMaximum=12, type='pie'))
     return d
Exemplo n.º 51
0
pc3.slices.fontColor = colors.yellow
d.add(pc3, 'pie3')
""")

# Hack to force a new paragraph before the todo() :-(
disc("")

from reportlab.lib.colors import *
from reportlab.graphics import shapes,renderPDF
from reportlab.graphics.charts.piecharts import Pie

d = Drawing(400,200)
d.add(String(100,175,"Without labels", textAnchor="middle"))
d.add(String(300,175,"With labels", textAnchor="middle"))

pc = Pie()
pc.x = 25
pc.y = 50
pc.data = [10,20,30,40,50,60]
pc.slices[0].popout = 5
d.add(pc, 'pie1')

pc2 = Pie()
pc2.x = 150
pc2.y = 50
pc2.data = [10,20,30,40,50,60]
pc2.labels = ['a','b','c','d','e','f']
d.add(pc2, 'pie2')

pc3 = Pie()
pc3.x = 275
Exemplo n.º 52
0
def generar_pdf_busquedas_view(request):
    print "Genero el PDF"
    fecha_m = ""
    resultados=[]
    fecha_a = ""
    b=[]
    t=[]
    fecha_inicio = x
    fecha_final = y
    c=0
    r=[]
    #story =[]

    


    response = HttpResponse(content_type='application/pdf')
    pdf_name = "reporte_busqueda.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    reportes = []
    styles = getSampleStyleSheet()
    fichero_imagen="biblioteca/media/images/Reports-banner.jpg"

    imagen_logo=Image(os.path.realpath(fichero_imagen),width=400,height=100)
    reportes.append(imagen_logo)
    

    header = Paragraph("Fecha del reporte: "+str(date.today()), styles['Heading1'])
    
    header2 = Paragraph("Reporte de las busquedas realizadas entre la fecha "+str(fecha_inicio)+" hasta la fecha "+str(fecha_final) + "\n", styles['Normal'])
    salto_linea = Paragraph("\n\n", styles["Normal"])

    reportes.append(header)
   
    reportes.append(header2)
    reportes.append(Spacer(1, 12))
    

    headings = ('Busqueda', 'Resultado',)# 'Cantidad_Veces_Buscadas')
    lista=[]
    t = Busqueda.objects.all()
    b = Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct()



    listar=[]
    for r in b:
        print "llllllllllllllllll",r,"\n"

        if r['resultados'] == False:
            r['resultados']="No se encontró"
            listar.append(r)  
        else:
            r['resultados']="Se encontró"
            listar.append(r)




    print "lisygyujgyjgjhbjh", listar


  




#GRAFICAS BARRA
    total_busquedas=Busqueda.objects.all().count() #TOTAL BUSQUEDAS
    si=Busqueda.objects.filter(resultados=True).count() #BUSUEDAS ENCONTRADAS (SI)
    no=total_busquedas-si #BUSQUEDAS NO ENCONTRADAS (NO)


#GRAFICAS PASTEL
    


    for i in b:
        print "________________",i.get("busqueda")
        for j in t:
            print "===============",j.busqueda
            if j.busqueda == i.get("busqueda") and j.fecha >= fecha_inicio and j.fecha <= fecha_final:
                c = c + 1
                print c
        lista.append(c)
        c=0     
    print lista , len(lista)

    li = zip(b,lista)               
    '''
    for i in b:
        print "________________",i.get("busqueda")
        for j in t:
            print "===============",j.busqueda
            if j.busqueda == i.get("busqueda"):
                c = c + 1
                print c
        lista.append(c)
        c=0
        li = zip(b,lista)
    '''

    #allreportes = [ (i.busqueda, i.resultados) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct()]

   # allreportes = [ i.values() for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct()]
    b=listar

    allreportes = [ i.values() for i in b]

   
    print allreportes


    t = Table([headings] + allreportes)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))


#GRAFICA DE BARRAS

    titulo = Paragraph("Busquedas encontradas y no encontradas en el sistema", estilo['title'])

    drawing = Drawing(400, 200)
    data = [(si, no)]
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = data
    bc.bars[0].fillColor = colors.blue
    bc.bars[1].fillColor = colors.black
    bc.strokeColor = colors.black
    bc.fillColor = colors.silver
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = total_busquedas+30
    try:
        r = total_busquedas/2
        if type(r) == 'float':
            bc.valueAxis.valueStep = total_busquedas+0.5
        if type(r) == 'int':
            bc.valueAxis.valueStep = r
    except:
        "Nos se puede"


    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 0
    bc.categoryAxis.categoryNames = ['Encontradas', 'No Encontradas']
    drawing.add(bc)

    bc.barLabels.nudge = 20
    bc.barLabelFormat = '%0.0f'
    bc.barLabels.dx = 0
    bc.barLabels.dy = 0
    bc.barLabels.boxAnchor = 'n' # irrelevant (becomes 'c')
    bc.barLabels.fontName = 'Helvetica'
    bc.barLabels.fontSize = 14





    
#GRAFICAS DE PASTEL
    titulo2 = Paragraph("Busquedas y número de veces realizadas", estilo['title'])

    d = Drawing(400, 200)
    pc = Pie()
    pc.x = 125
    pc.y = 25
    pc.data = lista
    print lista
    #pc.data = [7, 1, 1, 1, 1, 2]

    #pc.labels = [ str(i.values()) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda').distinct()]
    lista_labels = [ str(i.values()) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda').distinct()]
    #pc.labels = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6']
    pc.sideLabels = 1
    pc.width = 150
    pc.height = 150
    pc.slices.strokeWidth=1#0.5
    pc.slices[0].fillColor = colors.yellow
    pc.slices[1].fillColor = colors.thistle
    pc.slices[2].fillColor = colors.cornflower
    pc.slices[3].fillColor = colors.lightsteelblue
    pc.slices[4].fillColor = colors.aquamarine
    pc.slices[5].fillColor = colors.cadetblue
    d.add(pc)



    legend = Legend() 
    legend.x               = 370
    legend.y               = 0
    legend.dx              = 10 
    legend.dy              = 10 
    legend.fontName        = 'Helvetica' 
    legend.fontSize        = 10 
    legend.boxAnchor       = 'n' 
    legend.columnMaximum   = 10 
    legend.strokeWidth     = 1 
    legend.strokeColor     = colors.black  
    legend.deltax          = 75 
    legend.deltay          = 10 
    legend.autoXPadding    = 5 
    legend.yGap            = 0 
    legend.dxTextSpace     = 5 
    legend.alignment       = 'right' 
    legend.dividerLines    = 1|2|4 
    legend.dividerOffsY    = 4.5 
    legend.subCols.rpad    = 30 
     
    #Insertemos nuestros propios colores
    colores  = [colors.blue, colors.red, colors.green, colors.yellow, colors.black, colors.white, colors.silver, colors.pink, colors.brown, colors.orange, colors.purple]
    for i, color in enumerate(colores): 
        pc.slices[i].fillColor = color
         
    legend.colorNamePairs  = [(
                                pc.slices[i].fillColor, 
                                (lista_labels[i][0:200], '%0.0f' % pc.data[i])
                               ) for i in xrange(len(pc.data))]
     
    d.add(pc) 
    
    

    reportes.append(t)

    
    reportes.append(Spacer(0, inch*.1))
    reportes.append(Spacer(0, inch*.1))
    reportes.append(Spacer(0, inch*.1))
    reportes.append(titulo)
    
    reportes.append(drawing)
    reportes.append(Spacer(0, inch*.1))
    reportes.append(Spacer(0, inch*.1))

    reportes.append(titulo2)
    d.add(legend)
    reportes.append(d)
    doc.build(reportes)
    response.write(buff.getvalue())
    buff.close()
    return response
def plpleg(i=None):
    from reportlab.lib.colors import pink, red, green

    pie = Pie()
    pie.x = 0
    pie.y = 0
    pie.pointerLabelMode = "LeftAndRight"
    pie.slices.label_boxStrokeColor = red
    pie.simpleLabels = 0
    pie.sameRadii = 1
    pie.data = [1, 0.1, 1.7, 4.2, 0, 0]
    pie.labels = ["abcdef", "b", "c", "d", "e", "fedcba"]
    pie.strokeWidth = 1
    pie.strokeColor = green
    pie.slices.label_pointer_piePad = 6
    pie.width = 160
    pie.direction = "clockwise"
    pie.pointerLabelMode = "LeftRight"
    return autoLegender(i, pie, pie.slices, None)
Exemplo n.º 54
0
def generate_certificate(elements):
    style = TableStyle([('TEXTALIGN', (0, 0), (-1, -1), 'CENTER'),
                        ('TEXTCOLOR', (0, 0), (-1, -1), colors.red),
                        ('VALIGN', (0, 0), (0, -1), 'TOP'),
                        ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.red),
                        ('BOX', (0, 0), (-1, -1), 0.50, colors.green),
                        ('BACKGROUND', (0, 0), (-1, -1), colors.blue),
                        ])
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = "RGB"
    styles = ParagraphStyle(
        name='Normal',
        fontName='Helvetica-Bold',
        fontSize=15,
        alignment=1,
    )
    elements.append(Spacer(1, 0.5 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(0, 200)  # for indices
    data = [
        (13, 5, 20, 22, 37, 45, 19, 4),
        (14, 6, 21, 23, 38, 46, 20, 5)
    ]  # data for drawing bar graphs
    bc = VerticalBarChart()
    bc.x = 0  # x,y define the left bottom of graph
    bc.y = 0
    bc.height = 150
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 50
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 6  # next 3 lines is for naming indices
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 60
    bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99',
                                     'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99']
    drawing.add(bc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
    drawing = Drawing(0, 175)  # for indices
    lc = HorizontalLineChart()
    lc.x = 0
    lc.y = 10
    lc.height = 150
    lc.width = 300
    lc.data = data
    lc.joinedLines = 1
    catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ')
    lc.categoryAxis.categoryNames = catNames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 60
    lc.valueAxis.valueStep = 15
    lc.lines[0].strokeWidth = 2
    lc.lines[1].strokeWidth = 1.5
    drawing.add(lc)
    elements.append(drawing)
    drawing = Drawing(0, 400)  # for indices
    data = [
        ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)),
        ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))
    ]
    elements.append(Spacer(1, 0.1 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    lp = LinePlot()
    lp.x = 0
    lp.y = 50
    lp.height = 300
    lp.width = 600
    lp.data = data
    lp.joinedLines = 1
    lp.lines[0].symbol = makeMarker('FilledCircle')
    lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 5
    lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 7
    lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    elements.append(drawing)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = [10, 20, 30, 40, 50, 60]
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
    return elements
Exemplo n.º 55
0
def plpleg(i=None):
    from reportlab.lib.colors import pink, red, green
    pie = Pie()
    pie.x = 0
    pie.y = 0
    pie.pointerLabelMode='LeftAndRight'
    pie.slices.label_boxStrokeColor      = red
    pie.simpleLabels = 0
    pie.sameRadii = 1
    pie.data = [1, 0.1, 1.7, 4.2,0,0]
    pie.labels = ['abcdef', 'b', 'c', 'd','e','fedcba']
    pie.strokeWidth=1
    pie.strokeColor=green
    pie.slices.label_pointer_piePad      = 6
    pie.width = 160
    pie.direction = 'clockwise'
    pie.pointerLabelMode  = 'LeftRight'
    return autoLegender(i,pie,pie.slices,None)
Exemplo n.º 56
0
pc.slices.strokeWidth=0.5
pc.slices[3].popout = 10
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2,2]
pc.slices[3].labelRadius = 1.75
pc.slices[3].fontColor = colors.red

d.add(pc)
"""
)

from reportlab.graphics.charts.piecharts import Pie

d = Drawing(200, 100)

pc = Pie()
pc.x = 65
pc.y = 15
pc.width = 70
pc.height = 70
pc.data = [10, 20, 30, 40, 50, 60]
pc.labels = ["a", "b", "c", "d", "e", "f"]

pc.slices.strokeWidth = 0.5
pc.slices[3].popout = 10
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2, 2]
pc.slices[3].labelRadius = 1.75
pc.slices[3].fontColor = colors.red

d.add(pc)
Exemplo n.º 57
0
    def __get_tags_statistics(self):
        monto_categorias = dict()
        for tra in self.transactions:
            if len(tra.tags) > 0:
                for tag in tra.tags:
                    if tag in monto_categorias.keys():
                        monto_categorias[tag] += tra.amount
                    else:
                        monto_categorias[tag] = tra.amount

        labels = [lab.encode('utf-8') for lab in monto_categorias.keys()]
        data = monto_categorias.values()

        p = PageBreak()
        p.drawOn(self.c, 0, 1000)
        self.c.showPage()
        self.l = 600

        self.c.setFont('Courier', 14)
        self.c.drawString(30, 800, 'Categorias')

        drawing = Drawing(200, 200)

        pie = Pie()
        pie.x = 30
        pie.y = self.l - 130
        pie.height = 300
        pie.width = 300
        pie.data = data
        pie.labels = labels
        pie.simpleLabels = 1
        pie.slices.strokeWidth = 1
        pie.slices.strokeColor = black
        pie.slices.label_visible = 0

        legend = Legend()
        legend.x = 400
        legend.y = self.l
        legend.dx              = 8
        legend.dy              = 8
        legend.fontName        = 'Helvetica'
        legend.fontSize        = 7
        legend.boxAnchor       = 'w'
        legend.columnMaximum   = 10
        legend.strokeWidth     = 1
        legend.strokeColor     = black
        legend.deltax          = 75
        legend.deltay          = 10
        legend.autoXPadding    = 5
        legend.yGap            = 0
        legend.dxTextSpace     = 5
        legend.alignment       = 'right'
        legend.dividerLines    = 1|2|4
        legend.dividerOffsY    = 4.5
        legend.subCols.rpad    = 30
        n = len(pie.data)
        self.__setItems(n,pie.slices,
            'fillColor',self.pdf_chart_colors)

        legend.colorNamePairs = [(pie.slices[i].fillColor, 
            (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)]

        drawing.add(pie)
        drawing.add(legend)
        x, y = 0, 10

        renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
pc.slices.strokeWidth=0.5
pc.slices[3].popout = 10
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2,2]
pc.slices[3].labelRadius = 1.75
pc.slices[3].fontColor = colors.red

d.add(pc)
""")

from reportlab.graphics.charts.piecharts import Pie

d = Drawing(200, 100)

pc = Pie()
pc.x = 65
pc.y = 15
pc.width = 70
pc.height = 70
pc.data = [10,20,30,40,50,60]
pc.labels = ['a','b','c','d','e','f']

pc.slices.strokeWidth=0.5
pc.slices[3].popout = 10
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2,2]
pc.slices[3].labelRadius = 1.75
pc.slices[3].fontColor = colors.red

d.add(pc)
Exemplo n.º 59
0
def ListadoUsos(request):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=num_aprobados_reprobados.pdf; pagesize=A4;'

    #Esta lista contendra todos los elementos que se dibujaran en el pdf
    elementos = []
    doc = SimpleDocTemplate(response)
    styleSheet = getSampleStyleSheet()
    #---> Estilo Titulo
    el_titulo = styleSheet['Heading1']
    el_titulo.alignment = TA_CENTER
    el_titulo.spaceBefore = 15
    el_titulo.fontSize = 12
    el_titulo.fontName = 'Helvetica'


    txtInfo = u'<br />A.C.C.E.M.A:'
    # Estilo txtInfo
    info = styleSheet['Normal']
    info.fontSize = 12
    info.alignment = TA_LEFT
    info.fontName = 'Helvetica'
    infoV = Paragraph(txtInfo, info)

    #-->Estilo tabla
    x = [
    ('ALIGN', (0,0), (-1,-1), 'CENTER'),
    ('TOPPADDING', (0,0), (-1,-1), 1),
    ('BOTTOMPADDING', (0,0), (-1,-1), 2),
    ('GRID', (0,0), (-1,-1), 0.80, colors.black),
    ('FONT', (0,0), (-1,-1), "Helvetica", 10),
    ('FONT', (0,0), (1,0), "Helvetica-Bold", 12),
    ]
    tabla = []

    #--> Titulo de la constancia
    elementos.append(Spacer(1,5))
    Titulo = Paragraph('<b>Estadisticas de usos</b>', el_titulo)
    elementos.append(Titulo)
    elementos.append(Spacer(1,5))

    #--> Añadiendo la Informción antes del cuadro
    elementos.append(infoV)
    elementos.append(Spacer(1,10))

    usuarios = User.objects.all()
    usos = UsosDisp.objects.all()


    tabla.append([' CANTIDAD DE USUARIOS', u'NÚMERO DE USOS'])
    tabla.append(['%s'%(usuarios.__len__()), u'%s'%(usos.__len__())])

    t1 = Table(tabla, colWidths=('', ''))
    t1.setStyle(TableStyle(x))
    elementos.append(t1)

    #--> Calculando los porcentajes
    total = usos.__len__()
    
    #--> Frame del gráfico
    frame = Drawing(350,200)
    torta = Pie()
    torta.x = 125
    torta.y = 35
    torta.width = 120
    torta.height = 120

    torta.labels = []
    contador = 0 
    for i in usuarios:
        #import ipdb;ipdb.set_trace()
        uso_actual = usos.filter(Usuario=i).count()
        porcen_usuario = (float(uso_actual) * 100) / total

        torta.labels.append('%3.2f%% %s'%(porcen_usuario, i.username))
        torta.data.append(porcen_usuario)

    #--> Estilos del gráfico
    torta.slices.labelRadius = 1
    torta.sideLabels = 1
    torta.slices.fontSize = 8
    torta.slices.fontName = 'Helvetica-Bold'
    torta.slices.strokeWidth = 2
    torta.slices.popout = 10

    frame.add(torta)
    elementos.append(frame)
    doc.build(elementos, canvasmaker=NumeroDePagina )
    return response
Exemplo n.º 60
0
d.add(pc3, 'pie3')
"""
)

# Hack to force a new paragraph before the todo() :-(
disc("")

from reportlab.lib.colors import *
from reportlab.graphics import shapes, renderPDF
from reportlab.graphics.charts.piecharts import Pie

d = Drawing(400, 200)
d.add(String(100, 175, "Without labels", textAnchor="middle"))
d.add(String(300, 175, "With labels", textAnchor="middle"))

pc = Pie()
pc.x = 25
pc.y = 50
pc.data = [10, 20, 30, 40, 50, 60]
pc.slices[0].popout = 5
d.add(pc, "pie1")

pc2 = Pie()
pc2.x = 150
pc2.y = 50
pc2.data = [10, 20, 30, 40, 50, 60]
pc2.labels = ["a", "b", "c", "d", "e", "f"]
d.add(pc2, "pie2")

pc3 = Pie()
pc3.x = 275