def sample4a():
            '''Satish Darade failure'''
            from reportlab.graphics.charts.legends import LegendSwatchCallout
            from reportlab.graphics import shapes

            class LSwatchCallout(LegendSwatchCallout):
                def __init__(self, texts, fontName, fontSize):
                    self._texts = texts
                    self._fontName = fontName
                    self._fontSize = fontSize

                def __call__(self, legend, g, thisx, y, i, colName, swatch):
                    g.add(
                        shapes.String(swatch.x - 2,
                                      y,
                                      self._texts[i],
                                      textAnchor='end',
                                      fontName=self._fontName,
                                      fontSize=self._fontSize))

            d = Drawing(200, 100)
            legend = LineLegend()
            d.add(legend, 'legend')
            items = 'red green blue yellow pink black white'
            sw_names = items.upper().split()
            items = items.split()
            legend.colorNamePairs = [(getattr(colors, i), i) for i in items]
            legend.x = 20
            legend.y = 90
            d.legend.swatchCallout = LSwatchCallout(sw_names, 'Helvetica', 12)
            return d
        def sample3a():
            "Make sample legend with line swatches and dasharrays on the lines."
            d = Drawing(200, 100)
            legend = LineLegend()
            legend.alignment = 'right'
            legend.x = 20
            legend.y = 90
            legend.deltax = 60
            legend.dxTextSpace = 10
            legend.columnMaximum = 4
            items = 'red green blue yellow pink black white'.split()
            darrays = ([2, 1], [2, 5], [2, 2, 5,
                                        5], [1, 2, 3,
                                             4], [4, 2, 3,
                                                  4], [1, 2, 3, 4, 5, 6], [1])
            cnp = []
            for i in range(0, len(items)):
                l = LineSwatch()
                l.strokeColor = getattr(colors, items[i])
                l.strokeDashArray = darrays[i]
                cnp.append((l, items[i]))
            legend.colorNamePairs = cnp
            d.add(legend, 'legend')

            return d
Exemplo n.º 3
0
    def draw(self):
        legend_width = self.calc_legend_width(self.colorNamePairs, self.dx,
                                              self.deltax, self.fontName,
                                              self.fontSize, self.subCols)

        if self.positionType != "null" and self.backgroundRect is not None:
            if self.positionType == "top-left":
                self.x = self.backgroundRect.x
                self.y = self.backgroundRect.y + self.backgroundRect.height
            elif self.positionType == "top-mid":
                self.x = self.backgroundRect.x + int(
                    self.backgroundRect.width / 2) - int(legend_width / 2)
                self.y = self.backgroundRect.y + self.backgroundRect.height
            elif self.positionType == "top-right":
                self.x = self.backgroundRect.x + self.backgroundRect.width - legend_width
                self.y = self.backgroundRect.y + self.backgroundRect.height
            elif self.positionType == "bottom-left":
                self.x = self.backgroundRect.x
                self.y = self.backgroundRect.y - self.bottom_gap
            elif self.positionType == "bottom-mid":
                self.x = self.backgroundRect.x + int(
                    self.backgroundRect.width / 2) - int(legend_width / 2)
                self.y = self.backgroundRect.y - self.bottom_gap
            elif self.positionType == "bottom-right":
                self.x = self.backgroundRect.x + self.backgroundRect.width - legend_width
                self.y = self.backgroundRect.y - self.bottom_gap
            elif self.positionType == "right":
                self.x = self.backgroundRect.x + self.backgroundRect.width + 10
                self.y = self.backgroundRect.y + self.backgroundRect.height

            self.x += self.adjustX
            self.y += self.adjustY

        return LineLegend.draw(self)
Exemplo n.º 4
0
    def __init__(self,
                 width=400,
                 height=200,
                 data=[],
                 labels=[],
                 legends=[],
                 *args,
                 **kw):
        Drawing.__init__(self, width, height, *args, **kw)
        self.add(HorizontalLineChart(), name='chart')
        self.add(LineLegend(), name='legend')

        self.chart.x = 15
        self.chart.y = 15
        self.chart.width = self.width - 20
        self.chart.height = self.height - 40
        self.chart.data = data

        self.chart.categoryAxis.categoryNames = labels
        self.chart.categoryAxis.labels.angle = 45

        for i in range(len(data)):
            self.chart.lines[i].strokeColor = color_list[i]

        self.legend.alignment = 'right'
        self.legend.x = self.width
        self.legend.y = self.height - self.height / 4
        self.legend.dx = 8
        self.legend.dy = 1
        self.legend.deltay = 10
        self.legend.dxTextSpace = 3
        self.legend.columnMaximum = 10
        self.legend.colorNamePairs = [(color_list[i], legends[i])
                                      for i in range(len(legends))]
Exemplo n.º 5
0
    def __init__(self, data=None, legend_data=None):
        Drawing.__init__(self, width=530, height=160)

        self._add(self,
                  MyChartFrame(x=0, y=0, width=530, height=160,
                               title='Volume'),
                  name='frame')

        # chart
        self._add(self, LinePlot(), name='chart')
        self.chart.y = 20
        self.chart.x = 34
        self.chart.width = 423
        self.chart.height = 110

        # line styles
        self.chart.lines.symbol = makeMarker('Circle', size=2)

        colors = map(toColor, get_n_random_colors(len(legend_data)))
        for (i, _) in enumerate(legend_data):
            self.chart.lines[i].strokeColor = colors[i]

        # x axis
        self.chart.xValueAxis = NormalDateXValueAxis()
        self.chart.xValueAxis.xLabelFormat = '{dd} {MMM}'
        self.chart.xValueAxis.loLLen = 8
        self.chart.xValueAxis.hiLLen = 5
        self.chart.xValueAxis.labels.fontName = 'Lato'
        self.chart.xValueAxis.labels.fontSize = 9

        # y axis
        self.chart.yValueAxis = YValueAxis()
        self.chart.yValueAxis.visibleGrid = 1
        self.chart.yValueAxis.visibleAxis = 0
        self.chart.yValueAxis.strokeWidth = 0.25
        self.chart.yValueAxis.labels.rightPadding = 5
        self.chart.yValueAxis.labels.fontName = 'Lato'
        self.chart.yValueAxis.labels.fontSize = 9
        self.chart.yValueAxis.rangeRound = 'both'
        self.chart.yValueAxis.tickLeft = 7.5
        self.chart.yValueAxis.minimumTickSpacing = 0.5
        self.chart.yValueAxis.maximumTicks = 8
        self.chart.yValueAxis.avoidBoundFrac = 0.1

        # legend
        self._add(self, LineLegend(), name='legend')
        self.legend.alignment = 'right'
        self.legend.y = 110
        self.legend.x = 462
        self.legend.dxTextSpace = 5
        self.legend.columnMaximum = 4
        self.legend.fontName = 'Lato'
        self.legend.fontSize = 9

        self.legend.colorNamePairs = zip(colors, legend_data)

        # Data...
        self.chart.data = data
Exemplo n.º 6
0
    def __init__(self):
        LineLegend.__init__(self)

        self.positionType = "null"
        self.backgroundRect = None
        self.adjustX = 0
        self.adjustY = 0
        self.fontName = DefaultFontName
        self.deltax = 10
        self.deltay = 0
        self.boxAnchor = 'w'
        self.columnMaximum = 1
        self.yGap = 0
        self.fontSize = 7
        self.alignment = 'right'
        self.dxTextSpace = 5

        self.bottom_gap = 40
        def sample3():
            "Make sample legend with line swatches."

            d = Drawing(200, 100)

            legend = LineLegend()
            legend.alignment = 'right'
            legend.x = 20
            legend.y = 90
            legend.deltax = 60
            legend.dxTextSpace = 10
            legend.columnMaximum = 4
            items = 'red green blue yellow pink black white'.split()
            items = [(getattr(colors, i), i) for i in items]
            legend.colorNamePairs = items
            d.add(legend, 'legend')

            return d
Exemplo n.º 8
0
def add_legend1(draw_obj, chart, data, doc):
    legend = LineLegend()
    legend.alignment = 'right'
    legend.x = doc.leftMargin
    legend.y = doc.bottomMargin - 30

    legend.colorNamePairs = Auto(obj=chart)
    draw_obj.add(legend)
Exemplo n.º 9
0
        def sample4a():
            '''Satish Darade failure''' 
            from reportlab.graphics.charts.legends import LegendSwatchCallout
            from reportlab.graphics import shapes
            class LSwatchCallout(LegendSwatchCallout):
                def __init__(self,texts,fontName,fontSize):
                    self._texts = texts
                    self._fontName = fontName
                    self._fontSize = fontSize

                def __call__(self,legend,g,thisx,y,i,colName,swatch):
                    g.add(shapes.String(swatch.x-2,y,self._texts[i],textAnchor='end',fontName=self._fontName,fontSize=self._fontSize))

            d = Drawing(200, 100)
            legend = LineLegend()
            d.add(legend, 'legend')
            items = 'red green blue yellow pink black white'
            sw_names = items.upper().split()
            items = items.split()
            legend.colorNamePairs = [(getattr(colors, i), i) for i in items]
            legend.x = 20
            legend.y = 90
            d.legend.swatchCallout = LSwatchCallout(sw_names,'Helvetica',12)
            return d
Exemplo n.º 10
0
        def sample3():
            "Make sample legend with line swatches."

            d = Drawing(200, 100)

            legend = LineLegend()
            legend.alignment = 'right'
            legend.x = 20
            legend.y = 90
            legend.deltax = 60
            legend.dxTextSpace = 10
            legend.columnMaximum = 4
            items = 'red green blue yellow pink black white'.split()
            items = [(getattr(colors, i), i) for i in items]
            legend.colorNamePairs = items
            d.add(legend, 'legend')

            return d
Exemplo n.º 11
0
    def render_graph(self, request_opts, graph_opts):
        def label_fmt(x):
            print "@@@", x
            return str(x)

        ld = len(graph_opts["data"])
        palette = [Color(*x) for x in get_float_pallete(ld)]
        w = graph_opts["width"]
        h = graph_opts["height"]
        drawing = Drawing(w, h)
        # Legend
        legend = LineLegend()
        legend.colorNamePairs = [
            (palette[i], graph_opts["data"][i].name)
            for i in range(ld)
        ]
        legend.boxAnchor = "sw"
        legend.columnMaximum = 2
        legend.alignment = "right"
        drawing.add(legend)
        lh = legend._calcHeight() + self.X_PADDING / 2
        # Plot
        lp = LinePlot()
        lfs = lp.xValueAxis.labels.fontSize
        lp.x = self.X_PADDING
        lp.y = self.Y_PADDING + lh + lfs
        lp.width = w - 2 * self.X_PADDING
        lp.height = h - self.Y_PADDING - lp.y
        lp.data = [
            [(t, v) for v, t in ts] for ts in graph_opts["data"]
        ]
        for i in range(ld):
            lp.lines[i].strokeColor = palette[i]
        drawing.add(lp)
        # Render
        cdata = drawing.asString(format="png")
        response = self.render_plain_text(
            cdata,
            mimetype="image/png"
        )
        if not request_opts["noCache"]:
            cache.set(request_opts["requestKey"], response,
                      request_opts["cacheTimeout"])
        return response
Exemplo n.º 12
0
        def sample3a():
            "Make sample legend with line swatches and dasharrays on the lines."
            d = Drawing(200, 100)
            legend = LineLegend()
            legend.alignment = 'right'
            legend.x = 20
            legend.y = 90
            legend.deltax = 60
            legend.dxTextSpace = 10
            legend.columnMaximum = 4
            items = 'red green blue yellow pink black white'.split()
            darrays = ([2,1], [2,5], [2,2,5,5], [1,2,3,4], [4,2,3,4], [1,2,3,4,5,6], [1])
            cnp = []
            for i in range(0, len(items)):
                l =  LineSwatch()
                l.strokeColor = getattr(colors, items[i])
                l.strokeDashArray = darrays[i]
                cnp.append((l, items[i]))
            legend.colorNamePairs = cnp
            d.add(legend, 'legend')

            return d
Exemplo n.º 13
0
    def make_legend(self, drawing, chart):
        if not self.legend_labels:
            return

        # Get legend labels
        labels = self.get_legend_labels()

        # Legend object
        legend = LineLegend()
        #legend.fontName = 'Times-Roman'
        #legend.fontSize = 12

        legend.colorNamePairs = zip(self.colors[:len(labels)], labels)
        legend.columnMaximum = len(legend.colorNamePairs)
        legend.deltay = 5
        legend.alignment = 'right'
        legend.x = drawing.width
        legend.y = drawing.height - (self.title and self.title.get('height', DEFAULT_TITLE_HEIGHT) or 0)

        drawing.add(legend)

        return legend
Exemplo n.º 14
0
    def __init__(self,
                 series_colors_cmyk,
                 box_width,
                 box_height,
                 chart_width,
                 chart_height,
                 width=550,
                 height=215,
                 *args,
                 **kw):
        Drawing.__init__(self, width, height, *args, **kw)
        Drawing.hAlign = 'CENTER'

        font_name = 'Helvetica'
        # self.width = 550
        # self.height = 240
        self.width = box_width
        self.height = box_height
        self._add(self, LinePlot(), name='chart', validate=None, desc=None)
        self._add(self, LineLegend(), name='legend', validate=None, desc=None)

        # self.chart.width = 490
        # self.chart.height = 150
        self.chart.width = chart_width
        self.chart.height = chart_height
        self.chart.y = 60
        self.chart.x = 45
        self.chart.strokeWidth = 1

        for color in series_colors_cmyk:
            index = series_colors_cmyk.index(color)
            self.chart.lines[index].strokeColor = PCMYKColor(color[0],
                                                             color[1],
                                                             color[2],
                                                             color[3],
                                                             alpha=color[4])
            self.chart.lines[index].symbol = makeMarker('FilledCircle')
            self.chart.lines[index].symbol.strokeColor = PCMYKColor(
                color[0], color[1], color[2], color[3], alpha=color[4])
            self.chart.lines[index].symbol.size = 5
        self.chart.lines.strokeWidth = 2

        self.legend.colorNamePairs = Auto(obj=self.chart)
        self.legend.x = 5
        self.legend.y = 30
        # set size of swatches
        self.legend.dx = 0
        self.legend.dy = 0
        self.legend.fontName = font_name
        self.legend.fontSize = 8
        self.legend.alignment = 'right'
        self.legend.columnMaximum = 2
        self.legend.dxTextSpace = 4
        self.legend.variColumn = 1
        self.legend.boxAnchor = 'nw'
        self.legend.deltay = 15
        self.legend.autoXPadding = 20

        self.background = Rect(0,
                               0,
                               self.width,
                               self.height,
                               strokeWidth=0,
                               fillColor=PCMYKColor(0, 0, 10, 0))
        self.background.strokeColor = black
        self.background.fillOpacity = 0.25
        self.background.strokeWidth = 0
        self.background.x = 0
        self.background.fillColor = PCMYKColor(16, 12, 13, 0, alpha=30)
Exemplo n.º 15
0
    def body():
        # Body

        size_y = 0.62
        data = [["Sold", "Cash", "Card", "Contingent", "Reserved", "Expected", "Unsold Reserv."]]
        for cat, value in report_result_dict.iteritems():
            size_y = size_y + 1.86
            """
            if cat == 'all':
                report_cat_name = 'All'
            else:
                report_cat_name = self.report_cat_list[event_id][cat]
            """
            if cat == "all":
                categorie_name = "All"
            else:
                categorie_name = cat_name[cat]

            p = Paragraph('<para alignment="center"><b>' + categorie_name + "</b></para>", styles["Normal"])
            data.append([p, "", "", "", "", "", ""])
            if cat == "all":
                data_for_pie = [
                    value["a_total_sold"],
                    value["a_sold_cash"],
                    value["a_sold_card"],
                    value["a_sold_conti"],
                    value["a_reserved"],
                    value["a_not_visited"],
                ]

            data.append(
                [
                    value["a_total_sold"],
                    value["a_sold_cash"],
                    value["a_sold_card"],
                    value["a_sold_conti"],
                    value["a_reserved"],
                    value["a_total_pre"],
                    value["a_not_visited"],
                ]
            )

            data.append(
                [
                    str(value["m_total_sold"]) + unichr(8364),
                    str(value["m_sold_cash"]) + unichr(8364),
                    str(value["m_sold_card"]) + unichr(8364),
                    "-",
                    str(value["m_reserved"]) + unichr(8364),
                    str(value["m_total_pre"]) + unichr(8364),
                    str(value["m_not_visited"]) + unichr(8364),
                ]
            )

        tstyle = [
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.grey),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("ALIGN", (0, 1), (-1, -1), "RIGHT"),
            (
                "COLBACKGROUNDS",
                (0, 0),
                (-1, -1),
                [
                    colors.lightpink,
                    colors.lightpink,
                    colors.lightpink,
                    colors.lightpink,
                    colors.lightyellow,
                    colors.lightgrey,
                    colors.lightyellow,
                ],
            ),
            ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.lightslategray, None, None]),
        ]

        t = Table(data)
        t.setStyle(TableStyle(tstyle))
        t.wrapOn(c, 19 * cm, 0 * cm)
        pos_y = 26.5 - size_y
        t.drawOn(c, 1 * cm, pos_y * cm)

        # Price Details
        # size_y = 0.62

        pdata = []
        for cat, value in report_result_dict.iteritems():
            size_y = size_y + 1.86

            if cat == "all":
                pass
            else:
                categorie_name = cat_name[cat]

                p = Paragraph('<para alignment="center"><b>' + categorie_name + "</b></para>", styles["Normal"])
                pdata.append([p])

                data_price_titles = []
                data_price_amount = []
                data_price_total = []
                for prow in p_result:
                    if cat == "cat_" + str(prow["cat_id"]):
                        data_price_titles.append(prow["name"])
                        try:
                            data_price_amount.append(str(value["a_prices"][str(prow["id"])]))
                        except KeyError:
                            data_price_amount.append("0")

                        try:
                            data_price_total.append(str(value["m_prices"][str(prow["id"])]) + unichr(8364))
                        except KeyError:
                            data_price_total.append("0" + unichr(8364))

                print data_price_titles
                pdata.append(data_price_titles)
                pdata.append(data_price_amount)
                pdata.append(data_price_total)

        tstyle = [
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.grey),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("ALIGN", (0, 1), (-1, -1), "RIGHT"),
            ("COLBACKGROUNDS", (0, 0), (-1, -1), [colors.lightgrey, colors.whitesmoke]),
            ("ROWBACKGROUNDS", (0, 0), (-1, -1), [colors.lightslategray, None, None, None]),
        ]

        t = Table(pdata)
        t.setStyle(TableStyle(tstyle))
        t.wrapOn(c, 19 * cm, 0 * cm)
        pos_y = 25 - size_y
        t.drawOn(c, 1 * cm, pos_y * cm)

        """
        #Pie Chart

        d = Drawing(500, 500)
        pc = Pie()
        pc.x = 65
        pc.y = 15
        pc.width = 200
        pc.height = 200
        pc.data = data_for_pie
        pc.labels = ['Sold','Cash','Card','Contingent','Reserved','Unsold Reserv.']
        pc.slices.strokeWidth=0.5
        pc.slices[0].popout = 10
        #pc.slices[0].strokeWidth = 2
        #pc.slices[0].strokeDashArray = [2,2]
        pc.slices[0].labelRadius = 1.3
        pc.slices[0].fontColor = colors.red
        pc.slices[0].fillColor = colors.lightpink
        pc.slices[1].fillColor = colors.lightpink
        pc.slices[2].fillColor = colors.lightpink
        pc.slices[3].fillColor = colors.lightpink
        pc.slices[4].fillColor = colors.lightyellow
        pc.slices[5].fillColor = colors.lightyellow
        d.add(pc)
        d.wrapOn(c, 5*cm, 5*cm)
        d.drawOn(c, 1*cm, 1*cm)
        """
        if event_date == "all":
            data = []
            sold = []
            reserved = []
            unsold_reserved = []
            sold_contingent = []

            for key, value in sorted(report_date_dict.iteritems(), key=lambda report_date_dict: report_date_dict[0]):
                date_day_dt = dt.datetime.strptime(key, "%Y-%m-%d")
                date_day = date_day_dt.strftime("%Y%m%d")

                sold.append((int(date_day), value["sold"]))

                reserved.append((int(date_day), value["reserved"]))

                unsold_reserved.append((int(date_day), value["unsold_reserved"]))

                sold_contingent.append((int(date_day), value["sold_contingent"]))

            data.append(sold)
            data.append(reserved)
            data.append(unsold_reserved)
            data.append(sold_contingent)

            print data

            # sample data
            _colors = (
                Color(0.90, 0, 0),
                Color(0.801961, 0.801961, 0),
                Color(0.380392, 0.380392, 0),
                Color(0.580392, 0, 0),
            )
            _catNames = "Sold", "Reserved", "Unsold Reserved", "Contingents"

            d = Drawing(400, 200)
            # adding the actual chart here.
            plot = GridLinePlot()
            plot.y = 50
            plot.x = 15
            plot.width = 525
            plot.height = 125
            plot.xValueAxis.xLabelFormat = "{ddd} {dd}. {mm}."
            plot.lineLabels.fontSize = 6
            plot.lineLabels.boxStrokeWidth = 0.5
            plot.lineLabels.visible = 1
            plot.lineLabels.boxAnchor = "c"
            plot.lineLabels.angle = 0
            plot.lineLabelNudge = 10
            plot.joinedLines = 1
            plot.lines.strokeWidth = 1.5
            plot.lines[0].strokeColor = _colors[0]
            plot.lines[1].strokeColor = _colors[1]
            plot.lines[2].strokeColor = _colors[2]
            plot.lines[3].strokeColor = _colors[3]
            # sample data
            plot.data = data
            """
            plot.data  = [[(20010630, 1000),
                           (20011231, 101),
                           (20020630, 100.05),
                           (20021231, 102),
                           (20030630, 103),
                           (20031230, 104),
                           (20040630, 99.200000000000003),
                           (20041231, 99.099999999999994)],

                          [(20010630, 100.8),
                           (20011231, 100.90000000000001),
                           (20020630, 100.2),
                           (20021231, 100.09999999999999),
                           (20030630, 100),
                           (20031230, 100.05),
                           (20040630, 99.900000000000006),
                           (20041231, 99.799999999999997)],

                          [(20010630, 99.700000000000003),
                           (20011231, 99.799999999999997),
                           (20020630, 100),
                           (20021231, 100.01000000000001),
                           (20030630, 95),
                           (20031230, 90),
                           (20040630, 85),
                           (20041231, 80)]]
            """
            # y axis
            plot.yValueAxis.tickRight = 0
            plot.yValueAxis.maximumTicks = 10
            # plot.yValueAxis.leftAxisPercent        = 0
            plot.yValueAxis.tickLeft = 5
            plot.yValueAxis.valueMax = None
            plot.yValueAxis.valueMin = None
            plot.yValueAxis.rangeRound = "both"
            plot.yValueAxis.requiredRange = 30
            plot.yValueAxis.valueSteps = None
            plot.yValueAxis.valueStep = None
            plot.yValueAxis.forceZero = 0
            plot.yValueAxis.labels.fontSize = 7
            plot.yValueAxis.labels.dy = 0
            plot.yValueAxis.avoidBoundFrac = 0.1
            # x axis
            plot.xValueAxis.labels.fontName = "Helvetica"
            plot.xValueAxis.labels.fontSize = 7
            plot.xValueAxis.valueSteps = None
            plot.xValueAxis.dailyFreq = 0
            plot.xValueAxis.gridStrokeWidth = 0.25
            plot.xValueAxis.labels.angle = 90
            plot.xValueAxis.maximumTicks = 20
            plot.xValueAxis.tickDown = 3
            plot.xValueAxis.dailyFreq = 0
            plot.xValueAxis.bottomAxisLabelSlack = 0
            plot.xValueAxis.minimumTickSpacing = 10
            plot.xValueAxis.visibleGrid = 0
            plot.xValueAxis.gridEnd = 0
            plot.xValueAxis.gridStart = 0
            plot.xValueAxis.labels.angle = 45
            plot.xValueAxis.labels.boxAnchor = "e"
            plot.xValueAxis.labels.dx = 0
            plot.xValueAxis.labels.dy = -5

            # adding legend
            legend = LineLegend()
            legend.boxAnchor = "sw"
            legend.x = 20
            legend.y = -2
            legend.columnMaximum = 1
            legend.yGap = 0
            legend.deltax = 50
            legend.deltay = 0
            legend.dx = 10
            legend.dy = 1.5
            legend.fontSize = 7
            legend.alignment = "right"
            legend.dxTextSpace = 5
            legend.colorNamePairs = [(_colors[i], _catNames[i]) for i in xrange(len(plot.data))]

            d.add(plot)
            d.add(legend)

            d.wrapOn(c, 18 * cm, 5 * cm)
            d.drawOn(c, 1 * cm, 1 * cm)

        c.showPage()
Exemplo n.º 16
0
    def drawLegend(self, x, y, Ltype, Color, String, line2F = False, startX = 0):
        if Ltype == 'Line':
            legend = LineLegend()
            legend.strokeWidth = 0.1
        elif Ltype == 'Rect':
            legend = Legend()
            legend.dx = 5
            legend.dy = 5
        else:
            return -1
        legend.alignment = 'right'
        legend.x = x
        legend.y = y
        legend.fontName = 'Helvetica'
        legend.fontSize = 7
        legend.dxTextSpace = 4
        legend.colorNamePairs = [(Color, String)]
        #We use private functions to calculate the width. Bad?
        maxWidth = legend._calculateMaxWidth(legend.colorNamePairs)
        maxWidth += legend.dx + legend.dxTextSpace + legend.autoXPadding
        #To fit more possible legends, we start writing legends at some points above 
        #max Y val, and we allow max of 2 (5 size) lines, when we reach end of line 1,
        #pass the moveToline2F (True) to drawLegends, so next time it calls drawLegend
        #it passes proper x, y values. 
        moveToline2F = False
        cantDrawF = False
        if (maxWidth + x) > self.width:
            if line2F != True:
                moveToline2F = True
                legend.y -= 7
                if startX != 0:
                    legend.x = startX
                else:
                    cantDrawF = True
            else:
                cantDrawF = True

        if cantDrawF:
                print("Legend list too long. %s doesn't fit in graph" % String)
                maxWidth = -1
        else:
            self.drawing.add(legend)
            
        return (maxWidth, moveToline2F)        
Exemplo n.º 17
0
def create_graph(graph_data): 
    color=[green,red,blue,yellow,black]
    color_index = 0
    line_chart = Drawing(400, 200)
    data_length=len(graph_data["data"])
    lc = HorizontalLineChart()
    lc.x = 50
    lc.y = 50
    lc.height = 125
    lc.width = 300
    lc.data = graph_data["data"]
    lc.fillColor=lightblue	
    lc.joinedLines = 1
    lc.categoryAxis.categoryNames = list(graph_data["label"][0])
    lc.categoryAxis.labels.boxAnchor ='n'
    lc.valueAxis.valueMin = utils.get_least_pt(graph_data["data"])
    lc.valueAxis.valueMax = utils.get_max_pt(graph_data["data"])
    lc.valueAxis.valueStep = (lc.valueAxis.valueMax - lc.valueAxis.valueMin)/10 if (lc.valueAxis.valueMax - lc.valueAxis.valueMin) > 40 else (lc.valueAxis.valueMax - lc.valueAxis.valueMin)/5
   
    for i in xrange(data_length):
        lc.lines[i].strokeWidth = 2
        lc.lines[i].strokeColor = color[i]
    
    line_chart.add(lc)
    line_leg = LineLegend() 
    line_leg.boxAnchor       = 'sw'
    line_leg.x               = 100
    line_leg.y               = -1
    
    line_leg.columnMaximum   = 1
    line_leg.yGap            = 0
    line_leg.deltax          = 50
    line_leg.deltay          = 0
    line_leg.dx              = 10
    line_leg.dy              = 1.5
    line_leg.fontSize        = 10
    line_leg.alignment       = 'right'
    line_leg.dxTextSpace     = 5
    line_leg.colorNamePairs  = [(color[i],graph_data["legend"][0][i]) for i in xrange(data_length)]
    line_chart.add(line_leg) 
    
    return line_chart
Exemplo n.º 18
0
def drawsystemdailyefficiency(can, resultsbuffer):
    can.setFont("Helvetica", 24)
    sec_title = "Chiller Plant System Daily Efficiency"
    can.drawString(25, 750, sec_title)

    desc_text = "The chiller plant system daily efficiency demonstrates the total efficiency including every" \
                " parts of the system across a series of days. The range can be by default (say, 2 days) or" \
                " specified by administrators."
    stylesheet = getSampleStyleSheet()
    paragraph = Paragraph(desc_text, stylesheet['Normal'])
    aW, aH = 500, 600
    w, h = paragraph.wrap(aW, aH)
    if w <= aW and h <= aH:
        paragraph.drawOn(can, 25, 700)

    # Draw the chart
    drawing = Drawing(600, 400)

    # font
    fontName = 'Helvetica'
    fontSize = 7

    # chart
    lp = LinePlot()
    lp.y = 16
    lp.x = 32
    lp.width = 400
    lp.height = 200

    # line styles
    lp.lines.strokeWidth = 0
    lp.lines.symbol = makeMarker('FilledSquare')

    # x axis
    lp.xValueAxis = NormalDateXValueAxis()
    lp.xValueAxis.labels.fontName = fontName
    lp.xValueAxis.labels.fontSize = fontSize - 1
    lp.xValueAxis.forceEndDate = 1
    lp.xValueAxis.forceFirstDate = 1
    lp.xValueAxis.labels.boxAnchor = 'autox'
    lp.xValueAxis.xLabelFormat = '{d}-{MMM}'
    lp.xValueAxis.maximumTicks = 5
    lp.xValueAxis.minimumTickSpacing = 0.5
    lp.xValueAxis.niceMonth = 0
    lp.xValueAxis.strokeWidth = 1
    lp.xValueAxis.loLLen = 5
    lp.xValueAxis.hiLLen = 5
    lp.xValueAxis.gridEnd = drawing.width
    lp.xValueAxis.gridStart = lp.x - 10

    # y axis
    # self.chart.yValueAxis = AdjYValueAxis()
    lp.yValueAxis.visibleGrid = 1
    lp.yValueAxis.visibleAxis = 0
    lp.yValueAxis.labels.fontName = fontName
    lp.yValueAxis.labels.fontSize = fontSize - 1
    lp.yValueAxis.labelTextFormat = '%0.2f%%'
    lp.yValueAxis.strokeWidth = 0.25
    lp.yValueAxis.visible = 1
    lp.yValueAxis.labels.rightPadding = 5

    # self.chart.yValueAxis.maximumTicks = 6
    lp.yValueAxis.rangeRound = 'both'
    lp.yValueAxis.tickLeft = 7.5
    lp.yValueAxis.minimumTickSpacing = 0.5
    lp.yValueAxis.maximumTicks = 8
    lp.yValueAxis.forceZero = 0
    lp.yValueAxis.avoidBoundFrac = 0.1

    # legend
    ll = LineLegend()
    ll.fontName = fontName
    ll.fontSize = fontSize
    ll.alignment = 'right'
    ll.dx = 5

    # sample data
    lp.data = [[(19010706, 3.3900000000000001), (19010806, 3.29),
                (19010906, 3.2999999999999998), (19011006, 3.29),
                (19011106, 3.3399999999999999), (19011206, 3.4100000000000001),
                (19020107, 3.3700000000000001), (19020207, 3.3700000000000001),
                (19020307, 3.3700000000000001), (19020407, 3.5),
                (19020507, 3.6200000000000001), (19020607, 3.46),
                (19020707, 3.3900000000000001)],
               [(19010706, 3.2000000000000002), (19010806, 3.1200000000000001),
                (19010906, 3.1400000000000001), (19011006, 3.1400000000000001),
                (19011106, 3.1699999999999999), (19011206, 3.23),
                (19020107, 3.1899999999999999), (19020207, 3.2000000000000002),
                (19020307, 3.1899999999999999), (19020407, 3.3100000000000001),
                (19020507, 3.4300000000000002), (19020607, 3.29),
                (19020707, 3.2200000000000002)]]

    lp.lines[0].strokeColor = PCMYKColor(0, 100, 100, 40, alpha=100)
    lp.lines[1].strokeColor = PCMYKColor(100, 0, 90, 50, alpha=100)
    lp.xValueAxis.strokeColor = PCMYKColor(100, 60, 0, 50, alpha=100)
    ll.colorNamePairs = [(PCMYKColor(0, 100, 100, 40,
                                     alpha=100), '01-Mar-2017'),
                         (PCMYKColor(100, 0, 90, 50,
                                     alpha=100), '02-Mar-2017')]
    lp.lines.symbol.x = 0
    lp.lines.symbol.strokeWidth = 0
    lp.lines.symbol.arrowBarbDx = 5
    lp.lines.symbol.strokeColor = PCMYKColor(0, 0, 0, 0, alpha=100)
    lp.lines.symbol.fillColor = None
    lp.lines.symbol.arrowHeight = 5
    ll.dxTextSpace = 7
    ll.boxAnchor = 'nw'
    ll.subCols.dx = 0
    ll.subCols.dy = -2
    ll.subCols.rpad = 0
    ll.columnMaximum = 1
    ll.deltax = 1
    ll.deltay = 0
    ll.dy = 5
    ll.y = 240
    ll.x = 300
    lp.lines.symbol.kind = 'FilledCross'
    lp.lines.symbol.size = 5
    lp.lines.symbol.angle = 45

    drawing.add(lp)
    drawing.add(ll)
    # drawing.title.text = "Jurong Point System Efficiency"
    # drawing.title.fondSize = 16
    drawing.drawOn(can, 100, 450)

    can.showPage()
Exemplo n.º 19
0
    def __init__(self, width=600, height=400, *args, **kw):
        apply(Drawing.__init__, (self, width, height) + args, kw)
        self.add(LinePlot(), name='chart')

        self.add(String(200, 180, ''), name='title')

        #set any shapes, fonts, colors you want here.  We'll just
        #set a title font and place the chart within the drawing.
        #pick colors for all the lines, do as many as you need
        self.chart.x = 20
        self.chart.y = 30
        self.chart.width = self.width - 100
        self.chart.height = self.height - 75
        self.chart.lines[0].strokeColor = colors.blue
        self.chart.lines[1].strokeColor = colors.red

        self.chart.fillColor = colors.white
        self.title.fontName = 'Times-Roman'
        self.title.fontSize = 18
        #self.chart.data = [((0, 50), (100,100), (200,200), (250,210), (300,300), (400,500))]
        self.chart.xValueAxis.labels.fontSize = 12
        self.chart.xValueAxis.forceZero = 0
        self.chart.xValueAxis.gridEnd = self.width - self.width * 0.60
        self.chart.yValueAxis.gridEnd = self.height - self.height * 0.2
        self.chart.xValueAxis.tickDown = 3
        self.chart.xValueAxis.visibleGrid = 1
        self.chart.yValueAxis.visibleGrid = 1
        self.chart.yValueAxis.tickLeft = 3
        self.chart.yValueAxis.labels.fontName = 'Times-Roman'
        self.chart.yValueAxis.labels.fontSize = 12
        self.title.x = self.width / 2
        self.title.y = 0
        self.title.textAnchor = 'middle'
        self.add(LineLegend(), name='Legend')
        self.Legend.fontName = 'Times-Roman'
        self.Legend.fontSize = 12
        self.Legend.x = self.width - 10
        self.Legend.y = 70
        self.Legend.dxTextSpace = 5
        self.Legend.dy = 5
        self.Legend.dx = 5
        self.Legend.deltay = 5
        self.Legend.alignment = 'right'
        self.Legend.colorNamePairs = [(colors.blue, 'Tiempo Estimado')]
        self.add(Label(), name='XLabel')
        self.XLabel.fontName = 'Times-Roman'
        self.XLabel.fontSize = 12
        self.XLabel.x = 100
        self.XLabel.y = 5
        self.XLabel.textAnchor = 'middle'
        self.XLabel.height = 20
        self.XLabel._text = "que tal"
        self.add(Label(), name='YLabel')
        self.YLabel.fontName = 'Times-Roman'
        self.YLabel.fontSize = 12
        self.YLabel.x = -10
        self.YLabel.y = 100
        self.YLabel.angle = 90
        self.YLabel.textAnchor = 'middle'
        self.YLabel._text = "Hola"
        self.chart.yValueAxis.forceZero = 1
        self.chart.xValueAxis.forceZero = 1
        self.chart.lines[0].symbol = makeMarker('FilledCircle')
        self.chart.lines[1].symbol = makeMarker('Circle')
    def __init__(self,
                 data,
                 font,
                 font_bold,
                 title,
                 x_axis_params,
                 y_axis_params,
                 series_names,
                 series_colors_cmyk,
                 box_width,
                 box_height,
                 chart_width,
                 chart_height,
                 width=550,
                 height=215,
                 *args,
                 **kw):
        logger.debug("Generating line chart with data:\n{0}\n".format(
            json.dumps(data, indent=2)))

        Drawing.__init__(self, width, height, *args, **kw)
        Drawing.hAlign = "CENTER"

        # self.width = 550
        # self.height = 240
        self.width = box_width
        self.height = box_height
        self._add(self, LinePlot(), name="chart", validate=None, desc=None)
        self._add(self, LineLegend(), name="legend", validate=None, desc=None)

        # self.chart.width = 490
        # self.chart.height = 150
        self.chart.width = chart_width
        self.chart.height = chart_height
        self.chart.y = 60
        self.chart.x = 45
        self.chart.strokeWidth = 1

        for color in series_colors_cmyk:
            index = series_colors_cmyk.index(color)
            self.chart.lines[index].strokeColor = PCMYKColor(color[0],
                                                             color[1],
                                                             color[2],
                                                             color[3],
                                                             alpha=color[4])
            self.chart.lines[index].symbol = makeMarker("FilledCircle")
            self.chart.lines[index].symbol.strokeColor = PCMYKColor(
                color[0], color[1], color[2], color[3], alpha=color[4])
            self.chart.lines[index].symbol.size = 5
        self.chart.lines.strokeWidth = 2

        self.legend.colorNamePairs = Auto(obj=self.chart)
        self.legend.x = 10 * (
            len(series_names) // 5
        )  # adjust how far to the left/right the legend labels are
        self.legend.y = 12 * (len(series_names) // 5
                              )  # adjust how far up/down the legend labels are
        # set size of swatches
        self.legend.dx = 0
        self.legend.dy = -5
        self.legend.fontName = font
        self.legend.fontSize = 100 // len(series_names)
        self.legend.alignment = "right"
        self.legend.columnMaximum = (
            len(series_names) //
            5) + 1  # adjust number of ROWS allowed in legend
        self.legend.dxTextSpace = 4
        self.legend.variColumn = 1
        self.legend.boxAnchor = "nw"
        self.legend.deltay = 10  # adjust the space between legend rows
        self.legend.autoXPadding = 15 * (
            (len(series_names) // 5) + 1
        )  # adjust the space between legend columns

        self.background = Rect(0,
                               0,
                               self.width,
                               self.height,
                               strokeWidth=0,
                               fillColor=PCMYKColor(0, 0, 10, 0))
        self.background.strokeColor = black
        self.background.fillOpacity = 0.25
        self.background.strokeWidth = 0
        self.background.x = 0
        self.background.fillColor = PCMYKColor(16, 12, 13, 0, alpha=30)

        self.make_title(title, font=font_bold)
        self.make_data(data)
        self.make_x_axis(*x_axis_params, font=font)
        self.make_y_axis(*y_axis_params, font=font)
        self.make_series_labels(series_names)
Exemplo n.º 21
0
 def __init__(self, width=258, height=150, *args, **kw):
     Drawing.__init__(self, width, height, *args, **kw)
     # font
     fontName = 'Helvetica'
     fontSize = 7
     # chart
     self._add(self, LinePlot(), name='chart', validate=None, desc=None)
     self.chart.y = 16
     self.chart.x = 32
     self.chart.width = 212
     self.chart.height = 90
     # line styles
     self.chart.lines.strokeWidth = 0
     self.chart.lines.symbol = makeMarker('FilledSquare')
     # x axis
     self.chart.xValueAxis = NormalDateXValueAxis()
     self.chart.xValueAxis.labels.fontName = fontName
     self.chart.xValueAxis.labels.fontSize = fontSize - 1
     self.chart.xValueAxis.forceEndDate = 1
     self.chart.xValueAxis.forceFirstDate = 1
     self.chart.xValueAxis.labels.boxAnchor = 'autox'
     self.chart.xValueAxis.xLabelFormat = '{d}-{MMM}'
     self.chart.xValueAxis.maximumTicks = 5
     self.chart.xValueAxis.minimumTickSpacing = 0.5
     self.chart.xValueAxis.niceMonth = 0
     self.chart.xValueAxis.strokeWidth = 1
     self.chart.xValueAxis.loLLen = 5
     self.chart.xValueAxis.hiLLen = 5
     self.chart.xValueAxis.gridEnd = self.width
     self.chart.xValueAxis.gridStart = self.chart.x - 10
     # y axis
     #self.chart.yValueAxis = AdjYValueAxis()
     self.chart.yValueAxis.visibleGrid = 1
     self.chart.yValueAxis.visibleAxis = 0
     self.chart.yValueAxis.labels.fontName = fontName
     self.chart.yValueAxis.labels.fontSize = fontSize - 1
     self.chart.yValueAxis.labelTextFormat = '%0.2f%%'
     self.chart.yValueAxis.strokeWidth = 0.25
     self.chart.yValueAxis.visible = 1
     self.chart.yValueAxis.labels.rightPadding = 5
     #self.chart.yValueAxis.maximumTicks          = 6
     self.chart.yValueAxis.rangeRound = 'both'
     self.chart.yValueAxis.tickLeft = 7.5
     self.chart.yValueAxis.minimumTickSpacing = 0.5
     self.chart.yValueAxis.maximumTicks = 8
     self.chart.yValueAxis.forceZero = 0
     self.chart.yValueAxis.avoidBoundFrac = 0.1
     # legend
     self._add(self, LineLegend(), name='legend', validate=None, desc=None)
     self.legend.fontName = fontName
     self.legend.fontSize = fontSize
     self.legend.alignment = 'right'
     self.legend.dx = 5
     # sample data
     self.chart.data = [[(19010706, 3.3900000000000001), (19010806, 3.29),
                         (19010906, 3.2999999999999998), (19011006, 3.29),
                         (19011106, 3.3399999999999999),
                         (19011206, 3.4100000000000001),
                         (19020107, 3.3700000000000001),
                         (19020207, 3.3700000000000001),
                         (19020307, 3.3700000000000001), (19020407, 3.5),
                         (19020507, 3.6200000000000001), (19020607, 3.46),
                         (19020707, 3.3900000000000001)],
                        [(19010706, 3.2000000000000002),
                         (19010806, 3.1200000000000001),
                         (19010906, 3.1400000000000001),
                         (19011006, 3.1400000000000001),
                         (19011106, 3.1699999999999999), (19011206, 3.23),
                         (19020107, 3.1899999999999999),
                         (19020207, 3.2000000000000002),
                         (19020307, 3.1899999999999999),
                         (19020407, 3.3100000000000001),
                         (19020507, 3.4300000000000002), (19020607, 3.29),
                         (19020707, 3.2200000000000002)]]
     self.chart.lines[0].strokeColor = PCMYKColor(0,
                                                  100,
                                                  100,
                                                  40,
                                                  alpha=100)
     self.chart.lines[1].strokeColor = PCMYKColor(100, 0, 90, 50, alpha=100)
     self.chart.xValueAxis.strokeColor = PCMYKColor(100,
                                                    60,
                                                    0,
                                                    50,
                                                    alpha=100)
     self.legend.colorNamePairs = [(PCMYKColor(0, 100, 100, 40,
                                               alpha=100), 'Bovis Homes'),
                                   (PCMYKColor(100, 0, 90, 50,
                                               alpha=100), 'HSBC Holdings')]
     self.chart.lines.symbol.x = 0
     self.chart.lines.symbol.strokeWidth = 0
     self.chart.lines.symbol.arrowBarbDx = 5
     self.chart.lines.symbol.strokeColor = PCMYKColor(0, 0, 0, 0, alpha=100)
     self.chart.lines.symbol.fillColor = None
     self.chart.lines.symbol.arrowHeight = 5
     self.legend.dxTextSpace = 7
     self.legend.boxAnchor = 'nw'
     self.legend.subCols.dx = 0
     self.legend.subCols.dy = -2
     self.legend.subCols.rpad = 0
     self.legend.columnMaximum = 1
     self.legend.deltax = 1
     self.legend.deltay = 0
     self.legend.dy = 5
     self.legend.y = 135
     self.legend.x = 120
     self.chart.lines.symbol.kind = 'FilledCross'
     self.chart.lines.symbol.size = 5
     self.chart.lines.symbol.angle = 45
Exemplo n.º 22
0
def create_barchart(barchart_data):
    color=[green,red,blue,yellow,black]
    data_length=len(barchart_data["data"])
    bar_chart = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = barchart_data["data"]
    bc.fillColor=lightblue
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 50
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = list(barchart_data["label"][0])
    for i in xrange(data_length):
        bc.bars[i].fillColor = color[i]
    bar_chart.add(bc)


    ###legend#### 
    bar_leg = LineLegend()
    bar_leg.boxAnchor       = 'sw'
    bar_leg.x               = 100
    bar_leg.y               = -1

    bar_leg.columnMaximum   = 1
    bar_leg.yGap            = 0
    bar_leg.deltax          = 50
    bar_leg.deltay          = 0
    bar_leg.dx              = 10
    bar_leg.dy              = 1.5
    bar_leg.fontSize        = 10
    bar_leg.alignment       = 'right'
    bar_leg.dxTextSpace     = 5
    bar_leg.colorNamePairs  = [(color[i],barchart_data["legend"][0][i]) for i in xrange(data_length)]
    bar_chart.add(bar_leg) 
    return bar_chart