def autoLegender(i, chart, styleObj, sym="symbol"):
    if sym:
        setattr(styleObj[0], sym, makeMarker("Diamond", size=6))
        setattr(styleObj[1], sym, makeMarker("Square"))
    width = 300
    height = 150
    legend = Legend()
    legend.x = width - 5
    legend.y = 5
    legend.dx = 20
    legend.dy = 5
    legend.deltay = 0
    legend.boxAnchor = "se"
    if i == "col auto":
        legend.colorNamePairs[0] = (Auto(chart=chart), "auto chart=self.chart")
        legend.colorNamePairs[1] = (Auto(obj=chart, index=1), "auto  chart=self.chart index=1")
    elif i == "full auto":
        legend.colorNamePairs = Auto(chart=chart)
    elif i == "swatch set":
        legend.swatchMarker = makeMarker("Circle")
        legend.swatchMarker.size = 10
    elif i == "swatch auto":
        legend.swatchMarker = Auto(chart=chart)
    d = Drawing(width, height)
    d.background = Rect(0, 0, width, height, strokeWidth=1, strokeColor=colors.red, fillColor=None)
    m = makeMarker("Cross")
    m.x = width - 5
    m.y = 5
    m.fillColor = colors.red
    m.strokeColor = colors.yellow
    d.add(chart)
    d.add(legend)
    d.add(m)
    return d
Пример #2
0
def sample1c():
    "A line plot with non-equidistant points in x-axis."

    drawing = Drawing(400, 200)

    data = [
            ((1,1), (2,2), (2.5,1), (3,3), (4,5)),
            ((1,2), (2,3), (2.5,2), (3.5,5), (4,6))
        ]

    lp = LinePlot()

    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    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)

    return drawing
Пример #3
0
    def demo(self):
        """Shows basic use of a line chart."""

        drawing = Drawing(400, 200)

        data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))]

        lp = LinePlot()

        lp.x = 50
        lp.y = 50
        lp.height = 125
        lp.width = 300
        lp.data = data
        lp.joinedLines = 1
        lp.lineLabelFormat = "%2.0f"
        lp.strokeColor = colors.black

        lp.lines[0].strokeColor = colors.red
        lp.lines[0].symbol = makeMarker("FilledCircle")
        lp.lines[1].strokeColor = colors.blue
        lp.lines[1].symbol = makeMarker("FilledDiamond")

        lp.xValueAxis.valueMin = 0
        lp.xValueAxis.valueMax = 5
        lp.xValueAxis.valueStep = 1

        lp.yValueAxis.valueMin = 0
        lp.yValueAxis.valueMax = 7
        lp.yValueAxis.valueStep = 1

        drawing.add(lp)

        return drawing
Пример #4
0
def autoLegender(i,chart,styleObj,sym='symbol'):
    if sym:
        setattr(styleObj[0],sym, makeMarker('Diamond',size=6))
        setattr(styleObj[1],sym,makeMarker('Square'))
    width = 300
    height = 150
    legend = Legend()
    legend.x = width-5
    legend.y = 5
    legend.dx = 20
    legend.dy = 5
    legend.deltay = 0
    legend.boxAnchor = 'se'
    if i=='col auto':
        legend.colorNamePairs[0]=(Auto(chart=chart),'auto chart=self.chart')
        legend.colorNamePairs[1]=(Auto(obj=chart,index=1),'auto  chart=self.chart index=1')
    elif i=='full auto':
        legend.colorNamePairs=Auto(chart=chart)
    elif i=='swatch set':
        legend.swatchMarker=makeMarker('Circle')
        legend.swatchMarker.size = 10
    elif i=='swatch auto':
        legend.swatchMarker=Auto(chart=chart)
    d = Drawing(width,height)
    d.background = Rect(0,0,width,height,strokeWidth=1,strokeColor=colors.red,fillColor=None)
    m = makeMarker('Cross')
    m.x = width-5
    m.y = 5
    m.fillColor = colors.red
    m.strokeColor = colors.yellow
    d.add(chart)
    d.add(legend)
    d.add(m)
    return d
Пример #5
0
    def _render(self, drawing):
        if not self._labels:
            return

        gap = 5
        lc1 = linecharts.HorizontalLineChart()
        lc1.data = [self._data[0]]
        lc1.lines.symbol = markers.makeMarker('FilledCircle')
        lc1.categoryAxis.categoryNames = self._labels
        lc1.lineLabelFormat = '%2.0f'

        legend = None
        legend_height = 0
        if self.kw.get('legendlabels', False):
            legend_height = 40
            colors_list = []
            for i in xrange(len(self._data)):
                colors_list.append(lc1.lines[i].strokeColor)

            legend = legends.LineLegend()
            legend.alignment = 'right'
            legend.x = 4 * gap
            legend.y = drawing.height - lc1.y - gap
            legend.deltay = 60
            legend.dxTextSpace = 5
            legend.columnMaximum = 1
            legend.colorNamePairs = zip(colors_list,
                                        self.kw.get('legendlabels'))

        lc1.x = 20
        lc1.y = 20
        lc1.height = self.height - lc1.y - legend_height
        lc1.width = self.width - 1.5 * lc1.x
        lc1.lineLabels.dx = -7
        lc1.lineLabels.fillColor = colors.red

        lc2 = linecharts.HorizontalLineChart()
        lc2.data = [self._data[1]]
        lc2.lines.symbol = markers.makeMarker('FilledCircle')
        lc2.categoryAxis.categoryNames = self._labels
        lc2.lineLabelFormat = '%2.0f'
        lc2.lineLabels.dx = 7
        lc2.lineLabels.fillColor = colors.green
        lc2.valueAxis.strokeColor = colors.green
        # lc2.valueAxis
        lc2.categoryAxis.visible = False

        lc2.x = 20
        lc2.y = 20
        lc2.height = self.height - lc2.y - legend_height
        lc2.width = self.width - 1.5 * lc1.x
        lc2.valueAxis.joinAxisMode = 'right'
        lc2.lines[0].strokeColor = colors.green

        drawing.add(lc1)
        drawing.add(lc2)
        if legend:
            drawing.add(legend, 'legend')
Пример #6
0
def sample1a():
    drawing = Drawing(400, 200)

    data = [
            (13, 5, 20, 22, 37, 45, 19, 4),
            (5, 20, 46, 38, 23, 21, 6, 14)
            ]

    lc = SampleHorizontalLineChart()

    lc.x = 50
    lc.y = 50
    lc.height = 125
    lc.width = 300
    lc.data = data
    lc.joinedLines = 1
    lc.strokeColor = colors.white
    lc.fillColor = colors.HexColor(0xCCCCCC)
    lc.lines.symbol = makeMarker('FilledDiamond')
    lc.lineLabelFormat = '%2.0f'

    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

    drawing.add(lc)

    return drawing
Пример #7
0
 def line_plot(O, xy_max, data, label_font_size):
   if (reportlab is None): return
   from reportlab.graphics.charts.lineplots import LinePlot
   from reportlab.graphics.widgets.markers import makeMarker
   from reportlab.lib import colors
   lp = LinePlot()
   lp.x = 40
   lp.y = 40
   lp.height = 120
   lp.width = 120
   lp.data = [[(0,0),(xy_max,xy_max)], data]
   lp.lines[0].strokeColor = colors.Color(*[0.8]*3)
   lp.lines[0].strokeWidth = 0.5
   lp.lines[1].strokeColor = colors.white
   lp.lines[1].strokeWidth = 0
   lp.lines[1].symbol = makeMarker("Circle")
   lp.lines[1].symbol.strokeWidth = 0.5
   lp.joinedLines = 1
   lp.strokeColor = colors.Color(*[0.8]*3)
   lp.strokeWidth = 1
   lp.xValueAxis.valueMin = 0
   lp.xValueAxis.valueMax = xy_max
   lp.xValueAxis.valueSteps = range(xy_max+1)
   lp.xValueAxis.strokeWidth = 1
   lp.xValueAxis.tickDown = 3
   lp.xValueAxis.labels.fontSize = label_font_size
   lp.yValueAxis.valueMin = 0
   lp.yValueAxis.valueMax = xy_max
   lp.yValueAxis.valueSteps = range(xy_max+1)
   lp.yValueAxis.strokeWidth = 1
   lp.yValueAxis.tickLeft = 3
   lp.yValueAxis.labels.fontSize = label_font_size
   return lp
Пример #8
0
def sample3():
    drawing = Drawing(400, 200)

    data = [
            (13, 5, 20, 22, 37, 45, 19, 4),
            (5, 20, 46, 38, 23, 21, 6, 14)
            ]

    lc = HorizontalLineChart()

    lc.x = 50
    lc.y = 50
    lc.height = 125
    lc.width = 300
    lc.data = data
    lc.joinedLines = 1
    lc.lineLabelFormat = '%2.0f'
    lc.strokeColor = colors.black

    lc.lines[0].symbol = makeMarker('Smiley')
    lc.lines[1].symbol = NoEntry
    lc.lines[0].strokeWidth = 2
    lc.lines[1].strokeWidth = 4

    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

    drawing.add(lc)

    return drawing
Пример #9
0
def sample1a():
    "A line plot with non-equidistant points in x-axis."

    drawing = Drawing(400, 200)

    data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))]

    lp = LinePlot()

    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = data
    lp.joinedLines = 1
    lp.strokeColor = colors.black

    lp.lines.symbol = makeMarker("UK_Flag")

    lp.lines[0].strokeWidth = 2
    lp.lines[1].strokeWidth = 4

    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 5
    lp.xValueAxis.valueStep = 1

    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 7
    lp.yValueAxis.valueStep = 1

    drawing.add(lp)

    return drawing
Пример #10
0
def sample2():
    "A line plot with non-equidistant points in x-axis."

    drawing = Drawing(400, 200)

    data = [
        (
            ("25/11/1991", 1),
            ("30/11/1991", 1.000933333),
            ("31/12/1991", 1.0062),
            ("31/01/1992", 1.0112),
            ("29/02/1992", 1.0158),
            ("31/03/1992", 1.020733333),
            ("30/04/1992", 1.026133333),
            ("31/05/1992", 1.030266667),
            ("30/06/1992", 1.034466667),
            ("31/07/1992", 1.038733333),
            ("31/08/1992", 1.0422),
            ("30/09/1992", 1.045533333),
            ("31/10/1992", 1.049866667),
            ("30/11/1992", 1.054733333),
            ("31/12/1992", 1.061),
        )
    ]

    data[0] = preprocessData(data[0])

    lp = LinePlot()

    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = data
    lp.joinedLines = 1
    lp.lines.symbol = makeMarker("FilledDiamond")
    lp.strokeColor = colors.black

    start = mktime(mkTimeTuple("25/11/1991"))
    t0 = mktime(mkTimeTuple("30/11/1991"))
    t1 = mktime(mkTimeTuple("31/12/1991"))
    t2 = mktime(mkTimeTuple("31/03/1992"))
    t3 = mktime(mkTimeTuple("30/06/1992"))
    t4 = mktime(mkTimeTuple("30/09/1992"))
    end = mktime(mkTimeTuple("31/12/1992"))
    lp.xValueAxis.valueMin = start
    lp.xValueAxis.valueMax = end
    lp.xValueAxis.valueSteps = [start, t0, t1, t2, t3, t4, end]
    lp.xValueAxis.labelTextFormat = seconds2str
    lp.xValueAxis.labels[1].dy = -20
    lp.xValueAxis.labels[2].dy = -35

    lp.yValueAxis.labelTextFormat = "%4.2f"
    lp.yValueAxis.valueMin = 100
    lp.yValueAxis.valueMax = 110
    lp.yValueAxis.valueStep = 2

    drawing.add(lp)

    return drawing
Пример #11
0
def sample2():
    "Make a spider chart with markers, but no fill"
    d = Drawing(400, 400)
    sp = SpiderChart()
    sp.x = 50
    sp.y = 50
    sp.width = 300
    sp.height = 300
    sp.data = [[10,12,14,16,14,12], [6,8,10,12,9,15],[7,8,17,4,12,8]]
    sp.labels = ['U','V','W','X','Y','Z']
    sp.strands.strokeWidth = 1
    sp.strands[0].fillColor = colors.pink
    sp.strands[1].fillColor = colors.lightblue
    sp.strands[2].fillColor = colors.palegreen
    sp.strands[0].strokeColor = colors.red
    sp.strands[1].strokeColor = colors.blue
    sp.strands[2].strokeColor = colors.green
    sp.strands.symbol = "FilledDiamond"
    sp.strands[1].symbol = makeMarker("Circle")
    sp.strands[1].symbol.strokeWidth = 0.5
    sp.strands[1].symbol.fillColor = colors.yellow
    sp.strands.symbolSize = 6
    sp.strandLabels[0,3]._text = 'special'
    sp.strandLabels[0,1]._text = 'one'
    sp.strandLabels[0,0]._text = 'zero'
    sp.strandLabels[1,0]._text = 'Earth'
    sp.strandLabels[2,2]._text = 'Mars'
    sp.strandLabels.format = 'values'
    sp.strandLabels.dR = -5
    d.add(sp)
    return d
Пример #12
0
def sample2():
    drawing = Drawing(400, 200)

    data = [(13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14)]

    lc = HorizontalLineChart()

    lc.x = 50
    lc.y = 50
    lc.height = 125
    lc.width = 300
    lc.data = data
    lc.joinedLines = 1
    lc.lines.symbol = makeMarker("Smiley")
    lc.lineLabelFormat = "%2.0f"
    lc.strokeColor = colors.black
    lc.fillColor = colors.lightblue

    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

    drawing.add(lc)

    return drawing
Пример #13
0
def line_plot(data, elements):
    drawing = Drawing(0, 400)  # for indices
    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)
Пример #14
0
    def __init__(self, chart, data_dict, width=600, height=450,
                 colorscheme='color'):
        """ Initialize the basic graphing class.
            Set the chart, data, width, height and color scheme.
        """
        self._data_dict = data_dict
        Drawing.__init__(self, width, height)
        self.add(chart, name='_linechart')
        self._linechart.width = 900
        self._linechart.height = 240
        self._linechart.x = 50
        self._linechart.y = 80

        self._linechart.joinedLines = 1
        self._linechart.categoryAxis.categoryNames = self.getCategories()
        self._linechart.categoryAxis.labels.boxAnchor = 'n'
        self._linechart.valueAxis.valueMin = 0
        self._linechart.valueAxis.valueMax = self.getHighestScore()
        self._linechart.valueAxis.valueStep = 1
        self._linechart.lines[0].strokeWidth = 2
        self._linechart.lines[1].strokeWidth = 1.5
        self._linechart.lines[0].strokeDashArray=3,4
        self._linechart.lines[0].strokeColor = colors.green
        self._linechart.lines[1].strokeColor = colors.red
        self._linechart.lines[1].symbol = makeMarker('Cross')
        self._linechart.lines[0].symbol = makeMarker('Cross')

        # calculate a sane y-axis interval
        valuestep = self.getHighestScore() / 10
        if valuestep <= 1:
            self._linechart.valueAxis.valueStep = 1
        else:
            self._linechart.valueAxis.valueStep = valuestep

        self.setTitle()
        self._linechart.data = self.getChartData()
 def line_chart_draw(self, values, days):
     nr_days = len(days)
     min_temp = min(min(values[0]), min(values[1]))
     d = Drawing(0, 170)
     # draw line chart
     chart = SampleHorizontalLineChart()
     # set width and height
     chart.width = 350
     chart.height = 135
     # set data values
     chart.data = values
     # use(True) or not(False) line between points
     chart.joinedLines = True
     # set font desired
     chart.lineLabels.fontName = 'FreeSans'
     # set color for the plot area border and interior area
     chart.strokeColor = colors.white
     chart.fillColor = colors.lightblue
     # set lines color and width
     chart.lines[0].strokeColor = colors.red
     chart.lines[0].strokeWidth = 2
     chart.lines[1].strokeColor = colors.blue
     chart.lines[1].strokeWidth = 2
     # set symbol for points
     chart.lines.symbol = makeMarker('Square')
     # set format for points from chart
     chart.lineLabelFormat = '%2.0f'
     # for negative axes intersect should be under zero
     chart.categoryAxis.joinAxisMode = 'bottom'
     # set font used for axes
     chart.categoryAxis.labels.fontName = 'FreeSans'
     if nr_days > 7:
         chart.categoryAxis.labels.angle = 45
         chart.categoryAxis.labels.boxAnchor = 'e'
     chart.categoryAxis.categoryNames = days
     # change y axe format
     chart.valueAxis.labelTextFormat = '%2.0f °C'
     chart.valueAxis.valueStep = 10
     if min_temp > 0:
         chart.valueAxis.valueMin = 0
     llabels = ['Max temp', 'Min temp']
     d.add(self.title_draw(250, 180, _('Temperatures statistics')))
     d.add(chart)
     d.add(self.legend_draw(llabels, chart, x=400, y=150, type='line'))
     return d
Пример #16
0
    def demo(self):
        """Shows basic use of a line chart."""

        drawing = Drawing(200, 100)

        data = [(13, 5, 20, 22, 37, 45, 19, 4), (14, 10, 21, 28, 38, 46, 25, 5)]

        lc = HorizontalLineChart()

        lc.x = 20
        lc.y = 10
        lc.height = 85
        lc.width = 170
        lc.data = data
        lc.lines.symbol = makeMarker("Circle")

        drawing.add(lc)

        return drawing
Пример #17
0
    def _render(self, drawing):
        if not self._labels:
            return

        gap = 5
        lc = linecharts.HorizontalLineChart()
        lc.data = self._data
        lc.lines.symbol = markers.makeMarker('FilledCircle')
        lc.categoryAxis.categoryNames = self._labels
        lc.lineLabelFormat = '%2.0f'

        legend = None
        legend_height = 0
        if self.kw.get('legendlabels', False):
            legend_height = 40
            colors_list = []
            for i in xrange(len(self._data)):
                colors_list.append(lc.lines[i].strokeColor)

            legend = legends.LineLegend()
            legend.alignment = 'right'
            legend.x = 4 * gap
            legend.y = drawing.height - lc.y - gap
            legend.deltay = 60
            legend.dxTextSpace = 5
            legend.columnMaximum = 1
            legend.colorNamePairs = zip(colors_list,
                                        self.kw.get('legendlabels'))

        lc.x = 20
        lc.y = 20
        lc.height = self.height - lc.y - legend_height
        lc.width = self.width - 1.5 * lc.x

        drawing.add(lc)
        if legend:
            drawing.add(legend, 'legend')
Пример #18
0
    def test_23_linePlotCharts(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.lineplots import LinePlot
        from reportlab.graphics.widgets.markers import makeMarker

        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 = [
            [(1,1), (2,2), (2.5,1), (3,3), (4,5)],
        ]
        lp = LinePlot()
        lp.x = 5
        lp.y = 5
        lp.height = 190
        lp.width = 390
        lp.data = data
        lp.joinedLines = 1
        lp.lines[0].symbol = makeMarker('FilledCircle')
        d.add(lp)

        elements.append(d)

        doc.build(elements)
Пример #19
0
def sample1a():
    "A line plot with non-equidistant points in x-axis."

    drawing = Drawing(400, 200)

    data = [
            ((1,1), (2,2), (2.5,1), (3,3), (4,5)),
            ((1,2), (2,3), (2.5,2), (3.5,5), (4,6))
        ]

    lp = LinePlot()

    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = data
    lp.joinedLines = 1
    lp.strokeColor = colors.black

    lp.lines.symbol = makeMarker('UK_Flag')

    lp.lines[0].strokeWidth = 2
    lp.lines[1].strokeWidth = 4

    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 5
    lp.xValueAxis.valueStep = 1

    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 7
    lp.yValueAxis.valueStep = 1

    drawing.add(lp)

    return drawing
Пример #20
0
def getTempPlot():
    drawing = Drawing(400, 200)
    temps = [getTemps()]
    bc = LinePlot()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = temps
    bc.lines[0].symbol = makeMarker('Circle')

    #labels
    yilabel = Label()
    yilabel.setText("Temperatura (°C)")
    yilabel.angle = 90
    yilabel.setOrigin(20, 120)
    xlabel = Label()
    xlabel.setText("Días")
    xlabel.setOrigin(200, 20)

    #labelT = Label()
    #labelT.setText("Temperatura")
    #labelT.setOrigin(210,185)

    #labelH = Label()
    #labelH.setText("Humedad")
    #labelH.setOrigin(285,185)

    label55 = Label()
    label55.setText("55°")
    label55.setOrigin(325, 185)

    bc.xValueAxis.valueMin = 0
    bc.xValueAxis.valueMax = 30
    bc.xValueAxis.valueSteps = [x for x in range(0, bc.xValueAxis.valueMax, 5)]
    #bc.xValueAxis.labelTextFormat = '%2.1f'
    bc.yValueAxis.valueMin = 0
    bc.yValueAxis.valueMax = 80
    bc.yValueAxis.valueSteps = [0, 10, 20, 30, 40, 50, 60, 70, 80]
    drawing.add(bc)
    drawing.add(yilabel)
    drawing.add(xlabel)
    #drawing.add(Line(170,185,185,185, strokeColor=colors.red))
    #drawing.add(Line(250,185,265,185, strokeColor=colors.blue))
    drawing.add(
        Line(300,
             185,
             315,
             185,
             strokeColor=colors.black,
             strokeDashArray=[2, 2]))
    drawing.add(
        Line(50,
             135,
             350,
             135,
             strokeColor=colors.black,
             strokeDashArray=[2, 2]))
    #drawing.add(labelT)
    #drawing.add(labelH)
    drawing.add(label55)
    #drawing.add(Grid())
    drawing.add(String(130, 200, "Gráfico de temperaturas", fontSize=16))

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

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

    chart = None

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

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

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

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

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

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

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

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

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

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

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

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

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

    return drawing
Пример #23
0
 def __init__(self, width=400, height=200, *args, **kw):
     Drawing.__init__(self, width, height, *args, **kw)
     # Width and height of chart.
     self.width = 772
     self.height = 280
     # Add title.
     self._add(self, Label(), name='title', validate=None, desc=None)
     self.title._text = 'Simple Line Chart'
     self.title.fontSize = 24
     self.title.fontName = "Calibri"
     # Position Title.
     self.title.x = 386
     self.title.y = 220
     # Add Line chart to the Drawing.
     self._add(self,
               SimpleTimeSeriesPlot(),
               name='chart',
               validate=None,
               desc=None)
     # Line Chart Position.
     self.chart.x = 150
     self.chart.y = 20
     # Line Chart Dimensions.
     self.chart.width = 400
     self.chart.height = 150
     # Color the lines.
     self.chart.lines[0].strokeColor = HexColor('#0079c1')
     self.chart.lines[0].symbol = makeMarker('FilledCircle')
     self.chart.lines[0].symbol.size = 10
     self.chart.lines[1].strokeColor = HexColor('#c41919')
     self.chart.lines[1].symbol = makeMarker('Circle')
     self.chart.lines[1].symbol.size = 5
     self.chart.lines[2].strokeColor = HexColor('#ffe207')
     self.chart.lines[2].symbol = makeMarker('Circle')
     self.chart.lines[2].symbol.size = 30
     self.chart.lines[3].strokeColor = HexColor('#07e2ff')
     self.chart.lines[3].symbol = makeMarker('Circle')
     self.chart.lines[3].symbol.size = 15
     self.chart.lines[4].strokeColor = HexColor('#4423af')
     self.chart.lines[4].symbol = makeMarker('Circle')
     self.chart.lines[4].symbol.size = 5
     self.chart.lines[5].strokeColor = HexColor('#26a543')
     self.chart.lines[5].symbol = makeMarker('Circle')
     self.chart.lines[5].symbol.size = 20
     self.chart.lines[6].strokeColor = HexColor('#af22ac')
     self.chart.lines[6].symbol = makeMarker('Circle')
     self.chart.lines[6].symbol.size = 12
     # Hide Lines
     self.chart.joinedLines = 0
     # Format Labels on X-Axis
     self.chart.xValueAxis.xLabelFormat = '{dd}/{mm}/{yy}'
     # Grid Lines Visible on Graph.
     self.chart.xValueAxis.visibleGrid = 1
     self.chart.yValueAxis.visibleGrid = 1
     # Format labels on Y-Axis
     self.chart.yValueAxis.labelTextFormat = '%.1f%%'
     # Avoid assuming lowest value as origin
     self.chart.yValueAxis.avoidBoundSpace = (10, 0)
     # Add legends to the graph
     self._add(self, Legend(), name='legend', validate=None, desc=None)
     # Initialize Color vs Desc text
     self.legend.colorNamePairs = [
         (HexColor('#0079c1'), 'Data1'),
         (HexColor('#c41919'), 'Data2'),
         (HexColor('#ffe207'), 'Data3'),
         (HexColor('#07e2ff'), 'Data4'),
         (HexColor('#4423af'), 'Data5'),
         (HexColor('#26a543'), 'Data6'),
         (HexColor('#af22ac'), 'Data7'),
     ]
     # Position Legend
     self.legend.x = 600
     self.legend.y = 155
     self.legend.columnMaximum = 7
Пример #24
0
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.widgets.markers import makeMarker

drawing = Drawing(400, 200)

data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))]

lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
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)

draw(drawing, "LinePlot sample")
Пример #25
0
def create_single_grade_pdf(student_id, class_id, assignment_count, grade_standard_dict, grade_student_dict, assignment_line_all, assignment_names, assignment_dict):
    '''--Variables--'''
    Story=[]
    Elements=[]
    buff = StringIO()
    formatted_time = time.ctime()
    minimum = 100
    standard_averages=[[]]
    standard_table=[]

    #content_areas = []

    '''------'''
    styles = getSampleStyleSheet()
    HeaderStyle = styles["Heading1"]

    #get the student Name

    #Create the name for the PDf being returned
    pdfName = get_student_name(student_id).first_name+"_"+get_student_name(student_id).last_name+"_SR"+".pdf"

    #set up the response headers so the browser knows to return a PDF document
    response.headers['Content-Type'] = 'application/pdf'
    response.headers['Content-Disposition'] ='attachment;filename=%s;'%pdfName
    doc = SimpleDocTemplate(buff,pagesize=letter,rightMargin=72,leftMargin=72,topMargin=72,bottomMargin=18)
    doc.title=pdfName

    #Set up some styles
    styles=getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    styles.add(ParagraphStyle(name='Indent', rightIndent=3))
    styles.add(ParagraphStyle(name = 'Title2',
                                  parent = styles['Normal'],
                                  fontName = 'DejaVuSansCondensed',
                                  fontSize = 18,
                                  leading = 22,
                                  #alignment = TA_LEFT,
                                  spaceAfter = 6),
                                  alias = 'title2')


    #Time-Stamp
    ptext = '<font size=12>%s</font>' % formatted_time
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))
    Elements.extend(ptext)

    #Administrator
    ptext='<font size=12><b>%s %s</b></font>'%(get_student_name(student_id).first_name, get_student_name(student_id).last_name)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))
    Elements.extend(ptext)

    #Grade Number and Content Area
    ptext = '<font size=12><b>%s Student Report</b></font>'%(get_class_name(class_id).name)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 7))
    Elements.extend(ptext)
    
    
    #Total Assignments
    ptext = '<font size=12>Total Assignments: %s</font>'%(assignment_count)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 7))
    Elements.extend(ptext)
    
    
    
    
    
    Story.append(Spacer(1,20))
    #Graph Title
    ptext = '<font size=15><b>Current Performance by Standard</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1,50))

    
    #get all the standards for a specific grade and content area
    standard_query = ((db.classes.id == class_id)&
                       (student_id == db.student.id)&
                      (db.classes.id == db.student_classes.class_id)&
                      (db.student.id == db.student_classes.student_id)&
                      (db.student.id == db.student_grade.student_id)&
                      (db.grade.id == db.student_grade.grade_id)&
                      (db.grade.id == db.grade_standard.grade_id)&
                      (db.standard.id == db.grade_standard.standard_id)&
                      (db.classes.id == db.class_grade.class_id)&
                      (db.grade.id == db.class_grade.grade_id)&
                      (db.standard.content_area == db.contentarea.id))

    standard_list = db(standard_query).select(db.standard.id, db.standard.short_name, db.standard.reference_number,db.student_grade.student_score, db.grade.score, db.contentarea.name)
    standard_ref_list=[]
    #Setup the Dictionary of standard averages
    standard_dict = {}
    standard_table = []
    standard_averages=[[]]
    for row in standard_list:
        if row.standard.id in standard_dict.keys():
            if((row.grade.score != 0.0) | (row.student_grade.student_score != 0.0)):
                max_score = standard_dict[row.standard.id][0] + row.grade.score
                student_score = standard_dict[row.standard.id][1] + row.student_grade.student_score
                standard_dict[row.standard.id] = [max_score, student_score, row.standard.reference_number, row.standard.short_name]
        else:
            standard_dict[row.standard.id] = [row.grade.score, row.student_grade.student_score, row.standard.reference_number, row.standard.short_name]

    
    
        
    i = 0
    #set up the 2D list of Standard Averages
    for standard in sorted(standard_dict.keys()):
        standard_ref_list.append(standard_dict[standard][2])
        standard_table.append([])
        current_avg = (standard_dict[standard][1]/standard_dict[standard][0])*100
        if minimum > current_avg:
            minimum = current_avg
        #int/round was here
        standard_table[i].append(standard_dict[standard][3]+": "+format((standard_dict[standard][1]/standard_dict[standard][0])*100,'.2f')+"%")
        #int/round was here 
        standard_averages[0].append((standard_dict[standard][1]/standard_dict[standard][0])*100)


        for grade in grade_standard_dict.keys():
            for standardId in grade_standard_dict[grade][1]:
                if(standardId == standard):
                    standard_table[i].append(grade_standard_dict[grade][0]+":"+format((grade_student_dict[grade][1]/grade_student_dict[grade][0])*100, '.2f')+"%")
        i+=1
    sorted(standard_table,key=lambda l:l[0])

    
    '''---Graph---'''
    drawing = Drawing(600, 200)
    data = standard_averages
    bc = VerticalBarChart()

    #location in the document (x,y)
    bc.x = 10
    bc.y = 30

    #width and height of the graph
    bc.height = 225
    bc.width = 400
    bc.data = data
    bc.categoryAxis.drawGridLast=True
    bc.categoryAxis.gridStart=0
    bc.categoryAxis.gridStrokeLineCap = 2
    bc.categoryAxis.gridEnd=3
    #bc.barLabels = 

    #Update colors of the bars in the graph
    bc.bars.symbol = ShadedRect()
    bc.bars.symbol.fillColorStart = colors.lightblue
    bc.bars.symbol.fillColorEnd = colors.lightblue
    bc.bars.symbol.strokeWidth = 0


    #this draws a line at the top of the graph to close it. 
    bc.strokeColor = colors.black

    #Y-axis min, max, and steps.
    if minimum != 100:
        bc.valueAxis.valueMin = minimum -10
    else:
        bc.valueAxis.valueMin = 50
    bc.valueAxis.valueMax = 100
    bc.valueAxis.valueStep = 5

    #where to anchor the origin of the graph
    bc.categoryAxis.labels.boxAnchor = 'ne'

    #Locations of labels for the X-axis
    bc.categoryAxis.labels.dx = 2
    bc.categoryAxis.labels.dy = -2

    bc.barLabels.nudge = -10
    bc.barLabelFormat = '%.2f%%'
    bc.barLabels.dx = 0
    bc.barLabels.dy = 0
    #The angle of the lables for the X-axis
    bc.categoryAxis.labels.angle = 30
    #List of the categories to place on the X-axis
    bc.categoryAxis.categoryNames = standard_ref_list
    drawing.add(bc)
    '''------'''
    '''--Graph Legend--'''
    #Graph Legend
    legend = Legend()
    legend.alignment = 'right'
    legend.x = 420
    legend.y = 150
    legend.deltax = 60
    legend.dxTextSpace = 10
    legend.columnMaximum = 4

    legend.colorNamePairs = [(colors.lightblue, 'grade average')]
    drawing.add(legend, 'legend')
    drawing_title = "Bar Graph"
    
    Story.append(drawing)
    Story.append(Spacer(1,15))
    #LineGraph Title
    ptext = '<font size=15><b>Class Performance by Assignment</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1,30))
    
    '''
    Line Plot Graph ------
    '''
    assignment_data_all =[[],[]]
    for key in assignment_dict.keys():
        assignment_data_all[0].append(assignment_dict[key][2])
        assignment_data_all[1].append(assignment_dict[key][1])
    drawing2 = Drawing(600, 200)
    data2 = assignment_data_all
    #lp = LinePlot()
    
    #data[0] = preprocessData(data[0])
    lp = HorizontalLineChart()
    lp.x = -20
    lp.y = 0
    lp.height = 225
    lp.width = 500
    lp.data = data2
    lp.joinedLines = 1
    lp.lines.symbol = makeMarker('FilledCircle')
    lp.lines[0].strokeColor = colors.grey
    lp.lines[1].strokeColor = colors.lightblue
    lp.strokeColor = colors.black
    lp.categoryAxis.labels.fontSize = 7
    lp.categoryAxis.categoryNames = assignment_names
    lp.categoryAxis.labels.boxAnchor = 'ne'
    lp.categoryAxis.labels.angle = 30
    lp.categoryAxis.drawGridLast=True
    #lp.categoryAxis.gridStart=0
    lp.categoryAxis.gridStrokeLineCap = 2
    #lp.categoryAxis.gridEnd=3
    #lp.categoryAxis.visibleGrid           = 1
    lp.valueAxis.visibleGrid           = 1
    lp.valueAxis.visible               = 1
    lp.valueAxis.drawGridLast=False
    #lp.valueAxis.gridStart = 0
    #lp.valueAxis.gridEnd = 100
    lp.valueAxis.gridStrokeColor = colors.black
    lp.valueAxis.valueMin = 0
    lp.valueAxis.valueMax = 105
    lp.valueAxis.valueStep = 10
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.fillColor = colors.white
    drawing2.add(lp)
    
    legend = Legend()
    legend.alignment = 'right'
    legend.x = 482
    legend.y = 150
    legend.deltax = 60
    legend.dxTextSpace = 2
    legend.colorNamePairs = [(colors.lightblue, 'Student'),(colors.grey, 'Class')]
    drawing2.add(legend, 'legend')
    
    Story.append(drawing2)
    Story.append(Spacer(1,30))
    ptext = '<font size=15><b>Assignments by Standard</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1,10))
    t=Table(standard_table)
    t.setStyle(t.setStyle(TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black),
                                      ('FONTSIZE', (0,0), (-1,-1), 7),
                                      ('BACKGROUND',(0,0),(0,-1),colors.lightgrey),
                                      ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),])))
    Story.append(t)
    #build PDF document and return it
    doc.build(Story)
    pdf = buff.getvalue()
    buff.close()
    return pdf
Пример #26
0
def symbols(canv,data):
    '''
    produces filled symbols

    arguments
    n   number of points default 5
    x,y     initial symbol location
    dx      delta x for each new symbol
    dy      delta y for each symbol
    name    symbol name (suitable for makeMarker)
    fillColor   symbol fill colour
    strokeColor symbol stroke colour
    strokeWidth symbol stroke width
    angle   symbol angle
    '''
    args, kw = _evalArgs(data)
    if args:
        raise TypeError('Symbols takes no positional arguments')
    params = dict(
            n=5,
            x='72',
            y='72',
            dx='None',
            dy='0',
            name='StarFive',
            fillColor='yellow',
            strokeColor=None,
            strokeWidth='1',
            angle=0,
            )
    params.update(kw)

    from reportlab.graphics.shapes import Drawing
    from reportlab.graphics.widgets.markers import makeMarker
    from reportPackages.rlextra.rml2pdf.rml2pdf import readLengthOrNone

    name = params['name']
    n = int(params['n'])
    x0 = readLengthOrNone(params['x'])
    y0 = readLengthOrNone(params['y'])
    angle = float(params['angle'])
    size = readLengthOrNone(params['size'])
    strokeWidth = readLengthOrNone(params['strokeWidth'])
    dx = readLengthOrNone(params['dx'])
    if dx is None: dx = 2+1.5*size
    dy = readLengthOrNone(params['dy'])
    strokeColor = _toColor(params['strokeColor'])
    fillColor = _toColor(params['fillColor'])

    D = Drawing()
    for i in range(n):
        m = makeMarker(name)
        m.x = dx*i
        m.y = dy*i
        m.angle = angle
        m.size = size
        m.strokeWidth = strokeWidth
        m.strokeColor = strokeColor
        m.fillColor = fillColor
        D.add(m)

    D.drawOn(canv,x0,y0)
Пример #27
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
Пример #28
0
def addAcPower(canvas_param, opc_df_today, pos_x, pos_y, width, height):

    total_df = opc_df_today

    #  取出
    # “离心机1号实时功率”、
    # “离心机2号实时功率”、
    # “螺杆机实时功率”

    total_df_01P = total_df[total_df.browse_name ==
                            'Chilling_unit1_D1_CH-01-Load']
    total_df_02P = total_df[total_df.browse_name ==
                            'Chilling_unit2_D2_CH-02-Load']
    total_df_03P = total_df[total_df.browse_name ==
                            'Chilling_unit3_D3_CH-03-Load']

    # 生成5个变量相应的点阵
    data_01P = ExtractPointFromDf_DateX(
        df_origin=total_df_01P,
        date_col='present_value_source_timestamp',
        y_col='present_value_value')

    data_02P = ExtractPointFromDf_DateX(
        df_origin=total_df_02P,
        date_col='present_value_source_timestamp',
        y_col='present_value_value')

    data_03P = ExtractPointFromDf_DateX(
        df_origin=total_df_03P,
        date_col='present_value_source_timestamp',
        y_col='present_value_value')

    data_origin = [tuple(data_01P), tuple(data_02P), tuple(data_03P)]

    # 定义各曲线标签
    data_name_origin = ['离心机1号实时功率', '离心机2号实时功率', '螺杆机实时功率']

    # 处理某条线没有数据的情况,若不处理“没有数据”的情况,画线的时候会报错!
    data = []
    data_name = []

    for i in range(0, len(data_origin)):
        if len(data_origin[i]) != 0:
            data.append(data_origin[i])
            data_name.append(data_name_origin[i])

    if len(data) == 0:
        print('函数 addAcTemp:原始df解析后没有想要的冷机功率数据!')
        return canvas_param

    c = canvas_param
    # c.setFont("song", 10)

    drawing = Drawing(width=width, height=height)

    lp = LinePlot()
    # lp.x = 50
    # lp.y = 50
    lp.height = height
    lp.width = width
    lp.data = data
    lp.joinedLines = 1

    # 定义各曲线颜色
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.lightgreen
    lp.lines[3].strokeColor = colors.orange
    lp.lines[4].strokeColor = colors.darkgreen

    for i in range(0, len(data)):
        lp.lines[i].name = data_name[i]
        lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5)
        lp.lines[i].strokeWidth = 0.05

    # lp.lineLabelFormat = '%2.0f'
    # lp.strokeColor = colors.black

    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 60 * 60 * 24
    lp.xValueAxis.valueSteps = [n for n in range(0, 60 * 60 * 24, 60 * 60)]
    lp.xValueAxis.labelTextFormat = lambda x: str(s2t(x))[0:2]
    lp.yValueAxis.valueMin = 0
    # lp.yValueAxis.valueMax = 50
    # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-10)

    # 将画布添加到pdf中
    renderPDF.draw(drawing=drawing, canvas=c, x=pos_x, y=pos_y)

    return c
Пример #29
0
    def draw(self):
        # normalize slice data
        g = self.makeBackground() or Group()

        xradius = self.width/2.0
        yradius = self.height/2.0
        self._radius = radius = min(xradius, yradius)
        centerx = self.x + xradius
        centery = self.y + yradius

        data = self.normalizeData()

        n = len(data[0])

        #labels
        if self.labels is None:
            labels = [''] * n
        else:
            labels = self.labels
            #there's no point in raising errors for less than enough errors if
            #we silently create all for the extreme case of no labels.
            i = n-len(labels)
            if i>0:
                labels = labels + ['']*i

        spokes = []
        csa = []
        angle = self.startAngle*pi/180
        direction = self.direction == "clockwise" and -1 or 1
        angleBetween = direction*(2 * pi)/n
        markers = self.strands.markers
        for i in xrange(n):
            car = cos(angle)*radius
            sar = sin(angle)*radius
            csa.append((car,sar,angle))
            spoke = Line(centerx, centery, centerx + car, centery + sar, strokeWidth = 0.5)
            #print 'added spoke (%0.2f, %0.2f) -> (%0.2f, %0.2f)' % (spoke.x1, spoke.y1, spoke.x2, spoke.y2)
            spokes.append(spoke)
            if labels:
                si = self.strands[i]
                text = si.label_text
                if text is None: text = labels[i]
                if text:
                    labelRadius = si.labelRadius
                    L = WedgeLabel()
                    L.x = centerx + labelRadius*car
                    L.y = centery + labelRadius*sar
                    L.boxAnchor = si.label_boxAnchor
                    L._pmv = angle*180/pi
                    L.dx = si.label_dx
                    L.dy = si.label_dy
                    L.angle = si.label_angle
                    L.boxAnchor = si.label_boxAnchor
                    L.boxStrokeColor = si.label_boxStrokeColor
                    L.boxStrokeWidth = si.label_boxStrokeWidth
                    L.boxFillColor = si.label_boxFillColor
                    L.strokeColor = si.label_strokeColor
                    L.strokeWidth = si.label_strokeWidth
                    L._text = text
                    L.leading = si.label_leading
                    L.width = si.label_width
                    L.maxWidth = si.label_maxWidth
                    L.height = si.label_height
                    L.textAnchor = si.label_textAnchor
                    L.visible = si.label_visible
                    L.topPadding = si.label_topPadding
                    L.leftPadding = si.label_leftPadding
                    L.rightPadding = si.label_rightPadding
                    L.bottomPadding = si.label_bottomPadding
                    L.fontName = si.fontName
                    L.fontSize = si.fontSize
                    L.fillColor = si.fontColor
                    spokes.append(L)
            angle = angle + angleBetween

        # now plot the polygons

        rowIdx = 0
        for row in data:
            # series plot
            points = []
            car, sar = csa[-1][:2]
            r = row[-1]
            points.append(centerx+car*r)
            points.append(centery+sar*r)
            for i in xrange(n):
                car, sar = csa[i][:2]
                r = row[i]
                points.append(centerx+car*r)
                points.append(centery+sar*r)

                # make up the 'strand'
                strand = Polygon(points)
                strand.fillColor = self.strands[rowIdx].fillColor
                strand.strokeColor = self.strands[rowIdx].strokeColor
                strand.strokeWidth = self.strands[rowIdx].strokeWidth
                strand.strokeDashArray = self.strands[rowIdx].strokeDashArray

                g.add(strand)

                # put in a marker, if it needs one
                if markers:
                    if hasattr(self.strands[rowIdx], 'markerType'):
                        uSymbol = self.strands[rowIdx].markerType
                    elif hasattr(self.strands, 'markerType'):
                        uSymbol = self.strands.markerType
                    else:
                        uSymbol = None
                    m_x =  centerx+car*r
                    m_y = centery+sar*r
                    m_size = self.strands[rowIdx].markerSize
                    m_fillColor = self.strands[rowIdx].fillColor
                    m_strokeColor = self.strands[rowIdx].strokeColor
                    m_strokeWidth = self.strands[rowIdx].strokeWidth
                    m_angle = 0
                    if type(uSymbol) is type(''):
                        symbol = makeMarker(uSymbol,
                                    size = m_size,
                                    x =  m_x,
                                    y = m_y,
                                    fillColor = m_fillColor,
                                    strokeColor = m_strokeColor,
                                    strokeWidth = m_strokeWidth,
                                    angle = m_angle,
                                    )
                    else:
                        symbol = uSymbol2Symbol(uSymbol,m_x,m_y,m_fillColor)
                        for k,v in (('size', m_size), ('fillColor', m_fillColor),
                                    ('x', m_x), ('y', m_y),
                                    ('strokeColor',m_strokeColor), ('strokeWidth',m_strokeWidth),
                                    ('angle',m_angle),):
                            try:
                                setattr(uSymbol,k,v)
                            except:
                                pass
                    g.add(symbol)

            rowIdx = rowIdx + 1

        # spokes go over strands
        for spoke in spokes:
            g.add(spoke)
        return g
Пример #30
0
    def __init__(self, width=1000, height=400, *args, **kwargs):
        Drawing.__init__(self, width, height, *args, **kwargs)
        # background color
        self.background = Rect(0,
                               0,
                               self.width,
                               self.height,
                               strokeWidth=0,
                               fillColor=colors.lightgrey)
        # end here
        self.add(Circle(500, 200, 180), name='circle_perfect')
        self.add(Circle(500, 200, 145), name='circle_good')
        self.add(Circle(500, 200, 115), name='circle_medium')
        self.add(Circle(500, 200, 85), name='circle_bad')
        self.add(Circle(500, 200, 50), name='circle_awful')
        self.add(Circle(500, 200, 20), name='circle_center')
        self.add(SpiderChart(), name='background_chart')
        self.add(SpiderChart(), name='chart')

        # QR code
        qrw = QrCodeWidget('Well met')

        # QR size
        qrw.barHeight = 150
        qrw.barWidth = 150

        # QR position
        qrw.y = 100
        qrw.x = 10

        self.add(qrw)
        # end here

        # barcode
        barcode_group = Group()
        barcode = createBarcodeDrawing('EAN13',
                                       value='1234567890',
                                       width=200,
                                       height=100)

        barcode_group.add(barcode)
        barcode_group.shift(10, 10)  # barcode position
        self.add(barcode_group)
        # end here

        self.add(String(470, 386, 'Аналіз крові'), name='text0')
        self.add(String(605, 352, 'Антропометрія'), name='text1')
        self.add(String(670, 275, 'Постава'), name='text2')
        self.add(String(685, 170, 'Композиція тіла'), name='text3')
        self.add(String(645, 75, 'Електрокардіограмма'), name='text4')
        self.add(String(550, 10, 'Варіаційна пульсометрія'), name='text5')
        self.add(String(350, 10, 'Система дихання'), name='text6')
        self.add(String(220, 75, 'Кистьова динамометрія'), name='text7')
        self.add(String(225, 170, 'Основний обмін'), name='text8')
        self.add(String(160, 275, 'Карідореспіраторний профіль'), name='text9')
        self.add(String(330, 350, 'Психотест'), name='text10')

        # info
        self.add(String(840, 366, 'Чудово'), name='info_perfect')
        self.circle_perfect.fillColor = colors.Color(0, 0, 255, alpha=0.3)
        self.circle_perfect.strokeColor = colors.transparent
        self.info_perfect.fontName = 'HelveticaNeueC'
        self.info_perfect.fontSize = 12
        self.add(Rect(800, 356, 30, 30), name='rect_perfect')
        self.rect_perfect.fillColor = colors.Color(0, 0, 255, alpha=0.3)
        self.rect_perfect.strokeColor = colors.transparent

        self.add(String(840, 326, 'Добре'), name='info_good')
        self.circle_good.fillColor = colors.Color(0, 255, 0, alpha=0.5)
        self.circle_good.strokeColor = colors.transparent
        self.info_good.fontName = 'HelveticaNeueC'
        self.info_good.fontSize = 12
        self.add(Rect(800, 316, 30, 30), name='rect_good')
        self.rect_good.fillColor = colors.Color(0, 255, 0, alpha=0.5)
        self.rect_good.strokeColor = colors.transparent

        self.add(String(840, 286, 'Задовільно'), name='info_medium')
        self.circle_medium.fillColor = colors.yellow
        self.circle_medium.strokeColor = colors.transparent
        self.info_medium.fontName = 'HelveticaNeueC'
        self.info_medium.fontSize = 12
        self.add(Rect(800, 276, 30, 30), name='rect_medium')
        self.rect_medium.fillColor = colors.yellow
        self.rect_medium.strokeColor = colors.transparent

        self.add(String(840, 246, 'Погано'), name='info_bad')
        self.circle_bad.fillColor = colors.orange
        self.circle_bad.strokeColor = colors.transparent
        self.info_bad.fontName = 'HelveticaNeueC'
        self.info_bad.fontSize = 12
        self.add(Rect(800, 236, 30, 30), name='rect_bad')
        self.rect_bad.fillColor = colors.orange
        self.rect_bad.strokeColor = colors.transparent

        self.add(String(840, 206, 'Дуже погано'), name='info_awful')
        self.circle_awful.fillColor = colors.red
        self.circle_awful.strokeColor = colors.transparent
        self.info_awful.fontName = 'HelveticaNeueC'
        self.info_awful.fontSize = 12
        self.add(Rect(800, 196, 30, 30), name='rect_awful')
        self.rect_awful.fillColor = colors.red
        self.rect_awful.strokeColor = colors.transparent

        # end here

        self.chart.x = 20
        self.chart.y = 40
        self.chart.width = self.width - 40
        self.chart.height = self.height - 80

        self.background_chart.x = 10
        self.background_chart.y = 20
        self.background_chart.width = self.width - 20
        self.background_chart.height = self.height - 40

        # ruin has com to my code TODO rework this garbage
        self.text0.fontName = 'HelveticaNeueC'
        self.text0.fontSize = 12
        self.text1.fontName = 'HelveticaNeueC'
        self.text1.fontSize = 12
        self.text2.fontName = 'HelveticaNeueC'
        self.text2.fontSize = 12
        self.text3.fontName = 'HelveticaNeueC'
        self.text3.fontSize = 12
        self.text4.fontName = 'HelveticaNeueC'
        self.text4.fontSize = 12
        self.text5.fontName = 'HelveticaNeueC'
        self.text5.fontSize = 12
        self.text6.fontName = 'HelveticaNeueC'
        self.text6.fontSize = 12
        self.text7.fontName = 'HelveticaNeueC'
        self.text7.fontSize = 12
        self.text8.fontName = 'HelveticaNeueC'
        self.text8.fontSize = 12
        self.text9.fontName = 'HelveticaNeueC'
        self.text9.fontSize = 12
        self.text10.fontName = 'HelveticaNeueC'
        self.text10.fontSize = 12
        # end here aaaaaaaaaaaaaaaaaa

        self.chart.labels = [
            ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
        ]
        self.background_chart.labels = [
            ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
        ]

        self.chart.data = [
            [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],  # style
            [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],  # style
            [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],  # style
            [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],  # style
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],  # style
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  # values
        ]

        self.background_chart.data = [
            [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],  # style
            [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],  # style
            [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],  # style
            [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],  # style
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],  # style
        ]

        # style
        self.chart.strands.strokeColor = colors.transparent
        self.background_chart.strands.strokeColor = colors.transparent
        self.background_chart.spokes.strokeColor = colors.lightgrey
        # self.chart.strands[1].strokeWidth = 15
        # self.chart.strands[1].strokeColor = colors.lightgreen
        # self.chart.strands[2].strokeWidth = 15
        # self.chart.strands[2].strokeColor = colors.yellow
        # self.chart.strands[3].strokeWidth = 15
        # self.chart.strands[3].strokeColor = colors.orange
        # self.chart.strands[4].strokeWidth = 15
        # self.chart.strands[4].strokeColor = colors.red

        # self.background_chart.strands[0].fillColor = colors.Color(0, 0, 255, alpha=0.3)
        # self.background_chart.strands[1].fillColor = colors.Color(0, 255, 0, alpha=0.5)
        # self.background_chart.strands[2].fillColor = colors.yellow
        # self.background_chart.strands[3].fillColor = colors.orange
        # self.background_chart.strands[4].fillColor = colors.red

        # self.chart.strands[0].strokeColor = colors.blue
        # self.chart.strands[0].strokeDashArray = (4, 4)
        # self.chart.strands[0].symbol = makeMarker("Circle")
        # self.chart.strands[0].strokeWidth = 0.5
        # self.chart.strands[0].symbol.fillColor = colors.black

        #end here

        self.chart.strandLabels.format = 'values'

        # main graph style
        self.chart.strands[5].strokeColor = colors.darkblue
        self.chart.spokes.strokeColor = colors.transparent

        self.chart.strands[5].symbol = makeMarker('FilledCircle', size=11)
        # self.chart.strandLabels.dR = -20
        self.chart.strands[5].symbol.fillColor = colors.white
        self.chart.strands[5].strokeWidth = 2
Пример #31
0
low = [row[4] for row in data]
times = [row[0] + row[1] / 12.0 for row in data]

lp = LinePlot()
lp.gridFirst = True
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
lp.data = [
    list(zip(times, pred)),
    list(zip(times, high)),
    list(zip(times, low))
]
lp.lines[0].strokeColor = colors.blue
lp.lines[0].symbol = makeMarker('FilledCircle', size=3)
lp.lines[0].name = 'Predict'
lp.lines[1].strokeColor = colors.red
lp.lines[1].symbol = makeMarker('FilledCircle', size=3)
lp.lines[1].name = 'High'
lp.lines[2].strokeColor = colors.green
lp.lines[2].symbol = makeMarker('FilledCircle', size=3)
lp.lines[2].name = 'Low'

drawing.add(Circle(320, 190, 3, fillColor=colors.blue))
drawing.add(Circle(320, 180, 3, fillColor=colors.red))
drawing.add(Circle(320, 170, 3, fillColor=colors.green))

labs = [Label(), Label(), Label()]
i = 0
for lab in labs:
Пример #32
0
 def categoryVvalueChart(self,
                         chapter,
                         ordinateValues,
                         abscissaCategories,
                         chartType='HorizontalBarChart',
                         markerType=None,
                         gridlinesX=False,
                         gridlinesY=True,
                         ordinateTics=10,
                         bIncludeZero=True,
                         ordinateFmtType='%0.3f',
                         chartIdx=0,
                         pageHfraction=1.0,
                         chartX=None,
                         chartY=None,
                         chartH=None,
                         chartW=None,
                         title="",
                         captionLabel="",
                         caption="",
                         fontname='',
                         fontsize='',
                         fontcolor=''):
     abscissaCategories, title, captionLabel, caption = GetUnicode(
         [abscissaCategories, title, captionLabel, caption])
     ##testing
     #from numpy import randn,histogram
     #mu,sigma = 100,15
     #x = list(mu + sigma*randn(10000))
     #ordinateTics=10
     #ordinateValues,abscissaCategories = histogram(x,100,normed=True)
     #ordinateValues,abscissaCategories = [list(ordinateValues)],list(abscissaCategories)
     #for idx in xrange(len(abscissaCategories)):
     #    if idx%5: abscissaCategories[idx]=''
     #    else: abscissaCategories[idx]='%.2f'%abscissaCategories[idx]
     ##print abscissaCategories[:10],abscissaCategories[-10:]
     ##testing
     # if no X/Y & H/W scaling specified, set to fill up page within margins
     if chartType in ("HorizontalBarChart", "HorizontalLineChart",
                      "VerticalBarChart"):  # note: no "VerticalLineChart"
         pageWidth, pageHeight = self.pagesize  # in points
         nLeft, nBottom, nRight, nTop = [
             val * inch
             for val in self.nLeft, self.nBottom, self.nRight, self.nTop
         ]  # inches to points
         availH, availW = pageHfraction * (
             pageHeight - (nTop + nBottom)), pageWidth - (nLeft + nRight)
         pgMinDim, pgMaxDim = min(pageWidth / inch, pageHeight / inch), max(
             pageWidth / inch, pageHeight / inch)  # inches
         nGutter = min(
             pgMinDim / 17., pgMaxDim / 22.
         ) * inch  # 0.5" nominal gutter based on 8.5" x 11" paper size
         # todo: QC size (e.g., >0)
         if chartX == None or chartY == None or chartH == None or chartW == None:
             chartX, chartY, chartH, chartW, drawH, drawW = nGutter, nGutter, availH - 3 * nGutter, availW - 1.25 * nGutter, availH - 1.5 * nGutter, availW - 0.5 * nGutter
         else:
             chartX, chartY, chartH, chartW = [
                 val * inch for val in chartX, chartY, chartH, chartW
             ]
             drawH, drawW = chartH + 1.5 * nGutter, chartW + 0.75 * nGutter
         bIsHorizontal, bIsBarChart = chartType.find(
             'Horizontal') == 0, chartType.find('BarChart') > 0
         if bIsHorizontal:
             if bIsBarChart:
                 bXisValueYisCategory, bXisCategoryYisValue = True, False
                 gridlinesX, gridlinesY = gridlinesY, gridlinesX
                 chartObj = HorizontalBarChart()
                 for dataSeries in ordinateValues:
                     dataSeries.reverse()
                 ordinateValues.reverse()
                 abscissaCategories.reverse()
             else:  # note: HorizontalLineChart has same aspect as VerticalBarChart
                 bXisValueYisCategory, bXisCategoryYisValue = False, True
                 chartObj = HorizontalLineChart()
         else:  # note: only vertical chart possible is barchart
             bXisValueYisCategory, bXisCategoryYisValue = False, True
             chartObj = VerticalBarChart()
         if bXisValueYisCategory:
             labelsAngle, labelsAnchor, labelsDX, labelsDY = 0, 'e', -max(
                 [len(val) for val in abscissaCategories]), 0
             if gridlinesX:
                 chartObj.valueAxis.tickUp = chartH
             if gridlinesY:
                 chartObj.categoryAxis.tickRight = chartW
         else:  # bXisCategoryYisValue
             labelsAngle, labelsAnchor, labelsDX, labelsDY = 30, 'ne', 0, 0
             if gridlinesX:
                 chartObj.categoryAxis.tickUp = chartH
             if gridlinesY:
                 chartObj.valueAxis.tickRight = chartW
         colorPalette = [
             colors.lightcoral, colors.cornflower, colors.darkseagreen,
             colors.tan, colors.aquamarine, colors.lightsteelblue,
             colors.cadetblue, colors.thistle, colors.steelblue
         ]
         if bIsBarChart:
             chartObj.bars[0].fillColor = colorPalette[chartIdx % len(
                 colorPalette
             )]  # todo: bars[0],[1],... if ordinateValues a list of lists (stacked bars)
         else:
             chartObj.joinedLines = 1
             chartObj.lines[
                 0].strokeWidth = 2  # todo: lines[0],[1],... if ordinateValues a list of lists (multiple lines)
             chartObj.lines[0].strokeColor = colorPalette[
                 chartIdx % len(colorPalette)]  # ibid.
             #todo: chartObj.lines[0].symbol = makeMarker('FilledCircle') # or 'Circle', others?
             if markerType:
                 chartObj.lines[0].symbol = makeMarker(markerType)
         chartObj.data = ordinateValues
         chartObj.x, chartObj.y = chartX, chartY
         chartObj.height, chartObj.width = chartH, chartW
         ordinateMin = min([
             min(ordinateValuesSet) for ordinateValuesSet in ordinateValues
         ])
         ordinateMax = max([
             max(ordinateValuesSet) for ordinateValuesSet in ordinateValues
         ])
         if bIncludeZero:
             ordinateMin = min(0, ordinateMin)
             ordinateMax = max(0, ordinateMax)
         # evaluate ordinate range in graph string-label space and adjust ordinate[Min,Max,Step] accordingly
         ordinateMinGstr, ordinateMaxGstr = [
             ordinateGstr.replace('%', '').split()[0]
             for ordinateGstr in (ordinateFmtType % ordinateMin,
                                  ordinateFmtType % ordinateMax)
         ]
         ordinateMinG, ordinateMaxG = float(ordinateMaxGstr), float(
             ordinateMinGstr)
         bAdjustMinMax = True
         if ordinateMinG == ordinateMaxG:
             # if constant y-value graph, set range to span from zero (regardless of bIncludeZero)
             bAdjustMinMax = False
             if ordinateMinG != 0.:  # y-values!=0
                 if ordinateMax > 0: ordinateMin = 0
                 else: ordinateMax = 0
             else:  # y-values==0, set range to [0,1]
                 ordinateMin, ordinateMax = 0, 1.
             ordinateMinG, ordinateMaxG = ordinateMin, ordinateMax
             ordinateTics = 2
         #  determine smallest significant ordinateStep, per desired ordinateTicSize--using stepwise reduction down to 1
         for ordinateTicSize in range(ordinateTics, 1, -1):
             ordinateStep = abs(
                 (ordinateMaxG - ordinateMinG) / ordinateTicSize)
             ordinateStepGstr = ordinateFmtType % ordinateStep
             ordinateStepGstr = ordinateStepGstr.replace('%', '').split()[0]
             ordinateStepG = float(ordinateStepGstr)
             if ordinateStepG != 0:
                 ordinateStep = ordinateStepG
                 break
         if bAdjustMinMax:
             if ordinateMin != 0:  # extend y-axis on low side...
                 ordinateMin -= ordinateStep
             if ordinateMax != 0:  # then extend y-axis on high side, but don't exceed 100%...
                 try:
                     if (ordinateMax + ordinateStep
                         ) >= 100 and ordinateFmtType[-1] == '%':
                         ordinateMax = 100.
                     else:
                         ordinateMax += ordinateStep
                 except:  # ostensibly b/c invalid ordinateFmtType
                     ordinateMax += ordinateStep
         chartObj.valueAxis.valueMin, chartObj.valueAxis.valueMax, chartObj.valueAxis.valueStep = ordinateMin, ordinateMax, ordinateStep
         chartObj.valueAxis.labelTextFormat = ordinateFmtType
         chartObj.categoryAxis.labels.boxAnchor = labelsAnchor
         chartObj.categoryAxis.labels.dx, chartObj.categoryAxis.labels.dy = labelsDX, labelsDY
         chartObj.categoryAxis.labels.angle = labelsAngle
         chartObj.categoryAxis.categoryNames = abscissaCategories
         chartObjDrawing = Drawing(drawW, drawH)
         chartObjDrawing.add(chartObj)
         if title:
             self.CPage(
                 chapter, 0.5 + drawH / inch
             )  # todo: had to hack this b/c [start,end]Keep not working
             self.clabel2(chapter, title, fontname, fontsize, fontcolor)
         self.report[chapter].append(chartObjDrawing)
         if captionLabel or caption:
             self.report[chapter].append(
                 self.aTextFlowable('<b>%s</b> %s' %
                                    (captionLabel, caption),
                                    fontname=fontname,
                                    fontsize=fontsize,
                                    fontcolor=fontcolor))
    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)
Пример #34
0
from reportlab.graphics.charts.piecharts import Pie

from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.lib import colors

drawing = Drawing(400, 200)
data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)),
        ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))]
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
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)
drawing.save(formats=['pdf'], outDir='./pdfs', fnRoot='chart')
# c = canvas.Canvas('./pdfs/chart_canvas.pdf')
# c.da
Пример #35
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()
Пример #36
0
    def report(self, weather_history, title):
        doc = SimpleDocTemplate(self.buffer,
                                rightMargin=72,
                                leftMargin=72,
                                topMargin=30,
                                bottomMargin=72,
                                pagesize=self.pageSize)
        # register fonts
        freesans = settings.BASE_DIR + settings.STATIC_URL + "FreeSans.ttf"
        freesansbold = settings.BASE_DIR + settings.STATIC_URL + "FreeSansBold.ttf"
        pdfmetrics.registerFont(TTFont('FreeSans', freesans))
        pdfmetrics.registerFont(TTFont('FreeSansBold', freesansbold))
        # set up styles
        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(name="TableHeader",
                           fontSize=11,
                           alignment=TA_CENTER,
                           fontName="FreeSansBold"))
        styles.add(
            ParagraphStyle(name="ParagraphTitle",
                           fontSize=11,
                           alignment=TA_JUSTIFY,
                           fontName="FreeSansBold"))
        styles.add(
            ParagraphStyle(name="Justify",
                           alignment=TA_JUSTIFY,
                           fontName="FreeSans"))

        data = []
        data.append(Paragraph(title, styles["Title"]))
        data.append(Spacer(1, 12))
        table_data = []
        # table header
        table_data.append([
            Paragraph('Date', styles['TableHeader']),
            Paragraph('Station', styles['TableHeader']),
            Paragraph('Min temp', styles['TableHeader']),
            Paragraph('Mean temp', styles['TableHeader']),
            Paragraph('Max temp', styles['TableHeader'])
        ])
        for wh in weather_history:
            # add a row to table
            table_data.append([
                wh.date,
                Paragraph(wh.station.name,
                          styles['Justify']), u"{0} °C".format(wh.min),
                u"{0} °C".format(wh.mean), u"{0} °C".format(wh.max)
            ])
        # create table
        wh_table = Table(table_data, colWidths=[doc.width / 5.0] * 5)
        wh_table.hAlign = 'LEFT'
        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0), colors.gray)]))
        data.append(wh_table)
        data.append(Spacer(1, 48))

        # create line chart
        chart = SampleHorizontalLineChart()
        chart.width = 350
        chart.height = 135
        mins = [float(x.min) for x in weather_history]
        means = [float(x.mean) for x in weather_history]
        maxs = [float(x.max) for x in weather_history]
        chart.data = [mins, means, maxs]
        chart.lineLabels.fontName = 'FreeSans'
        chart.strokeColor = colors.white
        chart.fillColor = colors.lightblue
        chart.lines[0].strokeColor = colors.red
        chart.lines[0].strokeWidth = 2
        chart.lines.symbol = makeMarker('Square')
        chart.lineLabelFormat = '%2.0f'
        chart.categoryAxis.joinAxisMode = 'bottom'
        chart.categoryAxis.labels.fontName = 'FreeSans'
        chart.categoryAxis.labels.angle = 45
        chart.categoryAxis.labels.boxAnchor = 'e'
        chart.categoryAxis.categoryNames = [
            str(x.date) for x in weather_history
        ]
        chart.valueAxis.labelTextFormat = '%2.0f °C'
        chart.valueAxis.valueStep = 10

        # chart needs to be put in a drawing
        d = Drawing(0, 170)
        d.add(chart)
        # add drawing to data
        data.append(d)

        doc.build(data)
        pdf = self.buffer.getvalue()
        self.buffer.close()
        return pdf
Пример #37
0
    def crear_informe(self):
        guion = []
        d = Drawing(300, 200)

        tarta = Pie()
        tarta.x = 65
        tarta.y = 15
        tarta.width = 170
        tarta.height = 170

        tarta.data = []
        tarta.labels = []
        cores = []
        follaEstilo = getSampleStyleSheet()
        _HEX = list('0123456789ABCDEF')
        j=False
        ventasMarca=metodosBase.metodosBase.listar_ventas_marca(self)

        for ventaMarca in ventasMarca:
            tarta.data.append(ventaMarca[0])
            tarta.labels.append(ventaMarca[1])

            color = '#' + ''.join(_HEX[random.randint(0, len(_HEX)-1)] for _ in range(6))
            cores.append(colors.HexColor(color))
            if ((tarta.data[0] is not None) and j==False):
                mayor = tarta.data[0]
                indice=0
                j=True
            else:
                if(ventaMarca[0]>=mayor):
                    mayor=ventaMarca[0]




        tarta.slices.strokeWidth = 0.2  # anchura das liñas
        tarta.sideLabels = 1
        tarta.slices[tarta.data.index(mayor)].popout = 10  # destacase o gajo que pomos entre corchetes, o que ten maior valor de todos
        tarta.slices[tarta.data.index(mayor)].strokeWidth = 2  # a este gajo en concreto cambiamos o tamaño da liña
        tarta.slices[tarta.data.index(mayor)].labelRadius = 1.20  # radio da etiqueta , cambiamolo para este elemento
        tarta.slices[tarta.data.index(mayor)].fontColor = colors.red

        lenda = Legend()
        lenda.x = 370
        lenda.y = 0
        lenda.dx = 8
        lenda.dy = 8
        lenda.fontName = 'Helvetica'
        lenda.fontSize = 7
        lenda.boxAnchor = 'n'
        lenda.columnMaximum = 10
        lenda.strokeColor = colors.black
        lenda.strokeWidth = 1
        lenda.deltax = 75
        lenda.deltay = 10
        lenda.autoXPadding = 5
        lenda.yGap = 0
        lenda.dxTextSpace = 5
        lenda.alignment = 'right'
        lenda.dividerLines = 1 | 2 | 4
        lenda.dividerOffsY = 4.5
        lenda.subCols.rpad = 30

        for i, color in enumerate(cores):
            tarta.slices[i].fillColor = color
        lenda.colorNamePairs = [(tarta.slices[i].fillColor, (tarta.labels[i][0:20], '%0.2f' % tarta.data[i])
                                 ) for i in range(len(tarta.data))]
        '''parrafo 1 : cabeceira primeira grafica'''
        cabeceira = follaEstilo['Heading4']  # formato por defecto

        cabeceira.pageBreakBefore = 0  # con un uno a primeira folla queda en branco
        cabeceira.keepWitNext = 0  # para que non nos deixe a primeira paxina en branco
        cabeceira.backColor = colors.lightcyan
        parrafo = Paragraph("Informe de ventas por marcas", cabeceira)

        guion.append(parrafo)
        guion.append(Spacer(0, 40))

        d.add(lenda)
        d.add(tarta)
        guion.append(d)
        guion.append(Spacer(0, 60))
        '''parrafo 2:cabeceira segunda grafica'''
        cabeceira2 = follaEstilo['Heading4']  # formato por defecto

        cabeceira2.pageBreakBefore = 0  # con un uno a primeira folla queda en branco
        cabeceira2.keepWitNext = 0  # para que non nos deixe a primeira paxina en branco
        cabeceira2.backColor = colors.lightcyan
        parrafo2 = Paragraph("Informe de ventas por año de matriculación", cabeceira)

        guion.append(parrafo2)
        guion.append(Spacer(0, 40))

        d2 = Drawing(400, 200)
        lc = HorizontalLineChart()
        lc.x = 30
        lc.y = 50
        lc.height = 125
        lc.width = 350
        lc.data = []
        lista=[]
        lc.categoryAxis.categoryNames = []

        ventasAno = metodosBase.metodosBase.listar_ventas_anoMatricula(self)

        for ventaAno in ventasAno:
            lista.append(ventaAno[0])
            lc.categoryAxis.categoryNames.append(str(ventaAno[1]))
        lc.data.append(lista)

        lc.categoryAxis.labels.boxAnchor = 'n'
        lc.valueAxis.valueMin = 0
        lc.valueAxis.valueMax = 12
        lc.valueAxis.valueStep = 2
        lc.lines[0].strokeWidth = 2
        lc.lines[0].symbol = makeMarker('FilledCircle')  # círculos rellenos
        lc.lines[1].strokeWidth = 1.5
        d2.add(lc)
        guion.append(d2)
        guion.append(Spacer(0, 20))

        cabeceira3 = follaEstilo['Normal']  # formato por defecto
        parrafo3 = Paragraph(" COCHESJOSE S.L. CARRETERA INFINITA S/N  , TELEFONO:986505050", cabeceira3)
        cabeceira3.keepWitNext = 0  # para que non nos deixe a primeira paxina en branco
        guion.append(parrafo3)
        guion.append(Spacer(0, 20))

        doc = SimpleDocTemplate("informeVentas.pdf", pagesize=A4)

        doc.build(guion)
Пример #38
0
def addAcTemp(canvas_param, opc_df_today,pos_x, pos_y, width, height):

    total_df = opc_df_today

    #  取出
    # “室外天气”、
    # “冷却侧供水温度”、
    # “冷却侧回水温度”、
    # “冷冻侧供水温度”、
    # “冷冻侧回水温度”
    total_df_OAT = total_df[total_df.browse_name == 'OA-T']

    total_df_CSSWT = total_df[total_df.browse_name == 'CS-SWT']
    total_df_CSRWT = total_df[total_df.browse_name == 'CS-RWT']

    total_df_FSSWT = total_df[total_df.browse_name == 'FS-SWT']
    total_df_FSRWT = total_df[total_df.browse_name == 'FS-RWT']

    # 生成5个变量相应的点阵
    data_OAT = ExtractPointFromDf_DateX(df_origin=total_df_OAT, date_col='present_value_source_timestamp',
                                        y_col='present_value_value')

    data_CSSWT = ExtractPointFromDf_DateX(df_origin=total_df_CSSWT, date_col='present_value_source_timestamp',
                                          y_col='present_value_value')
    data_CSRWT = ExtractPointFromDf_DateX(df_origin=total_df_CSRWT, date_col='present_value_source_timestamp',
                                          y_col='present_value_value')

    data_FSSWT = ExtractPointFromDf_DateX(df_origin=total_df_FSSWT, date_col='present_value_source_timestamp',
                                          y_col='present_value_value')
    data_FSRWT = ExtractPointFromDf_DateX(df_origin=total_df_FSRWT, date_col='present_value_source_timestamp',
                                          y_col='present_value_value')

    data_origin = [tuple(data_OAT), tuple(data_CSSWT), tuple(data_CSRWT), tuple(data_FSSWT), tuple(data_FSRWT)]

    # 定义各曲线标签
    data_name_origin = ['室外温度', '冷却侧供水温度', '冷却侧回水温度', '冷冻侧供水温度', '冷冻侧回水温度']

    # 处理某条线没有数据的情况,若不处理“没有数据”的情况,画线的时候会报错!
    data = []
    data_name = []

    for i in range(0, len(data_origin)):
        if len(data_origin[i]) != 0:
            data.append(data_origin[i])
            data_name.append(data_name_origin[i])

    if len(data) == 0:
        print('函数 addAcTemp:原始df解析后没有想要的温度数据!')
        return canvas_param

    c = canvas_param
    # c.setFont("song", 10)

    drawing = Drawing(width=width, height=height)

    lp = LinePlot()
    # lp.x = 50
    # lp.y = 50
    lp.height = height
    lp.width = width
    lp.data = data
    lp.joinedLines = 1

    # 定义各曲线颜色
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.lightgreen
    lp.lines[3].strokeColor = colors.orange
    lp.lines[4].strokeColor = colors.darkgreen

    for i in range(0, len(data)):
        lp.lines[i].name = data_name[i]
        lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5)
        lp.lines[i].strokeWidth = 0.2

    # lp.lineLabelFormat = '%2.0f'
    # lp.strokeColor = colors.black

    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 60*60*24
    lp.xValueAxis.valueSteps = [n for n in range(0, 60*60*24, 60*60)]
    lp.xValueAxis.labelTextFormat = lambda x: str(s2t(x))[0:2]
    lp.yValueAxis.valueMin = 0
    # lp.yValueAxis.valueMax = 50
    # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-10)

    renderPDF.draw(drawing=drawing, canvas=c, x=pos_x, y=pos_y)
Пример #39
0
    def draw(self):
        # normalize slice data
        g = self.makeBackground() or Group()

        xradius = self.width/2.0
        yradius = self.height/2.0
        self._radius = radius = min(xradius, yradius)
        cx = self.x + xradius
        cy = self.y + yradius

        data = self.normalizeData()

        self._seriesCount = len(data)
        n = len(data[0])

        #labels
        if self.labels is None:
            labels = [''] * n
        else:
            labels = self.labels
            #there's no point in raising errors for less than enough errors if
            #we silently create all for the extreme case of no labels.
            i = n-len(labels)
            if i>0:
                labels = labels + ['']*i

        S = []
        STRANDS = []
        STRANDAREAS = []
        syms = []
        labs = []
        csa = []
        angle = self.startAngle*pi/180
        direction = self.direction == "clockwise" and -1 or 1
        angleBetween = direction*(2 * pi)/float(n)
        spokes = self.spokes
        spokeLabels = self.spokeLabels
        for i in xrange(n):
            car = cos(angle)*radius
            sar = sin(angle)*radius
            csa.append((car,sar,angle))
            si = self.spokes[i]
            if si.visible:
                spoke = Line(cx, cy, cx + car, cy + sar, strokeWidth = si.strokeWidth, strokeColor=si.strokeColor, strokeDashArray=si.strokeDashArray)
            S.append(spoke)
            sli = spokeLabels[i]
            text = sli._text
            if not text: text = labels[i]
            if text:
                S.append(_setupLabel(WedgeLabel, text, si.labelRadius, cx, cy, angle, car, sar, sli))
            angle += angleBetween

        # now plot the polygons
        rowIdx = 0
        strands = self.strands
        strandLabels = self.strandLabels
        for row in data:
            # series plot
            rsty = strands[rowIdx]
            points = []
            car, sar = csa[-1][:2]
            r = row[-1]
            points.append(cx+car*r)
            points.append(cy+sar*r)
            for i in xrange(n):
                car, sar, angle = csa[i]
                r = row[i]
                points.append(cx+car*r)
                points.append(cy+sar*r)
                L = self._innerDrawLabel(strandLabels[(rowIdx,i)], r, cx, cy, angle, car, sar, labelClass=StrandLabel)
                if L: labs.append(L)
                sty = strands[(rowIdx,i)]
                uSymbol = sty.symbol

                # put in a marker, if it needs one
                if uSymbol:
                    s_x =  cx+car*r
                    s_y = cy+sar*r
                    s_fillColor = sty.fillColor
                    s_strokeColor = sty.strokeColor
                    s_strokeWidth = sty.strokeWidth
                    s_angle = 0
                    s_size = sty.symbolSize
                    if type(uSymbol) is type(''):
                        symbol = makeMarker(uSymbol,
                                    size = s_size,
                                    x =  s_x,
                                    y = s_y,
                                    fillColor = s_fillColor,
                                    strokeColor = s_strokeColor,
                                    strokeWidth = s_strokeWidth,
                                    angle = s_angle,
                                    )
                    else:
                        symbol = uSymbol2Symbol(uSymbol,s_x,s_y,s_fillColor)
                        for k,v in (('size', s_size), ('fillColor', s_fillColor),
                                    ('x', s_x), ('y', s_y),
                                    ('strokeColor',s_strokeColor), ('strokeWidth',s_strokeWidth),
                                    ('angle',s_angle),):
                            if getattr(symbol,k,None) is None:
                                try:
                                    setattr(symbol,k,v)
                                except:
                                    pass
                    syms.append(symbol)

            # make up the 'strand'
            if rsty.fillColor:
                strand = Polygon(points)
                strand.fillColor = rsty.fillColor
                strand.strokeColor = None
                strand.strokeWidth = 0
                STRANDAREAS.append(strand)
            if rsty.strokeColor and rsty.strokeWidth:
                strand = PolyLine(points)
                strand.strokeColor = rsty.strokeColor
                strand.strokeWidth = rsty.strokeWidth
                strand.strokeDashArray = rsty.strokeDashArray
                STRANDS.append(strand)
            rowIdx += 1

        map(g.add,STRANDAREAS+STRANDS+syms+S+labs)
        return g
Пример #40
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')
Пример #41
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
    for i in range(1, int(num_clust)):
        fp_sum = fp_sum + dat_dict[num_clust][str(i)]['ALL_COUNT']/float(TOT)
        fn_sum = fn_sum + dat_dict[num_clust][str(i)]['AML_COUNT']/float(TOT)
    FP = TP - fp_sum
    FN = TN - fn_sum
    accuracy = (TP + TN) / (TP + FP + TN + FN) * 100.00
    accuracy_list.append((num_clust, accuracy))
    print "| %d             | %02.2f | %02.2f | %02.2f | %02.2f | %02.2f  |" % (num_clust, round(fp_sum), round(FP), round(fn_sum), round(FN), round(accuracy))
    
print "+---------------|-------|------|------|------|--------+"

lp.data = [accuracy_list]
print lp.data

lp.joinedLines = 1
lp.lines.symbol = makeMarker('Circle')
lp.lineLabelFormat = '%2.2f'
lp.strokeColor = colors.black
lp.xValueAxis.valueMin = 0
lp.xValueAxis.valueMax = 5
lp.xValueAxis.labelTextFormat = '%2.0f'
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 104
lp.yValueAxis.valueStep = 10

xlbl = Label()
xlbl.setText("No. of Clusters")
xlbl.setOrigin(310, 53)

xlbl1 = Label()
xlbl1.setText("No. Of Clusters Vs Accuracy")
Пример #43
0
def create_single_grade_pdf(student_id, class_id, assignment_count,
                            grade_standard_dict, grade_student_dict,
                            assignment_line_all, assignment_names,
                            assignment_dict):
    '''--Variables--'''
    Story = []
    Elements = []
    buff = StringIO()
    formatted_time = time.ctime()
    minimum = 100
    standard_averages = [[]]
    standard_table = []

    #content_areas = []
    '''------'''
    styles = getSampleStyleSheet()
    HeaderStyle = styles["Heading1"]

    #get the student Name

    #Create the name for the PDf being returned
    pdfName = get_student_name(student_id).first_name + "_" + get_student_name(
        student_id).last_name + "_SR" + ".pdf"

    #set up the response headers so the browser knows to return a PDF document
    response.headers['Content-Type'] = 'application/pdf'
    response.headers[
        'Content-Disposition'] = 'attachment;filename=%s;' % pdfName
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)
    doc.title = pdfName

    #Set up some styles
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    styles.add(ParagraphStyle(name='Indent', rightIndent=3))
    styles.add(
        ParagraphStyle(
            name='Title2',
            parent=styles['Normal'],
            fontName='DejaVuSansCondensed',
            fontSize=18,
            leading=22,
            #alignment = TA_LEFT,
            spaceAfter=6),
        alias='title2')

    #Time-Stamp
    ptext = '<font size=12>%s</font>' % formatted_time
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))
    Elements.extend(ptext)

    #Administrator
    ptext = '<font size=12><b>%s %s</b></font>' % (get_student_name(
        student_id).first_name, get_student_name(student_id).last_name)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))
    Elements.extend(ptext)

    #Grade Number and Content Area
    ptext = '<font size=12><b>%s Student Report</b></font>' % (
        get_class_name(class_id).name)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 7))
    Elements.extend(ptext)

    #Total Assignments
    ptext = '<font size=12>Total Assignments: %s</font>' % (assignment_count)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 7))
    Elements.extend(ptext)

    Story.append(Spacer(1, 20))
    #Graph Title
    ptext = '<font size=15><b>Current Performance by Standard</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1, 50))

    #get all the standards for a specific grade and content area
    standard_query = ((db.classes.id == class_id) &
                      (student_id == db.student.id) &
                      (db.classes.id == db.student_classes.class_id) &
                      (db.student.id == db.student_classes.student_id) &
                      (db.student.id == db.student_grade.student_id) &
                      (db.grade.id == db.student_grade.grade_id) &
                      (db.grade.id == db.grade_standard.grade_id) &
                      (db.standard.id == db.grade_standard.standard_id) &
                      (db.classes.id == db.class_grade.class_id) &
                      (db.grade.id == db.class_grade.grade_id) &
                      (db.standard.content_area == db.contentarea.id))

    standard_list = db(standard_query).select(
        db.standard.id, db.standard.short_name, db.standard.reference_number,
        db.student_grade.student_score, db.grade.score, db.contentarea.name)
    standard_ref_list = []
    #Setup the Dictionary of standard averages
    standard_dict = {}
    standard_table = []
    standard_averages = [[]]
    for row in standard_list:
        if row.standard.id in standard_dict.keys():
            if ((row.grade.score != 0.0) |
                (row.student_grade.student_score != 0.0)):
                max_score = standard_dict[row.standard.id][0] + row.grade.score
                student_score = standard_dict[
                    row.standard.id][1] + row.student_grade.student_score
                standard_dict[row.standard.id] = [
                    max_score, student_score, row.standard.reference_number,
                    row.standard.short_name
                ]
        else:
            standard_dict[row.standard.id] = [
                row.grade.score, row.student_grade.student_score,
                row.standard.reference_number, row.standard.short_name
            ]

    i = 0
    #set up the 2D list of Standard Averages
    for standard in sorted(standard_dict.keys()):
        standard_ref_list.append(standard_dict[standard][2])
        standard_table.append([])
        current_avg = (standard_dict[standard][1] /
                       standard_dict[standard][0]) * 100
        if minimum > current_avg:
            minimum = current_avg
        #int/round was here
        standard_table[i].append(standard_dict[standard][3] + ": " + format(
            (standard_dict[standard][1] / standard_dict[standard][0]) *
            100, '.2f') + "%")
        #int/round was here
        standard_averages[0].append(
            (standard_dict[standard][1] / standard_dict[standard][0]) * 100)

        for grade in grade_standard_dict.keys():
            for standardId in grade_standard_dict[grade][1]:
                if (standardId == standard):
                    standard_table[i].append(
                        grade_standard_dict[grade][0] + ":" +
                        format((grade_student_dict[grade][1] /
                                grade_student_dict[grade][0]) * 100, '.2f') +
                        "%")
        i += 1
    sorted(standard_table, key=lambda l: l[0])
    '''---Graph---'''
    drawing = Drawing(600, 200)
    data = standard_averages
    bc = VerticalBarChart()

    #location in the document (x,y)
    bc.x = 10
    bc.y = 30

    #width and height of the graph
    bc.height = 225
    bc.width = 400
    bc.data = data
    bc.categoryAxis.drawGridLast = True
    bc.categoryAxis.gridStart = 0
    bc.categoryAxis.gridStrokeLineCap = 2
    bc.categoryAxis.gridEnd = 3
    #bc.barLabels =

    #Update colors of the bars in the graph
    bc.bars.symbol = ShadedRect()
    bc.bars.symbol.fillColorStart = colors.lightblue
    bc.bars.symbol.fillColorEnd = colors.lightblue
    bc.bars.symbol.strokeWidth = 0

    #this draws a line at the top of the graph to close it.
    bc.strokeColor = colors.black

    #Y-axis min, max, and steps.
    if minimum != 100:
        bc.valueAxis.valueMin = minimum - 10
    else:
        bc.valueAxis.valueMin = 50
    bc.valueAxis.valueMax = 100
    bc.valueAxis.valueStep = 5

    #where to anchor the origin of the graph
    bc.categoryAxis.labels.boxAnchor = 'ne'

    #Locations of labels for the X-axis
    bc.categoryAxis.labels.dx = 2
    bc.categoryAxis.labels.dy = -2

    bc.barLabels.nudge = -10
    bc.barLabelFormat = '%.2f%%'
    bc.barLabels.dx = 0
    bc.barLabels.dy = 0
    #The angle of the lables for the X-axis
    bc.categoryAxis.labels.angle = 30
    #List of the categories to place on the X-axis
    bc.categoryAxis.categoryNames = standard_ref_list
    drawing.add(bc)
    '''------'''
    '''--Graph Legend--'''
    #Graph Legend
    legend = Legend()
    legend.alignment = 'right'
    legend.x = 420
    legend.y = 150
    legend.deltax = 60
    legend.dxTextSpace = 10
    legend.columnMaximum = 4

    legend.colorNamePairs = [(colors.lightblue, 'grade average')]
    drawing.add(legend, 'legend')
    drawing_title = "Bar Graph"

    Story.append(drawing)
    Story.append(Spacer(1, 15))
    #LineGraph Title
    ptext = '<font size=15><b>Class Performance by Assignment</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1, 30))
    '''
    Line Plot Graph ------
    '''
    assignment_data_all = [[], []]
    for key in assignment_dict.keys():
        assignment_data_all[0].append(assignment_dict[key][2])
        assignment_data_all[1].append(assignment_dict[key][1])
    drawing2 = Drawing(600, 200)
    data2 = assignment_data_all
    #lp = LinePlot()

    #data[0] = preprocessData(data[0])
    lp = HorizontalLineChart()
    lp.x = -20
    lp.y = 0
    lp.height = 225
    lp.width = 500
    lp.data = data2
    lp.joinedLines = 1
    lp.lines.symbol = makeMarker('FilledCircle')
    lp.lines[0].strokeColor = colors.grey
    lp.lines[1].strokeColor = colors.lightblue
    lp.strokeColor = colors.black
    lp.categoryAxis.labels.fontSize = 7
    lp.categoryAxis.categoryNames = assignment_names
    lp.categoryAxis.labels.boxAnchor = 'ne'
    lp.categoryAxis.labels.angle = 30
    lp.categoryAxis.drawGridLast = True
    #lp.categoryAxis.gridStart=0
    lp.categoryAxis.gridStrokeLineCap = 2
    #lp.categoryAxis.gridEnd=3
    #lp.categoryAxis.visibleGrid           = 1
    lp.valueAxis.visibleGrid = 1
    lp.valueAxis.visible = 1
    lp.valueAxis.drawGridLast = False
    #lp.valueAxis.gridStart = 0
    #lp.valueAxis.gridEnd = 100
    lp.valueAxis.gridStrokeColor = colors.black
    lp.valueAxis.valueMin = 0
    lp.valueAxis.valueMax = 105
    lp.valueAxis.valueStep = 10
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.fillColor = colors.white
    drawing2.add(lp)

    legend = Legend()
    legend.alignment = 'right'
    legend.x = 482
    legend.y = 150
    legend.deltax = 60
    legend.dxTextSpace = 2
    legend.colorNamePairs = [(colors.lightblue, 'Student'),
                             (colors.grey, 'Class')]
    drawing2.add(legend, 'legend')

    Story.append(drawing2)
    Story.append(Spacer(1, 30))
    ptext = '<font size=15><b>Assignments by Standard</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1, 10))
    t = Table(standard_table)
    t.setStyle(
        t.setStyle(
            TableStyle([
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 7),
                ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey),
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ])))
    Story.append(t)
    #build PDF document and return it
    doc.build(Story)
    pdf = buff.getvalue()
    buff.close()
    return pdf
Пример #44
0
def run(self):
    def weight_sort(a, b):
        return cmp(a.getWeight(), b.getWeight())
        
    drawing = Drawing(600, 300)
    lc = LinePlot()
     
    # Determine axis dimensions and create data set
    maxval = 0
    minval = 0    
    dimension_one_values = []
    dimension_two_values = []
    dimension_one_answeroptions_as_objects = []
    dimension_two_answeroptions_as_objects = []
    counter = 0
    for question in self.getQuestions():        
        weights = [int(weight) for weight in question.getAnswerOptionsWeights()]
        answeroptions = list(question.getAnswerOptions())

        # This is used by the legend. Sort on weight.
        if counter == 0:
            dimension_one_answeroptions_as_objects = question.getAnswerOptionsAsObjects()
            dimension_one_answeroptions_as_objects.sort(weight_sort)
        else:
            dimension_two_answeroptions_as_objects = question.getAnswerOptionsAsObjects()
            dimension_two_answeroptions_as_objects.sort(weight_sort)

        # Minmax
        lmin = min(weights)
        lmax = max(weights)
        if lmin < minval:
            minval = lmin
        if lmax > maxval:
            maxval = lmax
        
        # Data
        for user, answer in question.answers.items():
            value = answer.get('value', None)            
            weight = None
            if value is not None:                
                # Lookup the integer weight of this answer
                if value in answeroptions:
                    index = answeroptions.index(value)
                    weight = weights[index]
            # Always add to the list. ReportLab deals with None.    
            if counter == 0:
                dimension_one_values.append(weight)
            else:
                dimension_two_values.append(weight)
                
        counter += 1

    # Set minmax
    absmax = max(abs(minval), abs(maxval)) * 1.1    
    lc.xValueAxis.valueMin = -absmax
    lc.xValueAxis.valueMax = absmax    
    lc.yValueAxis.valueMin = -absmax
    lc.yValueAxis.valueMax = absmax
       
    # Zip to create data
    data = [zip(dimension_one_values, dimension_two_values)]
    if not len(data[0]):
        return
    
    lc.x = 0
    lc.y = 0
    # Misc setup
    lc.height = 300
    lc.width = 300
    lc.data = data
    lc.joinedLines = 0
    lc.fillColor = None
    lc.lines[0].strokeColor = colors.red
    lc.lines[0].symbol = makeMarker('FilledCircle')

    # Add a grid
    grid = DoubleGrid()
    lc.background = grid
    setupGrid(lc)    
    lc.background = None
    # Finetune the grid
    grid.grid0.strokeWidth = 0.2
    grid.grid1.strokeWidth = 0.2
    # Add to drawing else it overwrites the center Y axis
    drawing.add(grid)
   
    # Add a Y axis to pass through the origin
    yaxis = YValueAxis()
    yaxis.setPosition(lc.width/2, 0, lc.height)
    yaxis.configure([(0,-absmax),(0,absmax)])
    yaxis.strokeColor = colors.blue
    drawing.add(yaxis)

    # Color X-Axis
    lc.xValueAxis.strokeColor = colors.green

    drawing.add(lc)

    # Legend for Dimension One
    drawing.add(String(lc.width+20, lc.height-12, 'Dimension One (X-Axis):', 
        fontName='Helvetica', fontSize=12, fillColor=colors.green))
    legend = Legend()
    legend.alignment = 'right'
    legend.x = lc.width + 20
    legend.y = lc.height - 20
    legend.fontName = 'Helvetica'
    legend.fontSize = 12
    legend.columnMaximum = 7
    items = []
    for ob in dimension_one_answeroptions_as_objects:
        items.append( ( StringWidget(ob.getWeight()), ob() ) )
    legend.colorNamePairs = items
    drawing.add(legend, 'legend1')

    # Legend for Dimension Two
    drawing.add(String(lc.width+20, lc.height/2-12, 'Dimension Two (Y-Axis):', 
        fontName='Helvetica', fontSize=12, fillColor=colors.blue))
    legend = Legend()
    legend.alignment = 'right'
    legend.x = lc.width + 20
    legend.y = lc.height/2 - 20
    legend.fontName = 'Helvetica'
    legend.fontSize = 12
    legend.columnMaximum = 7
    items = []
    for ob in dimension_two_answeroptions_as_objects:
        items.append( ( StringWidget(ob.getWeight()), ob() ) )
    legend.colorNamePairs = items
    drawing.add(legend, 'legend2')

    # Write out
    data = drawing.asString('png')
    request = self.REQUEST
    response = request.RESPONSE
    response.setHeader('Content-Type', 'image/png')
    response.setHeader('Content-Disposition','inline; filename=%s.png' % self.getId())
    response.setHeader('Content-Length', len(data))           
    response.setHeader('Cache-Control', 's-maxage=0')
    
    return data
drawing = Drawing(400, 200)

data = [
    ((1,1), (2,2), (2.5,1), (3,3), (4,5)),
    ((1,2), (2,3), (2.5,2), (3.5,5), (4,6))
]

lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
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)

draw(drawing, 'LinePlot sample')
 def __init__(self,width=200,height=150,*args,**kw):
     Drawing.__init__(self,width,height,*args,**kw)
     self._add(self,LinePlot(),name='chart',validate=None,desc="The main chart")
     self.chart.width      = 115
     self.chart.height     = 80
     self.chart.x          = 30
     self.chart.y          = 40
     self.chart.lines[0].strokeColor = color01
     self.chart.lines[1].strokeColor = color02
     self.chart.lines[2].strokeColor = color03
     self.chart.lines[3].strokeColor = color04
     self.chart.lines[4].strokeColor = color05
     self.chart.lines[5].strokeColor = color06
     self.chart.lines[6].strokeColor = color07
     self.chart.lines[7].strokeColor = color08
     self.chart.lines[8].strokeColor = color09
     self.chart.lines[9].strokeColor = color10
     self.chart.lines[0].symbol = makeMarker('FilledSquare')
     self.chart.lines[1].symbol = makeMarker('FilledDiamond')
     self.chart.lines[2].symbol = makeMarker('FilledStarFive')
     self.chart.lines[3].symbol = makeMarker('FilledTriangle')
     self.chart.lines[4].symbol = makeMarker('FilledCircle')
     self.chart.lines[5].symbol = makeMarker('FilledPentagon')
     self.chart.lines[6].symbol = makeMarker('FilledStarSix')
     self.chart.lines[7].symbol = makeMarker('FilledHeptagon')
     self.chart.lines[8].symbol = makeMarker('FilledOctagon')
     self.chart.lines[9].symbol = makeMarker('FilledCross')
     self.chart.fillColor       = backgroundGrey
     self.chart.lineLabels.fontName              = 'Helvetica'
     self.chart.xValueAxis.labels.fontName       = 'Helvetica'
     self.chart.xValueAxis.labels.fontSize       = 7
     self.chart.xValueAxis.forceZero             = 0
     self.chart.data             = [((0, 50), (100,100), (200,200), (250,210), (300,300), (400,500)), ((0, 150), (100,200), (200,300), (250,200), (300,400), (400, 600))]
     self.chart.xValueAxis.avoidBoundFrac           = 1
     self.chart.xValueAxis.gridEnd                  = 115
     self.chart.xValueAxis.tickDown                 = 3
     self.chart.xValueAxis.visibleGrid              = 1
     self.chart.yValueAxis.tickLeft              = 3
     self.chart.yValueAxis.labels.fontName       = 'Helvetica'
     self.chart.yValueAxis.labels.fontSize       = 7
     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, 'Widgets'), (color02, 'Sprockets')]
     self.Legend.fontName       = 'Helvetica'
     self.Legend.fontSize       = 7
     self.Legend.x              = 153
     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._add(self,Label(),name='XLabel',validate=None,desc="The label on the horizontal axis")
     self.XLabel.fontName       = 'Helvetica'
     self.XLabel.fontSize       = 7
     self.XLabel.x              = 85
     self.XLabel.y              = 10
     self.XLabel.textAnchor     ='middle'
     self.XLabel.maxWidth       = 100
     self.XLabel.height         = 20
     self.XLabel._text          = "X Axis"
     self._add(self,Label(),name='YLabel',validate=None,desc="The label on the vertical axis")
     self.YLabel.fontName       = 'Helvetica'
     self.YLabel.fontSize       = 7
     self.YLabel.x              = 12
     self.YLabel.y              = 80
     self.YLabel.angle          = 90
     self.YLabel.textAnchor     ='middle'
     self.YLabel.maxWidth       = 100
     self.YLabel.height         = 20
     self.YLabel._text          = "Y Axis"
     self.chart.yValueAxis.forceZero           = 1
     self.chart.xValueAxis.forceZero           = 1
     self._add(self,0,name='preview',validate=None,desc=None)
Пример #47
0
    def __init__(self):
        LinePlot.__init__(self)
        self.width = 142
        self.height = 77
        self.outerBorderOn = 1
        self.outerBorderColor = colors.black
        self.background = None

        _labelOffset = 3
        _axisTickLengths = 2
        _axisStrokeWidth = 0.5

        self.yValueAxis.valueMin = None
        self.yValueAxis.valueMax = None
        self.yValueAxis.valueStep = None
        self.yValueAxis.labelTextFormat  = '%s'

        self.xLabel="X Lable"
        self.xValueAxis.labels.fontSize = 6

        self.yLabel="Y Lable"
        self.yValueAxis.labels.fontSize = 6

        self.data =[((0.030, 62.73),
                     (0.074, 54.363),
                     (1.216, 17.964)),

                     ((1.360, 11.621),
                     (1.387, 50.011),
                     (1.428, 68.953)),

                     ((1.444, 86.888),
                     (1.754, 35.58),
                     (1.766, 36.05))]

        #values for lineplot
        self.joinedLines = 0
        self.fillColor = self.background

        self.leftPadding=5
        self.rightPadding=10
        self.topPadding=5
        self.bottomPadding=5

        self.x = self.leftPadding+_axisTickLengths+(_labelOffset*2)
        self.x=self.x+_maxWidth(str(self.yValueAxis.valueMax), self.yValueAxis.labels.fontName, self.yValueAxis.labels.fontSize)
        self.y = self.bottomPadding+_axisTickLengths+_labelOffset+self.xValueAxis.labels.fontSize

        self.xValueAxis.labels.dy = -_labelOffset
        self.xValueAxis.tickDown = _axisTickLengths
        self.xValueAxis.strokeWidth = _axisStrokeWidth
        self.xValueAxis.rangeRound='both'
        self.yValueAxis.labels.dx = -_labelOffset
        self.yValueAxis.tickLeft = _axisTickLengths
        self.yValueAxis.strokeWidth = _axisStrokeWidth
        self.yValueAxis.rangeRound='both'

        self.lineLabelFormat="%.2f"
        self.lineLabels.fontSize = 5
        self.lineLabels.boxAnchor = 'e'
        self.lineLabels.dx             = -2
        self.lineLabelNudge = 0
        self.lines.symbol=makeMarker('FilledCircle',size=3)
        self.lines[1].symbol=makeMarker('FilledDiamond',size=3)
        self.lines[2].symbol=makeMarker('FilledSquare',size=3)
        self.lines[2].strokeColor = colors.green
Пример #48
0
  def make_graphs(self,canvas=None,left_margin=None):#text=None):
    from reportlab.graphics import renderPDF
    from reportlab.lib.pagesizes import letter
    from reportlab.graphics.shapes import Drawing,String
    from reportlab.graphics.charts.legends import Legend
    from reportlab.graphics.charts.lineplots import LinePlot
    from reportlab.graphics.widgets.markers import makeMarker
    from reportlab.lib import colors
    from reportlab.lib.units import inch
    #help(colors)

    self.framework = {4:dict(status=SpotClass.SPINDLE,color=colors.black),
                      5:dict(status=SpotClass.OVERLAP,color=colors.limegreen),
                      6:dict(status=SpotClass.OUTLIER,color=colors.greenyellow),
                      7:dict(status=SpotClass.ICE,color=colors.skyblue),
    }


    # set size and position
    width,height = letter
    #letter_landscape = (width,height)
    plot_dim = 3.0*inch

    # construct scatter plot
    plot_dxdy_pos = (left_margin*inch,height - plot_dim - 0.5*inch)
    plot_dxdy = LinePlot()
    plot_dxdy.data = self.plot_dxdy_data

    std_colors = {0:colors.darkred, 1:colors.red, 2:colors.salmon}
    for key in std_colors.keys():
      plot_dxdy.lines[key].strokeColor = None
      plot_dxdy.lines[key].symbol = makeMarker('Circle')
      plot_dxdy.lines[key].symbol.strokeColor = None
      plot_dxdy.lines[key].symbol.fillColor = std_colors[key]
      plot_dxdy.lines[key].symbol.size = 1.2

    for key in self.framework.keys():
      plot_dxdy.lines[key].strokeColor = None
      plot_dxdy.lines[key].symbol = makeMarker('Circle')
      plot_dxdy.lines[key].symbol.strokeColor = None
      plot_dxdy.lines[key].symbol.fillColor = self.framework[key]["color"]
      plot_dxdy.lines[key].symbol.size = 1.2

    plot_dxdy.lines[3].strokeColor = None
    plot_dxdy.lines[3].symbol = makeMarker('Circle')
    plot_dxdy.lines[3].symbol.strokeColor = colors.blue
    plot_dxdy.lines[3].symbol.fillColor = None
    plot_dxdy.lines[3].symbol.strokeWidth = 0.6
    plot_dxdy.lines[3].symbol.size = plot_dim*(self.sqrtr2)
    #print plot_dxdy.lines[3].symbol.getProperties()
    plot_dxdy.width = plot_dim
    plot_dxdy.height = plot_dim
    plot_dxdy.xValueAxis.valueMax = 1.0
    plot_dxdy.xValueAxis.valueMin = -1.0
    plot_dxdy.xValueAxis.joinAxis = plot_dxdy.yValueAxis
    plot_dxdy.xValueAxis.joinAxisMode = 'value'
    plot_dxdy.xValueAxis.joinAxisPos = -1.0
    plot_dxdy.yValueAxis.valueMax = 1.0
    plot_dxdy.yValueAxis.valueMin = -1.0
    d_dxdy = Drawing(plot_dim,plot_dim)
    d_dxdy.add(plot_dxdy)

    # construct cdf plot
    plot_cdf_pos = (left_margin*inch, height - 2.0*(plot_dim + 0.5*inch))
    plot_cdf = LinePlot()
    plot_cdf.data = self.plot_cdf_data
    plot_cdf.lines[0].strokeColor = colors.blue

    for key in std_colors.keys():
      plot_cdf.lines[key+1].strokeColor = None
      plot_cdf.lines[key+1].symbol = makeMarker('Circle')
      plot_cdf.lines[key+1].symbol.strokeColor = None
      plot_cdf.lines[key+1].symbol.fillColor = std_colors[key]
      plot_cdf.lines[key+1].symbol.size = 1.2

    if (len(self.plot_cdf_data) == 5):
      plot_cdf.lines[4].strokeColor = colors.green
    plot_cdf.width = plot_dim
    plot_cdf.height = plot_dim
    plot_cdf.xValueAxis.valueMax = 1.0
    plot_cdf.xValueAxis.valueMin = 0.0
    plot_cdf.yValueAxis.valueMax = 1.0
    plot_cdf.yValueAxis.valueMin = 0.0
    d_cdf = Drawing(plot_dim,plot_dim)
    d_cdf.add(plot_cdf)

    # construct pdf plot
    plot_pdf_pos = (left_margin*inch, height - 3.0*(plot_dim + 0.5*inch))
    plot_pdf = LinePlot()
    plot_pdf.data = self.plot_pdf_data
    plot_pdf.lines[1].strokeColor = colors.blue
    plot_pdf.lines[0].strokeColor = None
    plot_pdf.lines[0].symbol = makeMarker('Circle')
    plot_pdf.lines[0].symbol.strokeColor = colors.red
    plot_pdf.lines[0].symbol.size = 1
    plot_pdf.width = plot_dim
    plot_pdf.height = plot_dim
    plot_pdf.xValueAxis.valueMax = 1.0
    plot_pdf.xValueAxis.valueMin = 0.0
    d_pdf = Drawing(2*plot_dim,plot_dim)
    d_pdf.add(plot_pdf)

    # add legend
    legend = Legend()
    legend.alignment = 'right'
    legend.colorNamePairs = [(std_colors[0],'Inliers (%d'%int(self.fraction*100.0) + '% used for fit)'),
                             (std_colors[1],'Other inliers'),
                             (std_colors[2],'Outliers, reject next round'),]
    for key in self.framework.keys():
      legend.colorNamePairs.append(  (self.framework[key]["color"], "%s"%self.framework[key]["status"]  )  )

    legend.x = plot_dim - 1.0*inch
    legend.y = plot_dim
    legend.columnMaximum = 8
    d_pdf.add(legend)

    # add titles
    title_pos = (plot_dim/2.0,plot_dim + 0.25*inch)
    title_dxdy = String(title_pos[0],title_pos[1],'dx vs. dy (all)')
    title_dxdy.fontSize = 15
    title_dxdy.textAnchor = 'middle'
    d_dxdy.add(title_dxdy)
    title_cdf = String(title_pos[0],title_pos[1],'cdf (good)')
    title_cdf.fontSize = 15
    title_cdf.textAnchor = 'middle'
    d_cdf.add(title_cdf)
    title_pdf = String(title_pos[0],title_pos[1],'pdf (good)')
    title_pdf.fontSize = 15
    title_pdf.textAnchor = 'middle'
    d_pdf.add(title_pdf)

    # draw everything
    renderPDF.draw(d_dxdy,canvas,plot_dxdy_pos[0],plot_dxdy_pos[1])
    renderPDF.draw(d_cdf,canvas,plot_cdf_pos[0],plot_cdf_pos[1])
    renderPDF.draw(d_pdf,canvas,plot_pdf_pos[0],plot_pdf_pos[1])
#lc.data = [[0.7,0.1,0.5,0.2]]
datos = []
datos.append(tim_to_gray)
lc.data = datos
#lc.categoryAxis.categoryNames = ['Suspenso', 'Aprobado', 'Notable',
#                                'Sobresaliente']

lc.categoryAxis.categoryNames = imgs  #lista de las imagenes
lc.categoryAxis.labels.boxAnchor = 'n'
lc.categoryAxis.labels.angle = 90
lc.categoryAxis.labels.dy = -45
lc.valueAxis.valueMin = 0
lc.valueAxis.valueMax = 0.1
lc.valueAxis.valueStep = 0.01  # Los pasos pueden ser tambien [10, 15, 30, 35, 40]
lc.lines[0].strokeWidth = 1
lc.lines[0].symbol = makeMarker('FilledCircle')  # círculos rellenos
lc.lines[1].strokeWidth = 1.5
d.add(lc)
story.append(d)

#SEGUNDA GRAFICA
story.append(Spacer(0, inch * .50))  #Es una esecie de salto de linea
titulo = Paragraph("Tiempos de ejecución proceso calculo de histograma",
                   estilo['title'])
story.append(titulo)
story.append(Spacer(0, inch * .1))

d = Drawing(400, 200)
lc = HorizontalLineChart()
lc.x = 30
lc.y = 50
Пример #50
0
    def print_sensor_data(self, report_instance):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=20,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        # A large collection of style sheets pre-made for us
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

        style_Normal = styles["Normal"]
        style_Normal.textColor = colors.black

        style_Alerta = styles["Normal"]
        style_Alerta.textColor = colors.black

        style_Title = styles["Heading1"]
        style_Title.alignment = TA_LEFT

        style_Title_Center = styles["Heading1"]
        style_Title_Center.alignment = TA_CENTER

        # Our container for 'Flowable' objects
        elements = []

        # Saltos de linea
        saltosDeLineax1 = Paragraph("<br/>", style_Title)
        saltosDeLineax2 = Paragraph("<br/><br/>", style_Title)
        saltosDeLineax3 = Paragraph("<br/><br/><br/>", style_Title)

        # ps = ParagraphStyle('title', fontSize=20, leading=24)
        #  p1 = "here is some paragraph to see in large font"
        # Paragraph(p1, ps),

        # Tabla con reporte de incidencias y LOGOS.
        titulo_data = []
        titulo_table = []
        logo_cliente = Paragraph(
            '' + report_instance.sensor.arduino.project.enterprise.name,
            style_Normal)
        titulo_ciente = Paragraph(
            'Reporte de incidencias<br/>Sensor ' +
            report_instance.sensor.description, style_Title_Center)

        img_sensait = Image("arduino/static/sensait/logos/Sensait_logo.png")
        img_sensait.drawHeight = 8 * mm
        img_sensait.drawWidth = 20 * mm

        titulo_data.append((logo_cliente, titulo_ciente, img_sensait))

        titulo_table = Table(titulo_data,
                             colWidths=(50 * mm, 100 * mm, 50 * mm))
        titulo_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)]))
        elements.append(titulo_table)

        elements.append(saltosDeLineax2)

        resumen_data = []
        resumen_table = []

        resumen_laboratorio = Paragraph(
            '<b>Laboratorio:</b><br/>' +
            report_instance.sensor.arduino.project.name, style_Normal)
        resumen_equipo = Paragraph(
            '<b>Equipo:</b><br/>' + report_instance.sensor.arduino.name,
            style_Normal)
        resumen_serie = Paragraph(
            '<b>Modelo:</b><br/>' +
            report_instance.sensor.arduino.modelo_transmisor, style_Normal)

        resumen_data.append(
            (resumen_laboratorio, resumen_equipo, resumen_serie))

        resumen_periodo = Paragraph(
            '<b>Periodo:</b><br/>' + datetime.fromtimestamp(
                report_instance.fecha_inicial).strftime('%d/%m/%Y %H:%M:%S') +
            " al <br/>" + datetime.fromtimestamp(
                report_instance.fecha_final).strftime('%d/%m/%Y %H:%M:%S'),
            style_Normal)

        # Cantidad de Dias del reporte seleccionado.
        difEpochDias = (report_instance.fecha_final -
                        report_instance.fecha_inicial) / 86400
        periodoReporte = "Dia"

        if difEpochDias == 30:
            periodoReporte = "Mensual"
        elif difEpochDias == 15 or difEpochDias == 14:
            periodoReporte = "Quincenal"
        elif difEpochDias == 7 or difEpochDias == 6:
            periodoReporte = "Semanal"
        elif difEpochDias != 1:
            periodoReporte = str(difEpochDias) + " dias"
        else:
            periodoReporte = str(difEpochDias) + " Dia"

        resumen_rangodias = Paragraph(
            '<b>Periodo Generado:</b><br/>' + str(periodoReporte),
            style_Normal)
        resumen_void = Paragraph(" ", style_Normal)

        resumen_data.append((resumen_periodo, resumen_rangodias, resumen_void))

        # resumen_proyecto = Paragraph('<b>Proyecto:</b><br/>' + report_instance.sensor.arduino.project.name, style_Normal)
        # resumen_transmisor = Paragraph('<b>Transmisor:</b><br/>' + report_instance.sensor.arduino.name, style_Normal)
        # resumen_void = Paragraph(" ", style_Normal)

        # resumen_data.append((resumen_proyecto, resumen_transmisor, resumen_void))

        resumen_sensor = Paragraph(
            '<b>Sensor:</b><br/>' + report_instance.sensor.description,
            style_Normal)
        resumen_valmin = Paragraph(
            '<b>Valor Minimo:</b><br/>' +
            "%.2f" % report_instance.sensor.min_value, style_Normal)
        resumen_valmax = Paragraph(
            '<b>Valor Maximo:</b><br/>' +
            "%.2f" % report_instance.sensor.max_value, style_Normal)

        resumen_data.append((resumen_sensor, resumen_valmin, resumen_valmax))

        # VALORES MINIMOS Y MAXIMOS CALCULO.
        min_value = report_instance.sensor.min_value
        max_value = report_instance.sensor.max_value

        totalAlertas = 0
        promedioRegistros = 0.0
        totalRegistros = 0

        valmax = 0
        valmin = 0

        # Tabla de ejemplo
        main_table = []
        dataTable_L = []
        dataTable_R = []
        table_data = []

        all_alerts = []
        alert_list = []

        dataTable_L.append(
            ("Fecha y Hora", "Lectura", "Estado", "Numero incidencia"))
        sensorStatus = "Correcto"

        for num, data in enumerate(report_instance.sensor_data(), start=0):
            if str(data.data) != str("-127.00"):
                totalRegistros = num
                promedioRegistros += float(data.data)
                if num == 0:
                    valmin = float(data.data)
                if float(data.data) > float(max_value) or float(
                        min_value) > float(data.data):
                    sensorStatus = "Fuera de Rango"
                    alert_list.append(data)
                    totalAlertas += 1
                else:
                    sensorStatus = "Correcto"
                    if len(alert_list) > 0:
                        # print "New List " + str(len(all_alerts))
                        all_alerts.append(list(alert_list))
                        alert_list = []

                if float(data.data) > float(valmax):
                    valmax = float(data.data)
                if float(valmin) > float(data.data):
                    valmin = float(data.data)

                if len(alert_list) > 0:
                    alerta_code = "Alerta # " + str(len(all_alerts))
                else:
                    alerta_code = " "

                dataTable_L.append((datetime.fromtimestamp(
                    data.epoch).strftime('%d/%m/%Y %H:%M:%S'), data.data,
                                    sensorStatus, alerta_code))

        table_L = Table(dataTable_L, colWidths=[(doc.width) / 4.0] * 4)
        table_L.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))

        print promedioRegistros
        print totalRegistros
        if float(promedioRegistros) == 0 and float(promedioRegistros) == 0:
            val_promedio = 0
        else:
            val_promedio = float(promedioRegistros) / float(totalRegistros)

        resumen_promedio = Paragraph(
            '<b>Temperatura Promedio:</b><br/>' + "%.2f" % val_promedio,
            style_Normal)
        resumen_minima = Paragraph(
            '<b>Temperatura Minimo Registrada:</b><br/>' + "%.2f" % valmin,
            style_Normal)
        resumen_maxima = Paragraph(
            '<b>Temperatura Maxima Registrada:</b><br/>' + "%.2f" % valmax,
            style_Normal)

        resumen_data.append((resumen_promedio, resumen_minima, resumen_maxima))

        resumen_totalregistros = Paragraph(
            '<b>Total de Registros:</b><br/>' + "%.2f" % totalRegistros,
            style_Normal)
        resumen_totalfuera = Paragraph(
            '<b>Resumen Registros:</b><br/>' + "X %.2f" % totalAlertas +
            "<br/> + %.2f" % (totalRegistros - totalAlertas), style_Normal)
        resumen_alertasregistradas = Paragraph(
            '<b>Total alertas registradas:</b><br/>' + str(len(all_alerts)),
            style_Normal)
        resumen_void = Paragraph(" ", style_Normal)

        resumen_data.append((resumen_totalregistros, resumen_totalfuera,
                             resumen_alertasregistradas))

        resumen_table = Table(resumen_data,
                              colWidths=[(doc.width) / 3.0] * 3,
                              rowHeights=(16 * mm))
        resumen_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white),
                        ('VALIGN', (0, 0), (-1, -1), 'TOP')]))
        elements.append(resumen_table)

        # Informacion del reporte digamos LEGAL.
        # elements.append(Paragraph('La informacion que se despliega a continuacion son propiedad de la empresa que contrata el servicio de SENSAIT. La informacion que se despliega a continuacion son propiedad de la empresa que contrata el servicio de SENSAIT. ', styles['Normal']))

        elements.append(saltosDeLineax3)

        valores_Correctos = int(totalRegistros - totalAlertas)
        drawing = Drawing(400, 200)
        data = [(valores_Correctos, int(totalAlertas))]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 200
        bc.width = 400
        bc.data = data
        bc.barSpacing = 2.5
        bc.barWidth = 5
        bc.strokeColor = colors.black
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = int(totalRegistros)
        bc.valueAxis.valueStep = 50
        bc.categoryAxis.labels.boxAnchor = 'ne'
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        # bc.categoryAxis.labels.angle = 30
        bc.categoryAxis.categoryNames = [
            'Correctos = ' + str(valores_Correctos),
            'Fuera de Rango = ' + str(totalAlertas)
        ]
        bc.bars[(0, 0)].fillColor = colors.green
        bc.bars[(0, 1)].fillColor = colors.red
        drawing.add(bc)
        elements.append(drawing)

        elements.append(
            Paragraph(
                'Responsable ' +
                report_instance.sensor.arduino.project.nombre_encargado,
                style_Title))

        elements.append(PageBreak())

        # table_R = Table(dataTable_R, colWidths=[(doc.width) / 3.0] * 3)
        # table_R.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))

        # dataTable_Main = [table_L]  table_R
        # table_Main = Table(table_L, colWidths=[doc.width])
        # table_Main.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.red), ('BOX', (0, 0), (-1, -1), 0.25, colors.red)]))

        # Tabla con todos los registros...
        elements.append(
            Paragraph(
                str(len(all_alerts)) + ' ALERTAS REGISTRADAS',
                style_Title_Center))

        # Tablas POR ALERTA...
        alert_data_tables = []
        alerts_tables = []
        alert_content = []

        alerts_onedata_data = []
        alerts_onedata_table = []
        # print "all_alerts.len()"
        # print len(all_alerts)

        alerts_onedata_data.append(
            ("Fecha Alerta", "# Registros en alerta ", "Valor"))
        alert_max_value = float(report_instance.sensor.max_value)
        alert_min_value = float(report_instance.sensor.min_value)

        for num, alertlist in enumerate(all_alerts, start=0):
            print str(len(alertlist))
            # Esto genera la tabla para un rango de registros NO LO QUITARE jeje
            if len(alertlist) > 200:
                one_fecha = str(
                    datetime.fromtimestamp(
                        alertlist[len(alertlist) -
                                  1].epoch).strftime('%d/%m/%Y %H:%M:%S'))
                one_registros = len(alertlist)
                one_value = str(alertlist[len(alertlist) - 1].data)
                alerts_onedata_data.append(
                    (one_fecha, one_registros, one_value))
                # alerts_onedata_data.append( alertlist[num] , drawing))
            else:
                titulo = Paragraph('<b>Alerta # ' + str(num) + ' </b>',
                                   style_Normal)

                alert_data_tables = []
                alert_content = []
                alert_graph = []
                alert_limit = []
                alert_graph_dates = []

                alerta_primer_registro = Paragraph(
                    '<b>Fecha inicio alerta:</b><br/>' + str(
                        datetime.fromtimestamp(alertlist[0].epoch).strftime(
                            '%d/%m/%Y %H:%M:%S') + "<br/><br/>"), style_Normal)
                alerta_ultima_registro = Paragraph(
                    '<b>Fecha final alerta:</b><br/>' + str(
                        datetime.fromtimestamp(alertlist[len(alertlist) -
                                                         1].epoch).
                        strftime('%d/%m/%Y %H:%M:%S') + "<br/><br/>"),
                    style_Normal)
                tiempoAlerta = alertlist[0].epoch - alertlist[len(alertlist) -
                                                              1].epoch

                print "difEpoch: " + str(alertlist[len(alertlist) - 1].epoch)
                print "difEpochR: " + str(tiempoAlerta)
                print "difEpoch: " + str(alertlist[0].epoch)

                alerta_duracion = Paragraph(
                    '<b>Duracion alerta:</b><br/>' + str(
                        datetime.fromtimestamp(tiempoAlerta).strftime('%M:%S')
                        + "<br/><br/>"), style_Normal)
                alerta_total_registros = Paragraph(
                    '<b>Registros fuera de rango:</b><br/>' +
                    str(len(alertlist)) + "<br/><br/>", style_Normal)
                rango_maximo = Paragraph(
                    '<b>Valor Maximo:</b><br/>' +
                    "%.2f" % report_instance.sensor.max_value + "<br/><br/>",
                    style_Normal)
                rango_minimo = Paragraph(
                    '<b>Valor Maximo:</b><br/>' +
                    "%.2f" % report_instance.sensor.min_value + "<br/><br/>",
                    style_Normal)
                alerta_comentarios = Paragraph(
                    "<b>Comentarios:</b><br/>__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________<br/>",
                    style_Normal)
                alerta_accioncorrectiva = Paragraph(
                    "<b>Accion correctiva:</b><br/>__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________<br/>",
                    style_Normal)

                alerta_data = []
                alerta_table = []

                alerta_data.append((titulo, " "))
                alerta_data.append(
                    (alerta_primer_registro, alerta_ultima_registro))
                alerta_data.append((alerta_duracion, alerta_total_registros))
                alerta_data.append((rango_maximo, rango_minimo))
                alerta_data.append((" ", saltosDeLineax2))
                # alerta_data.append((alerta_comentarios))

                alerta_table = Table(alerta_data, colWidths=(50 * mm, 50 * mm))
                alerta_table.setStyle(
                    TableStyle([
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)
                    ]))

                # alert_content.append(alerta_primer_registro)
                # alert_content.append(alerta_ultima_registro)
                # alert_content.append(alerta_duracion)
                # alert_content.append(alerta_total_registros)
                # alert_content.append(rango_maximo)
                # alert_content.append(rango_minimo)
                # alert_content.append(alerta_comentarios)
                # alert_content.append(saltosDeLineax2)
                valMax = 0
                valMin = 0
                valTmp = 0

                for ids, alert in enumerate(alertlist, start=0):
                    # print alert.data
                    # datos = Paragraph(str(alert.data), style_Normal)
                    valTmp = float(alert.data)
                    # print "tmp: " + str(valTmp)
                    # print "max: " + str(valMax)
                    # print "min: " + str(valMin)
                    if float(valTmp >= 0):
                        if float(valTmp) > float(valMax):
                            valMax = valTmp
                            if valMin == 0:
                                valMin = float(valTmp)

                        if float(valMin) > float(valTmp):
                            valMin = float(valTmp)

                    else:
                        if float(valTmp) < float(valMax):
                            valMax = valTmp
                            if valMin == 0:
                                valMin = float(valTmp)

                        if float(valTmp) > float(valMin):
                            valMin = float(valTmp)

                    valueData = float(alert.data)

                    alert_graph.append(valueData)
                    alert_limit.append(alert_max_value)
                    alert_graph_dates.append(
                        str(
                            datetime.fromtimestamp(
                                alert.epoch).strftime('%H:%M:%S')))
                # END FOR
                print "tmp: " + str(valTmp)
                print "max: " + str(valMax)
                print "min: " + str(valMin)

                # CALCULAR BIEN LOS LIMITES DE LA GRAFICA
                if float(valMin) >= 0:
                    lim_min = float(valMin - 1)

                elif float(valMax) >= 0:
                    lim_max = float(valMax + 2)

                elif float(valMax) < 0:
                    lim_max = float(valMax - 2)

                elif float(valMin) < 0:
                    lim_min = float(valMin - 1)
                # END CALCULAR LIMITES

                lim_min = valMin
                lim_max = valMax

                print "lim_min: " + str(lim_min)
                print "lim_max: " + str(lim_max)

                drawing = Drawing(200, 220)
                data = [alert_graph, alert_limit]
                lc = HorizontalLineChart()
                lc.x = 10
                lc.y = 30
                lc.height = 150
                lc.width = 220
                lc.data = data
                # lc.strokeColor = colors.black
                catNames = alert_graph_dates
                lc.categoryAxis.categoryNames = catNames
                lc.categoryAxis.labels.dx = 0
                lc.categoryAxis.labels.dy = -15
                lc.categoryAxis.labels.angle = 75
                lc.categoryAxis.labels.boxAnchor = 'n'
                lc.joinedLines = 1
                lc.lines[0].symbol = makeMarker('FilledCircle')
                # lc.lineLabelFormat = '%2.0f'
                # lc.strokeColor = colors.black
                lc.valueAxis.valueMin = lim_min
                lc.valueAxis.valueMax = lim_max
                lc.valueAxis.valueStep = 1
                lc.lines[0].strokeWidth = 2
                # lc.lines[1].strokeWidth = 1.5
                drawing.add(lc)

                # print "endFor"

                alert_data_tables.append((drawing, alerta_table))
                alert_data_tables.append(
                    (alerta_comentarios, alerta_accioncorrectiva))

                alerts_tables = Table(alert_data_tables,
                                      colWidths=[(doc.width) / 2.0] * 2)
                alerts_tables.setStyle(
                    TableStyle([
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)
                    ]))
                elements.append(alerts_tables)

                # elements.append(PageBreak())

        if len(alerts_onedata_data) > 1:

            elements.append(
                Paragraph('ALERTAS CON 5 REGISTROS O MENOS',
                          style_Title_Center))
            elements.append(saltosDeLineax1)
            alerts_onedata_table = Table(alerts_onedata_data,
                                         colWidths=[(doc.width) / 3.0] * 3)
            alerts_onedata_table.setStyle(
                TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25,
                             colors.black),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))
            elements.append(alerts_onedata_table)
            # elements.append(PageBreak())

        elements.append(PageBreak())
        elements.append(Paragraph('DETALLE DE REGISTROS', style_Title_Center))
        elements.append(table_L)
        # elements.append(table_R)

        # Se agrega el llamado del header y footer
        doc.build(elements,
                  onFirstPage=self._header_footer,
                  onLaterPages=self._header_footer,
                  canvasmaker=NumberedCanvas)
Пример #51
0
    def draw(self):
        # normalize slice data
        g = self.makeBackground() or Group()

        xradius = self.width/2.0
        yradius = self.height/2.0
        self._radius = radius = min(xradius, yradius)
        cx = self.x + xradius
        cy = self.y + yradius

        data = self.normalizeData()

        self._seriesCount = len(data)
        n = len(data[0])

        #labels
        if self.labels is None:
            labels = [''] * n
        else:
            labels = self.labels
            #there's no point in raising errors for less than enough errors if
            #we silently create all for the extreme case of no labels.
            i = n-len(labels)
            if i>0:
                labels = labels + ['']*i

        S = []
        STRANDS = []
        STRANDAREAS = []
        syms = []
        labs = []
        csa = []
        angle = self.startAngle*pi/180
        direction = self.direction == "clockwise" and -1 or 1
        angleBetween = direction*(2 * pi)/float(n)
        spokes = self.spokes
        spokeLabels = self.spokeLabels
        for i in xrange(n):
            car = cos(angle)*radius
            sar = sin(angle)*radius
            csa.append((car,sar,angle))
            si = self.spokes[i]
            if si.visible:
                spoke = Line(cx, cy, cx + car, cy + sar, strokeWidth = si.strokeWidth, strokeColor=si.strokeColor, strokeDashArray=si.strokeDashArray)
            S.append(spoke)
            sli = spokeLabels[i]
            text = sli._text
            if not text: text = labels[i]
            if text:
                S.append(_setupLabel(WedgeLabel, text, si.labelRadius, cx, cy, angle, car, sar, sli))
            angle += angleBetween

        # now plot the polygons
        rowIdx = 0
        strands = self.strands
        strandLabels = self.strandLabels
        for row in data:
            # series plot
            rsty = strands[rowIdx]
            points = []
            car, sar = csa[-1][:2]
            r = row[-1]
            points.append(cx+car*r)
            points.append(cy+sar*r)
            for i in xrange(n):
                car, sar, angle = csa[i]
                r = row[i]
                points.append(cx+car*r)
                points.append(cy+sar*r)
                L = self._innerDrawLabel(strandLabels[(rowIdx,i)], r, cx, cy, angle, car, sar, labelClass=StrandLabel)
                if L: labs.append(L)
                sty = strands[(rowIdx,i)]
                uSymbol = sty.symbol

                # put in a marker, if it needs one
                if uSymbol:
                    s_x =  cx+car*r
                    s_y = cy+sar*r
                    s_fillColor = sty.fillColor
                    s_strokeColor = sty.strokeColor
                    s_strokeWidth = sty.strokeWidth
                    s_angle = 0
                    s_size = sty.symbolSize
                    if type(uSymbol) is type(''):
                        symbol = makeMarker(uSymbol,
                                    size = s_size,
                                    x =  s_x,
                                    y = s_y,
                                    fillColor = s_fillColor,
                                    strokeColor = s_strokeColor,
                                    strokeWidth = s_strokeWidth,
                                    angle = s_angle,
                                    )
                    else:
                        symbol = uSymbol2Symbol(uSymbol,s_x,s_y,s_fillColor)
                        for k,v in (('size', s_size), ('fillColor', s_fillColor),
                                    ('x', s_x), ('y', s_y),
                                    ('strokeColor',s_strokeColor), ('strokeWidth',s_strokeWidth),
                                    ('angle',s_angle),):
                            if getattr(symbol,k,None) is None:
                                try:
                                    setattr(symbol,k,v)
                                except:
                                    pass
                    syms.append(symbol)

            # make up the 'strand'
            if rsty.fillColor:
                strand = Polygon(points)
                strand.fillColor = rsty.fillColor
                strand.strokeColor = None
                strand.strokeWidth = 0
                STRANDAREAS.append(strand)
            if rsty.strokeColor and rsty.strokeWidth:
                strand = PolyLine(points)
                strand.strokeColor = rsty.strokeColor
                strand.strokeWidth = rsty.strokeWidth
                strand.strokeDashArray = rsty.strokeDashArray
                STRANDS.append(strand)
            rowIdx += 1

        map(g.add,STRANDAREAS+STRANDS+syms+S+labs)
        return g
Пример #52
0
def getPlot():
    drawing = Drawing(400, 200)
    #temps = [((0.5,7), (1.5,1), (2.5,2), (3.5,1), (4.5,3), (5.5,5), (6.5, 10), (7.5,6))]
    temps = [getTemps()]
    bc = LinePlot()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = temps
    #labels
    yilabel = Label()
    yilabel.setText("Temperatura (°C)")
    yilabel.angle = 90
    yilabel.setOrigin(20,120)
    xlabel = Label()
    xlabel.setText("Días")
    xlabel.setOrigin(200,20)

    labelT = Label()
    labelT.setText("Temperatura")
    labelT.setOrigin(210,185)

    labelH = Label()
    labelH.setText("Humedad")
    labelH.setOrigin(285,185)


    bc.xValueAxis.valueMin = 0
    bc.xValueAxis.valueMax = 20
    bc.xValueAxis.valueSteps = [x for x in range(1,bc.xValueAxis.valueMax)]
    #bc.xValueAxis.labelTextFormat = '%2.1f'
    bc.yValueAxis.valueMin = 0
    bc.yValueAxis.valueMax = 60
    bc.yValueAxis.valueSteps = [0, 10, 20, 30, 40, 50, 60]
    drawing.add(bc)
    drawing.add(yilabel)
    drawing.add(xlabel)
    drawing.add(Line(170,185,185,185, strokeColor=colors.red))
    drawing.add(Line(250,185,265,185, strokeColor=colors.blue))
    drawing.add(labelT)
    drawing.add(labelH)

    #humedad=[[(0.5, 4), (1.5, 3), (2.5, 4), (3.5, 6), (4.5, 4), (5.5, 2), (6.5, 5), (7.5, 6)]]
    humedad = [getHumedad()]
    lp = LinePlot()
    lp.x = bc.x
    lp.y = bc.y
    lp.height = bc.height
    lp.width = bc.width
    lp.data = humedad

    ydlabel = Label()
    ydlabel.setText("Humedad (%)")
    ydlabel.angle = -90
    ydlabel.setOrigin(lp.x+lp.width+30,lp.y+70)

    lp.joinedLines = 1
    lp.lines[0].symbol = makeMarker('Circle')
    lp.lines[0].strokeColor=colors.blue
    lp.lineLabelFormat = '%2.0f'
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = bc.xValueAxis.valueMax
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 100
    lp.xValueAxis.visible=False
    lp.yValueAxis.visible=False #Hide 2nd plot its Yaxis
    drawing.add(lp)
    drawing.add(ydlabel)

    y2Axis = YValueAxis()#Replicate 2nd plot Yaxis in the right
    y2Axis.setProperties(lp.yValueAxis.getProperties())
    y2Axis.setPosition(lp.x+lp.width,lp.y,lp.height)
    y2Axis.tickRight=5
    y2Axis.tickLeft=0
    y2Axis.labels.dx = 20
    y2Axis.configure(humedad)
    y2Axis.visible=True
    drawing.add(y2Axis)

    return drawing
Пример #53
0
 def __init__(self, width=200, height=150, *args, **kw):
     Drawing.__init__(self, width, height, *args, **kw)
     self._add(self,
               LinePlot(),
               name='chart',
               validate=None,
               desc="The main chart")
     self.chart.width = 115
     self.chart.height = 80
     self.chart.x = 30
     self.chart.y = 40
     self.chart.lines[0].strokeColor = color01
     self.chart.lines[1].strokeColor = color02
     self.chart.lines[2].strokeColor = color03
     self.chart.lines[3].strokeColor = color04
     self.chart.lines[4].strokeColor = color05
     self.chart.lines[5].strokeColor = color06
     self.chart.lines[6].strokeColor = color07
     self.chart.lines[7].strokeColor = color08
     self.chart.lines[8].strokeColor = color09
     self.chart.lines[9].strokeColor = color10
     self.chart.lines[0].symbol = makeMarker('FilledSquare')
     self.chart.lines[1].symbol = makeMarker('FilledDiamond')
     self.chart.lines[2].symbol = makeMarker('FilledStarFive')
     self.chart.lines[3].symbol = makeMarker('FilledTriangle')
     self.chart.lines[4].symbol = makeMarker('FilledCircle')
     self.chart.lines[5].symbol = makeMarker('FilledPentagon')
     self.chart.lines[6].symbol = makeMarker('FilledStarSix')
     self.chart.lines[7].symbol = makeMarker('FilledHeptagon')
     self.chart.lines[8].symbol = makeMarker('FilledOctagon')
     self.chart.lines[9].symbol = makeMarker('FilledCross')
     self.chart.fillColor = backgroundGrey
     self.chart.lineLabels.fontName = 'Helvetica'
     self.chart.xValueAxis.labels.fontName = 'Helvetica'
     self.chart.xValueAxis.labels.fontSize = 7
     self.chart.xValueAxis.forceZero = 0
     self.chart.data = [((0, 50), (100, 100), (200, 200), (250, 210),
                         (300, 300), (400, 500)),
                        ((0, 150), (100, 200), (200, 300), (250, 200),
                         (300, 400), (400, 600))]
     self.chart.xValueAxis.avoidBoundFrac = 1
     self.chart.xValueAxis.gridEnd = 115
     self.chart.xValueAxis.tickDown = 3
     self.chart.xValueAxis.visibleGrid = 1
     self.chart.yValueAxis.tickLeft = 3
     self.chart.yValueAxis.labels.fontName = 'Helvetica'
     self.chart.yValueAxis.labels.fontSize = 7
     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, 'Widgets'),
                                   (color02, 'Sprockets')]
     self.Legend.fontName = 'Helvetica'
     self.Legend.fontSize = 7
     self.Legend.x = 153
     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._add(self,
               Label(),
               name='XLabel',
               validate=None,
               desc="The label on the horizontal axis")
     self.XLabel.fontName = 'Helvetica'
     self.XLabel.fontSize = 7
     self.XLabel.x = 85
     self.XLabel.y = 10
     self.XLabel.textAnchor = 'middle'
     self.XLabel.maxWidth = 100
     self.XLabel.height = 20
     self.XLabel._text = "X Axis"
     self._add(self,
               Label(),
               name='YLabel',
               validate=None,
               desc="The label on the vertical axis")
     self.YLabel.fontName = 'Helvetica'
     self.YLabel.fontSize = 7
     self.YLabel.x = 12
     self.YLabel.y = 80
     self.YLabel.angle = 90
     self.YLabel.textAnchor = 'middle'
     self.YLabel.maxWidth = 100
     self.YLabel.height = 20
     self.YLabel._text = "Y Axis"
     self.chart.yValueAxis.forceZero = 1
     self.chart.xValueAxis.forceZero = 1
     self._add(self, 0, name='preview', validate=None, desc=None)
Пример #54
0
#每一个数据点是一个元组
#一条曲线对应一个存储数据点元组的元组
#一个图形可以包含多条曲线,用列表存储曲线元组
data = [((1, 100), (2, 200), (3, 300), (4, 400), (5, 500)),
        ((1, 50), (2, 80), (3, 400), (4, 40), (5, 70))]

drawing = Drawing(500, 300)

lp = LinePlot()
lp.x = 50  #坐标轴中心坐标
lp.y = 30
lp.height = 250
lp.width = 400
lp.data = data
lp.joinedLines = 1
lp.lines.symbol = makeMarker('FilledCircle')

lp.xValueAxis.valueMin = 1
lp.xValueAxis.valueMax = 5
lp.xValueAxis.valueStep = 1

lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 500
lp.yValueAxis.valueStep = 100
drawing.add(lp)

title = Label()
#若需要显示中文,需要先注册一个中文字体
pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc"))
title.fontName = "haha"
title.fontSize = 12
Пример #55
0
def symbols(canv,data):
    '''
    produces filled symbols

    arguments
    n   number of points default 5
    x,y     initial symbol location
    dx      delta x for each new symbol
    dy      delta y for each symbol
    name    symbol name (suitable for makeMarker)
    fillColor   symbol fill colour
    strokeColor symbol stroke colour
    strokeWidth symbol stroke width
    angle   symbol angle
    '''
    args, kw = _evalArgs(data)
    if args:
        raise TypeError('Symbols takes no positional arguments')
    params = dict(
            n=5,
            x='72',
            y='72',
            dx='None',
            dy='0',
            name='StarFive',
            fillColor='yellow',
            strokeColor=None,
            strokeWidth='1',
            angle=0,
            )
    params.update(kw)

    from reportlab.graphics.shapes import Drawing
    from reportlab.graphics.widgets.markers import makeMarker
    from rlextra.rml2pdf.rml2pdf import readLengthOrNone

    name = params['name']
    n = int(params['n'])
    x0 = readLengthOrNone(params['x'])
    y0 = readLengthOrNone(params['y'])
    angle = float(params['angle'])
    size = readLengthOrNone(params['size'])
    strokeWidth = readLengthOrNone(params['strokeWidth'])
    dx = readLengthOrNone(params['dx'])
    if dx is None: dx = 2+1.5*size
    dy = readLengthOrNone(params['dy'])
    strokeColor = _toColor(params['strokeColor'])
    fillColor = _toColor(params['fillColor'])

    D = Drawing()
    for i in range(n):
        m = makeMarker(name)
        m.x = dx*i
        m.y = dy*i
        m.angle = angle
        m.size = size
        m.strokeWidth = strokeWidth
        m.strokeColor = strokeColor
        m.fillColor = fillColor
        D.add(m)

    D.drawOn(canv,x0,y0)
Пример #56
0
    def make_graphs(self, canvas=None, left_margin=None):  #text=None):
        from reportlab.graphics import renderPDF
        from reportlab.lib.pagesizes import letter
        from reportlab.graphics.shapes import Drawing, String
        from reportlab.graphics.charts.legends import Legend
        from reportlab.graphics.charts.lineplots import LinePlot
        from reportlab.graphics.widgets.markers import makeMarker
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        #help(colors)

        self.framework = {
            4: dict(status=SpotClass.SPINDLE, color=colors.black),
            5: dict(status=SpotClass.OVERLAP, color=colors.limegreen),
            6: dict(status=SpotClass.OUTLIER, color=colors.greenyellow),
            7: dict(status=SpotClass.ICE, color=colors.skyblue),
        }

        # set size and position
        width, height = letter
        #letter_landscape = (width,height)
        plot_dim = 3.0 * inch

        # construct scatter plot
        plot_dxdy_pos = (left_margin * inch, height - plot_dim - 0.5 * inch)
        plot_dxdy = LinePlot()
        plot_dxdy.data = self.plot_dxdy_data

        std_colors = {0: colors.darkred, 1: colors.red, 2: colors.salmon}
        for key in std_colors.keys():
            plot_dxdy.lines[key].strokeColor = None
            plot_dxdy.lines[key].symbol = makeMarker('Circle')
            plot_dxdy.lines[key].symbol.strokeColor = None
            plot_dxdy.lines[key].symbol.fillColor = std_colors[key]
            plot_dxdy.lines[key].symbol.size = 1.2

        for key in self.framework.keys():
            plot_dxdy.lines[key].strokeColor = None
            plot_dxdy.lines[key].symbol = makeMarker('Circle')
            plot_dxdy.lines[key].symbol.strokeColor = None
            plot_dxdy.lines[key].symbol.fillColor = self.framework[key][
                "color"]
            plot_dxdy.lines[key].symbol.size = 1.2

        plot_dxdy.lines[3].strokeColor = None
        plot_dxdy.lines[3].symbol = makeMarker('Circle')
        plot_dxdy.lines[3].symbol.strokeColor = colors.blue
        plot_dxdy.lines[3].symbol.fillColor = None
        plot_dxdy.lines[3].symbol.strokeWidth = 0.6
        plot_dxdy.lines[3].symbol.size = plot_dim * (self.sqrtr2)
        #print plot_dxdy.lines[3].symbol.getProperties()
        plot_dxdy.width = plot_dim
        plot_dxdy.height = plot_dim
        plot_dxdy.xValueAxis.valueMax = 1.0
        plot_dxdy.xValueAxis.valueMin = -1.0
        plot_dxdy.xValueAxis.joinAxis = plot_dxdy.yValueAxis
        plot_dxdy.xValueAxis.joinAxisMode = 'value'
        plot_dxdy.xValueAxis.joinAxisPos = -1.0
        plot_dxdy.yValueAxis.valueMax = 1.0
        plot_dxdy.yValueAxis.valueMin = -1.0
        d_dxdy = Drawing(plot_dim, plot_dim)
        d_dxdy.add(plot_dxdy)

        # construct cdf plot
        plot_cdf_pos = (left_margin * inch,
                        height - 2.0 * (plot_dim + 0.5 * inch))
        plot_cdf = LinePlot()
        plot_cdf.data = self.plot_cdf_data
        plot_cdf.lines[0].strokeColor = colors.blue

        for key in std_colors.keys():
            plot_cdf.lines[key + 1].strokeColor = None
            plot_cdf.lines[key + 1].symbol = makeMarker('Circle')
            plot_cdf.lines[key + 1].symbol.strokeColor = None
            plot_cdf.lines[key + 1].symbol.fillColor = std_colors[key]
            plot_cdf.lines[key + 1].symbol.size = 1.2

        if (len(self.plot_cdf_data) == 5):
            plot_cdf.lines[4].strokeColor = colors.green
        plot_cdf.width = plot_dim
        plot_cdf.height = plot_dim
        plot_cdf.xValueAxis.valueMax = 1.0
        plot_cdf.xValueAxis.valueMin = 0.0
        plot_cdf.yValueAxis.valueMax = 1.0
        plot_cdf.yValueAxis.valueMin = 0.0
        d_cdf = Drawing(plot_dim, plot_dim)
        d_cdf.add(plot_cdf)

        # construct pdf plot
        plot_pdf_pos = (left_margin * inch,
                        height - 3.0 * (plot_dim + 0.5 * inch))
        plot_pdf = LinePlot()
        plot_pdf.data = self.plot_pdf_data
        plot_pdf.lines[1].strokeColor = colors.blue
        plot_pdf.lines[0].strokeColor = None
        plot_pdf.lines[0].symbol = makeMarker('Circle')
        plot_pdf.lines[0].symbol.strokeColor = colors.red
        plot_pdf.lines[0].symbol.size = 1
        plot_pdf.width = plot_dim
        plot_pdf.height = plot_dim
        plot_pdf.xValueAxis.valueMax = 1.0
        plot_pdf.xValueAxis.valueMin = 0.0
        d_pdf = Drawing(2 * plot_dim, plot_dim)
        d_pdf.add(plot_pdf)

        # add legend
        legend = Legend()
        legend.alignment = 'right'
        legend.colorNamePairs = [
            (std_colors[0],
             'Inliers (%d' % int(self.fraction * 100.0) + '% used for fit)'),
            (std_colors[1], 'Other inliers'),
            (std_colors[2], 'Outliers, reject next round'),
        ]
        for key in self.framework.keys():
            legend.colorNamePairs.append(
                (self.framework[key]["color"],
                 "%s" % self.framework[key]["status"]))

        legend.x = plot_dim - 1.0 * inch
        legend.y = plot_dim
        legend.columnMaximum = 8
        d_pdf.add(legend)

        # add titles
        title_pos = (plot_dim / 2.0, plot_dim + 0.25 * inch)
        title_dxdy = String(title_pos[0], title_pos[1], 'dx vs. dy (all)')
        title_dxdy.fontSize = 15
        title_dxdy.textAnchor = 'middle'
        d_dxdy.add(title_dxdy)
        title_cdf = String(title_pos[0], title_pos[1], 'cdf (good)')
        title_cdf.fontSize = 15
        title_cdf.textAnchor = 'middle'
        d_cdf.add(title_cdf)
        title_pdf = String(title_pos[0], title_pos[1], 'pdf (good)')
        title_pdf.fontSize = 15
        title_pdf.textAnchor = 'middle'
        d_pdf.add(title_pdf)

        # draw everything
        renderPDF.draw(d_dxdy, canvas, plot_dxdy_pos[0], plot_dxdy_pos[1])
        renderPDF.draw(d_cdf, canvas, plot_cdf_pos[0], plot_cdf_pos[1])
        renderPDF.draw(d_pdf, canvas, plot_pdf_pos[0], plot_pdf_pos[1])
Пример #57
0
    def createTimeSeries(self,ser):
        if self.single_record:
            return
        # Time series are available for these quantities. The number indicates their position in the data string
        series = {'h':0, 'g':1, 'i10':2, 'i100':6, 'tori':3, 'Read10':7}
        # The time series plot will get added to the 'drawing' object
        drawing = Drawing(400, 200)
        # and it is of type 'LinePlot'
        lp = LinePlot()
        lp.x = 30
        lp.y = 50
        lp.height = 125
        lp.width = 350
        # Record the publication years, because these values will be used as x axis labels
        years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['metrics series'].keys())))
        lp.data = []
        series_data = []
        # The maximum value will be used to scale the y axis
        max_value = 0
        # This list will hold the data points for the histogram
        for year in years:
            values = map(lambda a: float(a),self.data['metrics series'][str(year)].split(':'))
            max_value = max(max_value,values[series[ser]])
            if ser == 'read10' and year > 1995:
                series_data.append((year,values[series[ser]]))
            else:
                series_data.append((year,values[series[ser]]))

        lp.data.append(series_data)
        lp.joinedLines = 1
        # Define the line color
        lp.lines[0].strokeColor = colors.orange
        # Actual data point will be marked by a filled circle
        lp.lines.symbol = makeMarker('FilledCircle')
        lp.strokeColor = colors.black
        # The extreme values for the x axis
        lp.xValueAxis.valueMin = years[0]
        lp.xValueAxis.valueMax = years[-1]
        # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly
        lp.xValueAxis.labels.dx = -6
        lp.xValueAxis.labels.dy = -18
        # and rotate the labels by 90 degrees
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.valueSteps = years
        # For both axes values will be displayed as integers
        lp.xValueAxis.labelTextFormat = '%2.0f'
        lp.yValueAxis.labelTextFormat = '%2.0f'
        # Define the maximum value of the y axis
        lp.yValueAxis.valueMax = int(math.ceil(float(max_value)/10.0))*10
        # Depending on the range of values, set a value step for the y axis
        if max_value > 10000:
            lp.yValueAxis.valueStep = 1000
        elif max_value > 1000:
            lp.yValueAxis.valueStep = 100
        else:
            lp.yValueAxis.valueStep = 10
        # The y axis always starts at 0
        lp.yValueAxis.valueMin = 0
        # Now add the line plot to the 'drawing' object
        drawing.add(lp)
        # Finally add the appropriate title to the plot
        drawing.add(String(200,190,"%s index time series" % ser, textAnchor="middle", fillColor='blue'))
        # Append the result to the 'story'
        self.story.append(drawing)
Пример #58
0
    def __init__(self):
        LinePlot.__init__(self)
        self.width = 142
        self.height = 77
        self.outerBorderOn = 1
        self.outerBorderColor = colors.black
        self.background = None

        _labelOffset = 3
        _axisTickLengths = 2
        _axisStrokeWidth = 0.5

        self.yValueAxis.valueMin = None
        self.yValueAxis.valueMax = None
        self.yValueAxis.valueStep = None
        self.yValueAxis.labelTextFormat  = '%s'

        self.xLabel="X Lable"
        self.xValueAxis.labels.fontSize = 6

        self.yLabel="Y Lable"
        self.yValueAxis.labels.fontSize = 6

        self.data =[((0.030, 62.73),
                     (0.074, 54.363),
                     (1.216, 17.964)),

                     ((1.360, 11.621),
                     (1.387, 50.011),
                     (1.428, 68.953)),

                     ((1.444, 86.888),
                     (1.754, 35.58),
                     (1.766, 36.05))]

        #values for lineplot
        self.joinedLines = 0
        self.fillColor = self.background

        self.leftPadding=5
        self.rightPadding=10
        self.topPadding=5
        self.bottomPadding=5

        self.x = self.leftPadding+_axisTickLengths+(_labelOffset*2)
        self.x=self.x+_maxWidth(str(self.yValueAxis.valueMax), self.yValueAxis.labels.fontName, self.yValueAxis.labels.fontSize)
        self.y = self.bottomPadding+_axisTickLengths+_labelOffset+self.xValueAxis.labels.fontSize

        self.xValueAxis.labels.dy = -_labelOffset
        self.xValueAxis.tickDown = _axisTickLengths
        self.xValueAxis.strokeWidth = _axisStrokeWidth
        self.xValueAxis.rangeRound='both'
        self.yValueAxis.labels.dx = -_labelOffset
        self.yValueAxis.tickLeft = _axisTickLengths
        self.yValueAxis.strokeWidth = _axisStrokeWidth
        self.yValueAxis.rangeRound='both'

        self.lineLabelFormat="%.2f"
        self.lineLabels.fontSize = 5
        self.lineLabels.boxAnchor = 'e'
        self.lineLabels.dx             = -2
        self.lineLabelNudge = 0
        self.lines.symbol=makeMarker('FilledCircle',size=3)
        self.lines[1].symbol=makeMarker('FilledDiamond',size=3)
        self.lines[2].symbol=makeMarker('FilledSquare',size=3)
        self.lines[2].strokeColor = colors.green
Пример #59
0
def genLPDrawing(data, data_note, width=letter[0]*0.8, height=letter[1]*0.25, timeAxis='day', y_min_zero=False):
    """
    函数功能:生成Drawing之用
    :return:
    """

    drawing = Drawing(width=width, height=height)

    lp = LinePlot()
    # lp.x = 50
    # lp.y = 50
    lp.height = height
    lp.width = width
    lp.data = data
    lp.joinedLines = 1

    # 定义颜色集
    barFillColors = [
        colors.red, colors.green, colors.blue, colors.darkgoldenrod,
        colors.pink, colors.purple, colors.lightgreen, colors.darkblue, colors.lightyellow,
        colors.fidred, colors.greenyellow, colors.gray, colors.white,colors.blueviolet, colors.lightgoldenrodyellow]

    for i in range(0, len(data)):
        lp.lines[i].name = data_note[i]
        lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5)
        lp.lines[i].strokeWidth = 0.2
        lp.lines[i].strokeColor = barFillColors[i]

    # lp.lineLabelFormat = '%2.0f'
    # lp.strokeColor = colors.black

    x_min = data[0][0][0]
    x_max = data[0][-1][0]

    lp.xValueAxis.valueMin = x_min
    lp.xValueAxis.valueMax = x_max

    if timeAxis=='day':
        step = int(((x_max - x_min) / (60 * 60 * 24)) / 30) + 1

        lp.xValueAxis.valueSteps = [n for n in range(int(x_min), int(x_max), 60 * 60 * 24 * step)]
        lp.xValueAxis.labelTextFormat = lambda x: str(Sec2Datetime(x)[0:10])
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.labels.fontSize = 6
        lp.xValueAxis.labels.dy = -18
        if y_min_zero:
            lp.yValueAxis.valueMin = 0

        # lp.yValueAxis.valueMax = 50
        # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]

    elif timeAxis=='quarter':

        step = int(((x_max - x_min)/0.25) / 30) + 1

        lp.xValueAxis.valueSteps = [n for n in range(int(x_min), int(x_max), int(math.ceil(0.25 * step)))]
        lp.xValueAxis.labelTextFormat = lambda x: convertValue2Quarter(x)
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.labels.fontSize = 6
        lp.xValueAxis.labels.dy = -18

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

    elif timeAxis=='year':

        lp.xValueAxis.valueSteps = [n for n in range(int(x_min), int(x_max), 1)]
        lp.xValueAxis.labelTextFormat = lambda x: str(x)
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.labels.fontSize = 6
        lp.xValueAxis.labels.dy = -18

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

    elif timeAxis=='month':

        lp.xValueAxis.valueSteps = list(map(lambda x:x[0],data[0]))
        lp.xValueAxis.labelTextFormat = lambda x: str(Sec2Datetime(x))[0:7]
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.labels.fontSize = 6
        lp.xValueAxis.labels.dy = -18

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

    drawing.add(lp)
    add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-20)

    return drawing
Пример #60
0
    def stackedGraphs(self,lxydata,tmin=None,tmax=None): # list of (label, [x,yarr]) with x in seconds

        lcheight = 125
        lcwidth = self.PAGE_WIDTH-280
        graphsinchart = self.maxnumgraphsinchart
        stacks = (len(lxydata)/graphsinchart)
        if len(lxydata)%graphsinchart>0:
            stacks +=1
        drawing = Drawing(lcwidth+130, stacks*lcheight+75)
        ix = 0
        for ix in range(0,len(lxydata),graphsinchart):
            subset=lxydata[ix:min(ix+graphsinchart,len(lxydata))]
            maxX = subset[0][1][0][0]
            maxY = 1.
            minX = maxX
            minY = -1
            for label,xyarr in subset:
                xarr = [x for (x,y) in xyarr]
                yarr = [y for (x,y) in xyarr]
                maxY = max(maxY, max(yarr))
                minY = min(minY, min(yarr))
                maxX = max(maxX, max(xarr))
                minX = min(minX, min(xarr))
            if not tmin is None:
                minX = tmin
            if not tmax is None:
                maxX = tmax
            subset.append(('CritMax',[[minX,1.],[maxX,1.]]))
            subset.append(('CritMin',[[minX,-1.],[maxX,-1.]]))
            lc = LinePlot()
            lc.x = 30
            lc.y = 50+lcheight*ix/graphsinchart
            lc.height = (lcheight-10)
            lc.width = lcwidth
            lc.data = [xy for (l,xy) in subset]
            datalabels = [ l for (l,xy) in subset]

            lc.xValueAxis.valueMin = minX
            lc.xValueAxis.valueMax = maxX
            lc.xValueAxis.valueStep = int((maxX-minX)/5)
            if ix == 0:
                lc.xValueAxis.labelTextFormat = dateformatter # Use the formatter
            else:
                lc.xValueAxis.labelTextFormat = emptyformatter # Use the formatter
            lc.xValueAxis.visibleGrid           = True
            lc.xValueAxis.gridStrokeWidth = .5
            lc.xValueAxis.gridStrokeColor = colors.darkgrey
            lc.xValueAxis.subTickNum = 1
            lc.xValueAxis.subGridStrokeWidth = .25
            lc.xValueAxis.subGridStrokeColor = colors.lightgrey
            lc.xValueAxis.visibleSubGrid = True

            lc.yValueAxis.valueMin = minY
            lc.yValueAxis.valueMax = maxY
            lc.yValueAxis.valueStep = .25
            if (maxY-minY)>2:
                lc.yValueAxis.valueStep = .5
            if (maxY-minY)>4:
                lc.yValueAxis.valueStep = 1.
            lc.yValueAxis.visibleGrid           = True
            lc.yValueAxis.gridStrokeWidth = .5
            lc.yValueAxis.gridStrokeColor = colors.darkgrey
            lc.yValueAxis.subTickNum = 1
            lc.yValueAxis.subGridStrokeWidth = .25
            lc.yValueAxis.subGridStrokeColor = colors.lightgrey
            lc.yValueAxis.visibleSubGrid = True

            for x in range(len(lc.data)):
                lc.lines[x].strokeColor = self.colors[x]
                lc.lines[x].name = datalabels[x]
                if len(lc.data[x]) ==1:
                    lc.lines[x].symbol = makeMarker('FilledCircle') # added to make filled circles.
                lc.lines[x].strokeWidth = 2
                if lc.lines[x].name == 'CritMin' or lc.lines[x].name == 'CritMax': # distinguish min/max
                    lc.lines[x].strokeColor = self.colors[0]
                    lc.lines[x].strokeDashArray = (5, 1)

            self.addLabels(drawing,ylabel="geschaalde waarde")
            drawing.add(lc)
            ix += 1

            drawing.add(self.addAutoLegend(lc,(lc.x,lc.y,lc.width,lc.height),len(lc.data),side='right'))
        return drawing