def recommend(self, howMany):
	userKnownLanguages = {}
	for button in self.buttons:
		if(button.clicked == True):
			if button.t not in userKnownLanguages:
				userKnownLanguages[button.t] = 1

	topicOfChoice = ""
	# Grab the topic the user selected
	try:
		index = self.listbox.curselection()[0]
		topicOfChoice = self.listbox.get(index)
	except IndexError:
		pass
        
	nearestCluster = classifier.nearest(userKnownLanguages, self.indexByTopic)
	for frame in self.frames:
		frame.pack_forget()
        self.displayRecommendations(topicOfChoice, userKnownLanguages)
        data = classifier.difference(self.indexByTopic[nearestCluster]['languages'], userKnownLanguages)
        labels,d1 =zip(*data)
        d = Drawing(300,200)
        chart = VerticalBarChart()
        chart.width = 260
        chart.height = 160
        chart.x = 20
        chart.y = 10
        chart.data = [d1]
        chart.categoryAxis.categoryNames = labels
        d.add(chart)
        d.save(formats=['pdf'],outDir='.',fnRoot='graph')
        os.system('open graph.pdf')
Esempio n. 2
0
def draw_bar_chart(pdf_text, page_height):
    '''Currently generates a dummy graph.
    Next, need to pass in data that shall
    be the reactors temp throughout the
    sequence.
    '''
    pdf_text.showPage()
    drawing = Drawing(400, 200)
    data = [
            (13, 5, 20, 22, 37, 45, 19, 4),
            (14, 6, 21, 23, 38, 46, 20, 5)
            ]
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    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 = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99']
    drawing.add(bc)
    renderPDF.draw(drawing, pdf_text, inch, inch)
    
    return page_height
Esempio n. 3
0
def conversion_chart(data, labels):
    """Create chart that can be drawn as a gif with given data/labels"""

    drawing = Drawing(500, 400)
    bc = VerticalBarChart()

    bc.x = 80
    bc.y = 80

    bc.height = 290
    bc.width = 390

    bc.data = data

    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 100
    bc.valueAxis.valueStep = 10
    bc.valueAxis.labelTextFormat = '%2.2f'
    bc.barLabels.fontSize = 15
    bc.barLabelFormat = '%2.2f'
    bc.barLabels.boxAnchor = 's'

    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = 2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = labels

    drawing.add(bc)

    return drawing
    def vertical_bar_chart_draw(self, values, days, llabels):
        d = Drawing(0, 170)
        #  chart
        bc = VerticalBarChart()
        # set width and height
        bc.height = 125
        bc.width = 470
        # set data
        bc.data = values
        # set distance between bars elements
        bc.barSpacing = 0.5

        # set labels position under the x axe
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        # set name displayed for x axe
        bc.categoryAxis.categoryNames = days

        # set label format for each bar
        bc.barLabelFormat = '%d'
        # set distance between top of bar and it's label
        bc.barLabels.nudge = 7

        # set some charactestics for the Y axe
        bc.valueAxis.labelTextFormat = '%d km/h'
        bc.valueAxis.valueMin = 0

        d.add(self.title_draw(250, 190, _('Wind speed statistics')))
        d.add(bc)
        d.add(self.legend_draw(llabels, bc, x=480, y=165, boxAnchor='ne',
                               columnMaximum=1, type='bar'))
        # d.add(bcl)
        return d
Esempio n. 5
0
    def print_chunks_chart(self):
        nChunks = len(self.filechunks)

        d = Drawing(400, 140)
        traffic_MB = [n/(1024*1024) for n in self.traffic]
        data = [traffic_MB]
        bc = VerticalBarChart()
##        bc.x = 0
##        bc.y = 10
        bc.height = 100
        bc.width = 370
        bc.data = data
        bc.categoryAxis.tickUp = 0.5
        bc.categoryAxis.tickDown = 1.5

        bc.categoryAxis.categoryNames = []
        for n in range(nChunks):
            if n%5 == 0:
                bc.categoryAxis.categoryNames.append( str(n) )
            else:
                bc.categoryAxis.categoryNames.append('')

        bc.bars.strokeWidth = 0.3
        bc.valueAxis.labels.fontSize = 6
        bc.categoryAxis.labels.fontSize = 6
        bc.bars[0].fillColor = colors.lightblue
        
        bc.valueAxis.valueMin = 0

        d.add(bc)
        drawing = GraphicsDrawing(d, 'Traffic per chunk in MB')

        self.story.append(drawing)
        self.story.append(Spacer(0.01,1.0*cm))
Esempio n. 6
0
def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4)]):
    drawing = Drawing(400, 200)

    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = data

    bc.strokeColor = colors.black

    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 60
    bc.valueAxis.valueStep = 15

    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30

    catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ')
    catNames = map(lambda n:n+'-99', catNames)
    bc.categoryAxis.categoryNames = catNames
    drawing.add(bc)

    return drawing
Esempio n. 7
0
 def createReadsHistogram(self):
     '''
     Routine to create histogram of numbers of 'reads' for given years
     '''
     # The vertical bar chart will get added to the 'drawing' object
     drawing = Drawing(400, 200)
     # Now we can start constructing the vertical bar chart
     lc = VerticalBarChart()
     lc.x = 30
     lc.y = 50
     lc.height = 125
     lc.width = 350
     # Record the 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['reads histogram'].keys())))
     # This list will hold the data points for the histogram
     lc.data = []
     # Record the counts of both reads of refereed and non-refereed papers
     refereed = []
     non_refereed = []
     # The maximum number of reads will be used to scale the y axis
     max_reads = 0
     # Take only the first two values of each value string in the histogram data
     # The first is for 'all' papers, the second for the 'refereed' papers
     for year in years:
         values = map(lambda a: int(a),self.data['reads histogram'][str(year)].split(':')[:2])
         max_reads = max(max_reads,max(values))
         refereed.append(values[1])
         non_refereed.append(values[0]-values[1])
     lc.data.append(refereed)
     lc.data.append(non_refereed)
     # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly
     lc.categoryAxis.labels.dx = -6
     lc.categoryAxis.labels.dy = -6
     # and rotate the labels by 90 degrees
     lc.categoryAxis.labels.angle = 90
     # Define the value step and maximum for the y axis
     lc.valueAxis.valueMax = int(math.ceil(float(max_reads)/10.0))*10
     lc.valueAxis.valueStep = max(int(math.floor(float(max_reads)/10.0)),1)
     lc.valueAxis.valueMin = 0
     # The label names are the access years
     lc.categoryAxis.categoryNames = map(lambda a: str(a), years)
     # Now add the histogram to the 'drawing' object
     drawing.add(lc)
     # Add a legend to the histogram so that we now which color means what
     legend = Legend()
     legend.alignment = 'right'
     legend.x = 380
     legend.y = 160
     legend.deltax = 60
     legend.dxTextSpace = 10
     items = [(colors.red, 'refereed'), (colors.green, 'non-refereed')]
     legend.colorNamePairs = items
     drawing.add(legend, 'legend')
     # Finally add a title to the histogram
     drawing.add(String(200,190,"reads histogram", textAnchor="middle", fillColor='blue'))
     # Append the result to the 'story'
     self.story.append(drawing)
Esempio n. 8
0
def generateversionchart((versionpickle, picklehash, imagedir, pickledir)):
	datapickle = open(os.path.join(pickledir, versionpickle), 'rb')
	data = cPickle.load(datapickle)
	datapickle.close()

	## calculate the possible widths and heights of chart, bars, labels and so on
	maxversionstring = max(map(lambda x: len(x[0]), data))

	barwidth = 15
	chartwidth = len(data) * barwidth + 10 * len(data)

	maxvalue = max(map(lambda x: x[1], data))
	step = int(math.log(maxvalue,10))
	valueStep = pow(10,step)

	## calculate a possible good value for startx and starty so labels are not cut off
	startx = max(10 + step * 10, 30)

	## TODO: fiddle with values to create nicer looking graphs
	starty = maxversionstring * 10 + 20

	drawheight = 225 + starty
	drawwidth = chartwidth + startx + 10

	## create the drawing
	drawing = Drawing(drawwidth, drawheight)
	bc = VerticalBarChart()
	bc.x = startx
	bc.y = starty
	bc.height = 200
	bc.width = chartwidth
	bc.data = [tuple(map(lambda x: x[1], data))]
	bc.strokeColor = colors.white
	bc.valueAxis.valueMin = 0
	bc.valueAxis.labels.fontSize = 16
	bc.valueAxis.valueMax = maxvalue
	bc.valueAxis.valueStep = valueStep
	bc.categoryAxis.labels.boxAnchor = 'w'
	bc.categoryAxis.labels.dx = 0
	bc.categoryAxis.labels.dy = -2
	bc.categoryAxis.labels.angle = -90
	bc.categoryAxis.labels.fontSize = 16
	bc.categoryAxis.categoryNames = map(lambda x: x[0], data)
	bc.barWidth = barwidth

	drawing.add(bc)
	outname = os.path.join(imagedir, picklehash)

	renderPM.drawToFile(drawing, outname, fmt='PNG')
	return picklehash
 def getChart(self):
     d = Drawing(300, 200)
     chart = VerticalBarChart()
     chart.width = 560
     chart.height = 460
     chart.x = 50
     chart.y = 50
     chart.height = 125
     chart.width = 300
     chart.strokeColor = colors.black
     chart.valueAxis.valueMin = 0
     chart.valueAxis.valueMax = 100
     chart.valueAxis.valueStep = 10
     chart.categoryAxis.labels.boxAnchor = 'ne'
     chart.categoryAxis.labels.dx = 8
     chart.categoryAxis.labels.dy = -2
     chart.categoryAxis.labels.angle = 0
     chart.data = self.marks#self.averages
     chart.categoryAxis.categoryNames = self.chartXValues#self.studentNumbers
     
     d.add(chart)
     #d.save(fnRoot='test', formats=['png', 'pdf'])
     return d
def run(self, include_sub_survey=False, dimensions=[]):

    # Build data set
    averages = []
    category_names = []
    
    for dimension in self.getDimensions():
        averages.append(self.get_average_score_for_dimension(
            include_sub_survey=include_sub_survey,
            dimension=dimension))
        category_names.append(dimension)
        
    drawing = Drawing(600, 300)
    
    bc = VerticalBarChart()         
    bc.x = 20
    bc.y = 20  
    bc.height = 260
    bc.width = 580
    bc.data = [averages]
    bc.categoryAxis.categoryNames = category_names
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 10
    bc.categoryAxis.labels.textAnchor = 'middle'
    bc.categoryAxis.visibleTicks = 0
    bc.valueAxis.valueMax = 100.0
    bc.valueAxis.valueMin = min(averages, 0)
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.labels.textAnchor = 'middle'
    bc.barLabelFormat = '%.0f'
    bc.barLabels.dy = 8
    bc.barLabels.fontName = 'Helvetica'
    bc.barLabels.fontSize = 10
    bc.barWidth = len(averages)
    bc.fillColor = None

    drawing.add(bc)
    
    # 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
Esempio n. 11
0
def chartBins(bins, filename):
    data = []
    labels = []

    keys = bins.keys()
    keys.sort()

    for k in keys:
        mid = (k[1] + k[0]) / 2.0
        labels.append(str(mid))
        data.append(len(bins[k]))

    maxval = max(data)
    data = [tuple(data)]

    # now, make the chart
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 500
    bc.width = 1100
    bc.data = data

    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueStep = 10
    bc.valueAxis.valueMax = maxval + bc.valueAxis.valueStep

    bc.categoryAxis.labels.boxAnchor = "n"
    # bc.categoryAxis.labels.dx = 8
    # bc.categoryAxis.labels.dy = -2
    # bc.categoryAxis.labels.angle = 30

    new_labels = []
    for i, l in enumerate(labels):
        if i % 5 == 0:
            new_labels.append(l)
        else:
            new_labels.append("")

    # bc.categoryAxis.categoryNames = labels
    bc.categoryAxis.categoryNames = new_labels

    drawing = Drawing(1200, 600)
    drawing.add(bc)

    from reportlab.graphics import renderPM

    renderPM.drawToFile(drawing, output_filename)
def graphout(statenames, data):
    drawing = Drawing(500, 200)
    lc = VerticalBarChart()
    lc.x = 30
    lc.y = 50
    lc.height = 125
    lc.width = 450
    lc.data = data
    statenames = statenames
    lc.categoryAxis.categoryNames = statenames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.categoryAxis.labels.angle = 270
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 10000000 #1500
    lc.valueAxis.valueStep = 1000000 #300
    drawing.add(lc)
    return drawing
Esempio n. 13
0
    def makeBarChart(self, context, width, height, data):
        content = []

        drawing = Drawing(width, height)

        lp = VerticalBarChart()
        lp.x = 0
        lp.y = 0
        lp.height = height
        lp.width = width
        lp.data = data

        drawing.add(lp)

        content.append(drawing)

        return content
Esempio n. 14
0
    def test_21_barCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        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.barcharts import VerticalBarChart

        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, 12))

        d = Drawing(400, 200)
        data = [(13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5)]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 125
        bc.width = 300
        bc.data = data
        bc.strokeColor = colors.black
        bc.groupSpacing = 10
        bc.barSpacing = 2.5

        bc.valueAxis._valueMin = 0
        bc.valueAxis._valueMax = 50
        bc.valueAxis._valueStep = 10

        bc.categoryAxis.categoryNames = [
            '1', '2', '3', '4', '5', '6', '7', '8'
        ]
        # bc.categoryAxis.style = 'stacked'
        d.add(bc)

        elements.append(d)

        doc.build(elements)
Esempio n. 15
0
    def test_21_barCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        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.barcharts import VerticalBarChart

        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,12))

        d = Drawing(400,200)
        data = [
            (13,5,20,22,37,45,19,4),
            (14,6,21,23,38,46,20,5)
        ]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 125
        bc.width = 300
        bc.data = data
        bc.strokeColor = colors.black
        bc.groupSpacing = 10
        bc.barSpacing = 2.5

        bc.valueAxis._valueMin = 0
        bc.valueAxis._valueMax = 50
        bc.valueAxis._valueStep = 10

        bc.categoryAxis.categoryNames = ['1','2','3','4','5','6','7','8']
        # bc.categoryAxis.style = 'stacked'
        d.add(bc)

        elements.append(d)

        doc.build(elements)
    def draw(self, cur_drawing, start_x, start_y, end_x, end_y):
        """Draw a bar chart with the info in the specified range."""
        bar_chart = VerticalBarChart()
        if self.chart_title:
            self._draw_title(cur_drawing, self.chart_title,
                             start_x, start_y, end_x, end_y)
        # set the position of the bar chart
        x_start, x_end, y_start, y_end = self._determine_position(start_x,
                                                                  start_y,
                                                                  end_x,
                                                                  end_y)

        bar_chart.x = x_start
        bar_chart.y = y_start
        bar_chart.width = abs(x_start - x_end)
        bar_chart.height = abs(y_start - y_end)

        # set the information in the bar chart
        bar_chart.data = self.display_info
        bar_chart.valueAxis.valueMin = min(self.display_info[0])
        bar_chart.valueAxis.valueMax = max(self.display_info[0])
        for data_set in self.display_info[1:]:
            if min(data_set) < bar_chart.valueAxis.valueMin:
                bar_chart.valueAxis.valueMin = min(data_set)
            if max(data_set) > bar_chart.valueAxis.valueMax:
                bar_chart.valueAxis.valueMax = max(data_set)

        # set other formatting options
        if len(self.display_info) == 1:
            bar_chart.groupSpacing = 0
            style = TypedPropertyCollection(BarChartProperties)
            style.strokeWidth = 0
            style.strokeColor = colors.green
            style[0].fillColor = colors.green

            bar_chart.bars = style

        # set the labels
        # XXX labels don't work yet
        # bar_chart.valueAxis.title = self.x_axis_title
        # bar_chart.categoryAxis.title = self.y_axis_title

        cur_drawing.add(bar_chart)
Esempio n. 17
0
    def draw(self, cur_drawing, start_x, start_y, end_x, end_y):
        """Draw a bar chart with the info in the specified range."""
        bar_chart = VerticalBarChart()
        if self.chart_title:
            self._draw_title(cur_drawing, self.chart_title,
                             start_x, start_y, end_x, end_y)
        # set the position of the bar chart
        x_start, x_end, y_start, y_end = self._determine_position(start_x,
                                                                  start_y,
                                                                  end_x,
                                                                  end_y)

        bar_chart.x = x_start
        bar_chart.y = y_start
        bar_chart.width = abs(x_start - x_end)
        bar_chart.height = abs(y_start - y_end)

        # set the information in the bar chart
        bar_chart.data = self.display_info
        bar_chart.valueAxis.valueMin = min(self.display_info[0])
        bar_chart.valueAxis.valueMax = max(self.display_info[0])
        for data_set in self.display_info[1:]:
            if min(data_set) < bar_chart.valueAxis.valueMin:
                bar_chart.valueAxis.valueMin = min(data_set)
            if max(data_set) > bar_chart.valueAxis.valueMax:
                bar_chart.valueAxis.valueMax = max(data_set)

        # set other formatting options
        if len(self.display_info) == 1:
            bar_chart.groupSpacing = 0
            style = TypedPropertyCollection(BarChartProperties)
            style.strokeWidth = 0
            style.strokeColor = colors.green
            style[0].fillColor = colors.green

            bar_chart.bars = style

        # set the labels
        # XXX labels don't work yet
        # bar_chart.valueAxis.title = self.x_axis_title
        # bar_chart.categoryAxis.title = self.y_axis_title

        cur_drawing.add(bar_chart)
Esempio n. 18
0
    def getBarChart(self, x_values, y_values):
        """Gets a bar chart with the given values
            Parameters:
                self: the class instance
                x_values: list - x values for the bar chart
                y_values: list of tuples - y values for the bar chart
            Returns:
                reportlab Vertical Bar Chart - bar chart with inputted values
        """

        # Setting up sizing, position and colourings
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 100
        bc.height = 150
        bc.width = 350
        bc.strokeColor = colors.black

        # Setting up axis
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = 300
        bc.valueAxis.valueStep = 25

        # Setting up position and angle of labels
        bc.categoryAxis.labels.boxAnchor = 'ne'
        bc.categoryAxis.labels.dx = 0
        bc.categoryAxis.labels.dy = -2
        bc.categoryAxis.labels.angle = 65

        # Adding bar labels
        bc.barLabelFormat = '%s'
        bc.barLabels.nudge = 5
        bc.barLabels.boxAnchor = 's'
        bc.barLabels.dy = -1

        # Changing bar colours
        bc.bars[0].fillColor = colors.green

        # Adding x and y data to the chart
        bc.categoryAxis.categoryNames = x_values
        bc.data = y_values

        return bc
Esempio n. 19
0
def create_barchart(barchart_data):
    color=[green,red,blue,yellow,black]
    data_length=len(barchart_data["data"])
    bar_chart = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = barchart_data["data"]
    bc.fillColor=lightblue
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 50
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = list(barchart_data["label"][0])
    for i in xrange(data_length):
        bc.bars[i].fillColor = color[i]
    bar_chart.add(bc)


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

    bar_leg.columnMaximum   = 1
    bar_leg.yGap            = 0
    bar_leg.deltax          = 50
    bar_leg.deltay          = 0
    bar_leg.dx              = 10
    bar_leg.dy              = 1.5
    bar_leg.fontSize        = 10
    bar_leg.alignment       = 'right'
    bar_leg.dxTextSpace     = 5
    bar_leg.colorNamePairs  = [(color[i],barchart_data["legend"][0][i]) for i in xrange(data_length)]
    bar_chart.add(bar_leg) 
    return bar_chart
Esempio n. 20
0
def getPDF(values=[]):
    d = Drawing(1700, 900)  # image size

    chart = VerticalBarChart()
    chart.width = 1600
    chart.height = 800
    chart.x = 110
    chart.y = 90
    chart.data = [values]
    chart.groupSpacing = 10
    chart.categoryAxis.labels.angle = 45
    chart.valueAxis.labels.fontSize = 18
    chart.valueAxis.valueMin = 0
    chart.valueAxis.valueMax = getMaxValue(values)
    chart.categoryAxis.labels.fontSize = 24
    chart.categoryAxis.categoryNames = n_store[1 : len(n_store)]
    chart.valueAxis.valueMin = 0

    d.add(chart)
    d.save(fnRoot="test", formats=["pdf"])
Esempio n. 21
0
 def draw_chart_bar(self, bar_data):
     # sort the amounts by the largest
     drawing = Drawing(400, 400)
     data = [bar_data['amounts']]
     bc = VerticalBarChart()
     bc.x = 50
     bc.y = 10
     bc.height = 350
     bc.width = 350
     bc.data = data
     bc.strokeColor = colors.black
     bc.valueAxis.valueMin = 0
     bc.categoryAxis.labels.boxAnchor = 'ne'
     bc.categoryAxis.labels.dx = 8
     bc.categoryAxis.labels.dy = -2
     bc.categoryAxis.labels.angle = 30
     bc.categoryAxis.categoryNames = bar_data['clients']
     bc.valueAxis.valueStep = 1000
     drawing.add(bc)
     renderPDF.draw(drawing, self.pdf, 30 * mm, 100 * mm)
Esempio n. 22
0
def graphout(prod_catnames, data):
    drawing = Drawing(500, 200)
    lc = VerticalBarChart()
    lc.x = 30
    lc.y = 50
    lc.height = 125
    lc.width = 450
    lc.data = data
    #prod_catnames = prod_catnames
    lc.categoryAxis.categoryNames = prod_catnames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.categoryAxis.labels.angle = 270
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 5000  #1500
    lc.valueAxis.valueStep = 1000  #300
    #lc.lines[0].strokeWidth = 2
    #lc.lines[0].symbol = makeMarker('FilledCircle') # added to make filled circles.
    #lc.lines[1].strokeWidth = 1.5
    drawing.add(lc)
    return drawing
Esempio n. 23
0
    def getVerticalBarChart():
        data = [(df2.iloc[i, 38:43])]
        chart = VerticalBarChart()
        chart.data = data
        chart.valueAxis.valueMax = 90
        chart.valueAxis.valueMin = 0
        chart.valueAxis.valueStep = 10
        chart.x = 5
        chart.y = 5
        chart.height = 100
        chart.width = 240
        chart.strokeColor = colors.black
        chart.fillColor = colors.pink
        chart.categoryAxis.categoryNames = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5']
        title = String(50, 120, 'Time (sec)', fontSize=14)

        drawing = Drawing(240, 120)
        drawing.add(title)
        drawing.add(chart)
        return drawing
def graphout(prod_catnames, data):
    drawing = Drawing(500, 200)
    lc = VerticalBarChart()
    lc.x = 30
    lc.y = 50
    lc.height = 125
    lc.width = 450
    lc.data = data
    #prod_catnames = prod_catnames
    lc.categoryAxis.categoryNames = prod_catnames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.categoryAxis.labels.angle = 270
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 5000 #1500
    lc.valueAxis.valueStep = 1000 #300
    #lc.lines[0].strokeWidth = 2
    #lc.lines[0].symbol = makeMarker('FilledCircle') # added to make filled circles.
    #lc.lines[1].strokeWidth = 1.5
    drawing.add(lc)
    return drawing
Esempio n. 25
0
    def makeBarChart(self, context, width, height, data, xvalues, barColors, strokeWidth, displayBarLabels, labelAngles, yAxisMin, yAxisMax):
        content = []

        drawing = Drawing(width, height)

        chart = VerticalBarChart()
        chart.x = 0
        chart.y = 0
        chart.height = height
        chart.width = width
        chart.data = data

        if displayBarLabels:
            chart.barLabelFormat = '%2.0f'
            chart.barLabels.dy = 6
        else:
            chart.barLabelFormat = None

        if xvalues:
            chart.categoryAxis.categoryNames = xvalues

        if yAxisMin is not None:
            chart.valueAxis.valueMin = yAxisMin

        if yAxisMax is not None:
            chart.valueAxis.valueMax = yAxisMax

        if strokeWidth:
            self.handleSingleOrList(chart.bars, strokeWidth, 'strokeWidth', len(data))

        if barColors:
            self.handleSingleOrList(chart.bars, barColors, 'fillColor', len(data), colors.HexColor)

        if labelAngles is not None:
            self.handleSingleOrList(chart.categoryAxis.labels, labelAngles, 'angle', len(data[0]))

        drawing.add(chart)

        content.append( drawing )

        return content
Esempio n. 26
0
 def GraficoCustoFixoImplemento(self):
     grafico = Drawing(200, 200)
     dados = [
         (self.DepreciacaoImplemento, self.JuroImplemento,
          self.GaragemImplemento, self.SeguroImplemento),
     ]
     barras = VerticalBarChart()
     barras.x = 0
     barras.y = 0
     barras.height = 150
     barras.width = 150
     barras.data = dados
     barras.barLabelFormat = DecimalFormatter(2)
     barras.barLabels.nudge = 6
     barras.categoryAxis.categoryNames = [
         'Depreciação', 'Juros', 'Garagem', 'Seguro'
     ]
     barras.categoryAxis.labels.angle = 45
     barras.categoryAxis.labels.boxAnchor = 'ne'
     grafico.add(barras)
     return grafico
Esempio n. 27
0
 def GraficoCustoVariavel(self):
     grafico = Drawing(200, 200)
     dados = [
         (self.CustoCombHora, self.CustoOleoHora,
          self.CustoManutencaoHoraTrator, self.PrecoTratorista),
     ]
     barras = VerticalBarChart()
     barras.x = 0
     barras.y = 0
     barras.height = 150
     barras.width = 150
     barras.data = dados
     barras.barLabelFormat = DecimalFormatter(2)
     barras.barLabels.nudge = 6
     barras.categoryAxis.categoryNames = [
         'Combustível', 'Óleo', 'Manutenção', 'Operador'
     ]
     barras.categoryAxis.labels.angle = 45
     barras.categoryAxis.labels.boxAnchor = 'ne'
     grafico.add(barras)
     return grafico
def vertical_bar_graph(data, elements):
    drawing = Drawing(0, 200)  # for indices
    bc = VerticalBarChart()
    bc.x =15  # x,y define the left bottom of graph
    bc.y = -130
    bc.height = 250
    bc.width = 500
    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 = ['Ques1', 'Ques2', 'Ques3',
                                     'Ques4', 'Ques5', 'Ques6', 'Ques7', 'Ques8']
    drawing.add(bc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
def verticalbargraph(data, elements):
    drawing = Drawing(0, 200)  # for indices
    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))
Esempio n. 30
0
def letrasGrafico(data):
    "Make a slightly pathologic bar chart with only TWO data items."
    drawing = Drawing(800, 300)
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = -10
    bc.height = 300
    bc.width = 300
    bc.barWidth = 15
    bc.Title = "Frencuencias en "
    bc.data = data
    #bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 7000
    bc.valueAxis.valueStep = 500
    bc.categoryAxis.labels.boxAnchor = 'e'
    bc.categoryAxis.labels.angle = 0
    abc = "abcdefghijklmnopqrstuvwxyz"
    bc.categoryAxis.categoryNames = list(abc)
    drawing.add(bc)
    return drawing
Esempio n. 31
0
 def diagrammAlleMonateEinkommen(self, aPngDateiname):
     # Festlegen der Gesamtgröße in Pixel
     d = Drawing(800, 600)
     # Anlegen des Diagramms
     diagramm = VerticalBarChart()
     # Positionierung und Größe des Diagramms
     diagramm.x = 50
     diagramm.y = 50
     diagramm.width = 700
     diagramm.height = 500
     # Holen der Daten
     daten = []
     jahre = []
     aAnzJahre, aSumme, ea = self.listeAlleMonateEinkommen()
     print(ea)
     for x in ea:
         # print (x)
         x['betrag'], x['jahr']
         daten.append(float(x['betrag']))
         jahre.append(str(x['jahr']))
     ymin = min(daten)
     ymax = max(daten)
     # Daten für das Diagramm müssen als Liste von Tupeln vorliegen
     daten = [tuple(daten)]
     print(daten)
     print(jahre)
     # return False
     # Hinzufügen der Daten
     diagramm.data = daten
     # Y-Achse (in ReportLab „valueAxis“) formatieren
     diagramm.valueAxis.valueMin = ymin
     diagramm.valueAxis.valueMax = ymax
     diagramm.valueAxis.valueStep = 2000
     # X-Achse (in ReportLab „categoryAxis“) formatieren
     diagramm.categoryAxis.categoryNames = jahre
     # Diagramm zeichnen
     d.add(diagramm)
     # ... und speichernhttp://www.reportlab.com/software/opensource/rl-toolkit/guide/
     print(aPngDateiname)
     renderPM.drawToFile(d, aPngDateiname, 'PNG')
Esempio n. 32
0
    def add_bar_chart(self, width, height, labels, data, minv=None, maxv=None):
        pad = 10

        _min, _max = self._find_min_max(data)
        minv = _min if minv is None else minv
        maxv = _max if maxv is None else maxv

        bc = VerticalBarChart()
        bc.x = pad * mm
        bc.y = pad * mm
        bc.width = (width - 2 * pad) * mm
        bc.height = (height - 2 * pad) * mm

        bc.categoryAxis.categoryNames = labels
        bc.data = data
        bc.valueAxis.valueMin = minv
        bc.valueAxis.valueMax = maxv

        drawing = Drawing(width * mm, height * mm)
        drawing.hAlign = "CENTER"
        drawing.add(bc)
        self.story.append(drawing)
Esempio n. 33
0
def sample1barline(
    data=[(100, 110, 120, 130), (70, 25, 85, 30), (63, 75, 51, 92),
          (51, 21, 66, 71), (10, 11, 90, 30)],
    seriesOrder=[[0, 3, 1], [4], [2]],
    lines=[3, 4],
    cAStyle='mixed',
):
    d = Drawing(400, 250)
    chart = VerticalBarChart()
    d.add(chart, name='chart')
    leg = Legend()
    d.add(leg, name='leg')
    chart.bars.strokeColor = None
    chart.bars[2].fillColor = colors.blue
    chart.bars[3].fillColor = colors.orange
    chart.bars[4].fillColor = colors.black  #yellow
    chart.bars[4].strokeWidth = 3
    chart.bars[4].symbol = makeMarker('FilledDiamond',
                                      size=10,
                                      fillColor=colors.red)
    chart.barSpacing = 1
    chart.categoryAxis.style = cAStyle
    chart.data = data
    chart.x = 20
    chart.y = 70
    chart.height = d.height - chart.y - 10
    chart.valueAxis.forceZero = True
    chart.width = d.width - chart.x - 10
    for i in lines:
        chart.bars[i].isLine = 1
    for i in lines:
        chart.bars[i].strokeWidth = 2
    leg.colorNamePairs = Auto(chart=chart)
    leg.x = d.width / 2
    leg.y = 5
    leg.boxAnchor = 's'
    leg.columnMaximum = 1
    leg.alignment = 'right'
    return d
Esempio n. 34
0
    def __drawPage2Group(self, c):
        # 第二页,下方柱状图,所有内容书写范围为Pleft:10mm Pright:200mm Pheader:187mm Pfooter:10mm
        Pleft = START_X + 10 * mm
        Pright = START_X + 200 * mm
        Pheader = START_Y + 187 * mm
        Pfooter = START_Y + 10 * mm
        c.setFillColorRGB(1, 1, 1)
        c.rect(Pleft, Pheader - 160 * mm, 190 * mm, 120 * mm, fill=1)
        c.setFont("song", 15)
        c.setFillColorRGB(1, 0, 1)
        c.drawString(Pleft + 3 * mm, Pheader - 50 * mm, "漏洞信息分组")

        a = []
        familyids = []
        for familyid in self.scanParams['statsFamily']:
            a.append(self.scanParams['statsFamily'][familyid]['total'])
            familyids.append(str(familyid))
        print a, familyids
        d = Drawing(400, 300)
        data = [a]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 245
        bc.width = 400
        bc.data = data
        bc.strokeColor = colors.black
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = 5
        bc.valueAxis.valueStep = 1
        bc.categoryAxis.labels.boxAnchor = 'ne'
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        bc.categoryAxis.labels.angle = 30
        bc.categoryAxis.categoryNames = familyids
        bc.categoryAxis.labels.fontName = 'song'
        bc.categoryAxis.labels.fontSize = 10
        d.add(bc)
        renderPDF.draw(d, c, Pleft + 10 * mm, Pheader - 160 * mm)
Esempio n. 35
0
    def vertical_bar_chart_draw(self, values, days, llabels):
        d = Drawing(0, 170)
        #  chart
        bc = VerticalBarChart()
        # set width and height
        bc.height = 125
        bc.width = 470
        # set data
        bc.data = values
        # set distance between bars elements
        bc.barSpacing = 0.5

        # set labels position under the x axe
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        # set name displayed for x axe
        bc.categoryAxis.categoryNames = days

        # set label format for each bar
        bc.barLabelFormat = '%d'
        # set distance between top of bar and it's label
        bc.barLabels.nudge = 7

        # set some charactestics for the Y axe
        bc.valueAxis.labelTextFormat = '%d km/h'
        bc.valueAxis.valueMin = 0

        d.add(self.title_draw(250, 190, _('Wind speed statistics')))
        d.add(bc)
        d.add(
            self.legend_draw(llabels,
                             bc,
                             x=480,
                             y=165,
                             boxAnchor='ne',
                             columnMaximum=1,
                             type='bar'))
        # d.add(bcl)
        return d
Esempio n. 36
0
def getVetricalBarChart(taxes_int):
    values = []
    years = []
    font = 'Arial'
    for year in taxes_int:
        years.append(year)
        values.append(taxes_int[year])

    data = [values]
    chart = VerticalBarChart()
    chart.height = 180
    chart.width = 450
    chart.data = data

    chart.valueAxis.valueMin = 0
    chart.barWidth = 20
    chart.groupSpacing = 5
    chart.barLabels.fontName = font
    chart.barLabels.fontSize = 8
    chart.bars[0].fillColor = colors.cornflowerblue
    chart.barLabelFormat = '%d тг'
    chart.barLabels.nudge = 7

    chart.categoryAxis.labels.fontName = font
    chart.categoryAxis.labels.fontSize = 8
    chart.categoryAxis.categoryNames = years

    chart.valueAxis.labels.fontName = font
    chart.valueAxis.labels.fontSize = 8
    # chart.valueAxis.gridStrokeDashArray = strokeDashArray
    # chart.valueAxis.gridStrokeWidth = strokeWidth
    # chart.valueAxis.strokeDashArray = strokeDashArray
    # chart.valueAxis.strokeWidth = strokeWidth


    drawing = Drawing(300)
    drawing.add(chart)
    return drawing
Esempio n. 37
0
def myBarChart(data):
    drawing = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = data
    bc.barWidth = .3*inch
    bc.groupSpacing = .2 * inch
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 100
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    catNames = string.split('Trial1 Trial2 Trial3 Trial4 Trial5')
    bc.categoryAxis.categoryNames = catNames
    bc.bars[0].fillColor = colors.blue
    bc.bars[1].fillColor = colors.lightblue
    drawing.add(bc)
    return drawing
Esempio n. 38
0
def barras(datos):
    alto = datos["alto"]
    ancho = datos["ancho"]
    data = datos["data"]
    labels = datos["labels"]
    colores = datos["colores"]

    grafico = VerticalBarChart()
    grafico.x = 30
    grafico.y = 0
    grafico.height = alto
    grafico.width = ancho
    grafico.data = data
    grafico.barSpacing = 1.25
    for i in range(len(colores)):
        color = colors.HexColor(colores[i])
        grafico.bars[i].strokeColor = color
        grafico.bars[i].fillColor = color
    grafico.valueAxis.labels.fontName = "Helvetica"
    grafico.valueAxis.labels.fontSize = FONTSIZE
    grafico.valueAxis.valueMin = 0
    grafico.valueAxis.valueMax = 100
    grafico.valueAxis.valueStep = 10
    grafico.categoryAxis.categoryNames = labels
    grafico.categoryAxis.labels.fontName = "Helvetica"
    grafico.categoryAxis.labels.fontSize = FONTSIZE
    grafico.categoryAxis.labels.dy = -FONTSIZE
    grafico.categoryAxis.labels.boxAnchor = 'c'
    grafico.categoryAxis.labels.angle = 0
    retorno = crearDrawing(grafico)
    etiqueta = Label()
    etiqueta.setOrigin(0, alto)
    etiqueta.fontSize = FONTSIZE
    etiqueta.fontName = "Helvetica"
    etiqueta.setText("(%)")
    retorno.add(etiqueta)
    return retorno
Esempio n. 39
0
    def __drawPage2Owasp(self, c):
        # 第二页,右侧OWASP图,所有内容书写范围为Pleft:120mm Pright:200mm Pheader:247mm Pfooter:80mm
        Pleft = START_X + 100 * mm
        Pright = START_X + 200 * mm
        Pheader = START_Y + 247 * mm
        Pfooter = START_Y + 80 * mm
        c.setFillColorRGB(1, 1, 1)
        c.rect(Pleft, Pheader - 80 * mm, 100 * mm, 80 * mm, fill=1)
        c.setFont("song", 15)
        c.setFillColorRGB(1, 0, 1)
        c.drawString(Pleft + 2 * mm, Pheader - 10 * mm, "OWASP TOP10占比分布")

        d = Drawing(300, 200)
        data = [(13, 5, 20, 22, 37, 45, 19, 4, 5, 10)]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 130
        bc.width = 180
        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 = 8
        bc.categoryAxis.labels.dy = -2
        bc.categoryAxis.labels.angle = 30
        bc.categoryAxis.categoryNames = [
            '1.SQL注入', '2.失效的身份认证和会话管理', '3.跨站脚本(XSS)', '4.不安全的直接引用对象',
            '5.安全配置错误', '6.敏感信息泄漏', '功能级访问控制缺失', '8.跨站请求伪造(CSRF)',
            '9.使用含有已知漏洞的组件', '10.未验证的重定向和转发'
        ]
        bc.categoryAxis.labels.fontName = 'song'
        bc.categoryAxis.labels.fontSize = 5
        d.add(bc)
        renderPDF.draw(d, c, Pleft + 2 * mm, Pheader - 80 * mm)
 def draw_bar(bar_data=[],
              ax=[],
              items=[],
              limit_step=(100, 10),
              draw_weight=500,
              draw_height=250):
     drawing = Drawing(draw_weight, draw_height)
     bc = VerticalBarChart()
     bc.x = 35
     bc.y = 100
     bc.height = 120
     bc.width = 350
     bc.data = bar_data
     bc.strokeColor = Config_Charts.chose_colors[15]
     bc.valueAxis.valueMin = 0
     bc.valueAxis.valueMax = limit_step[0]
     bc.valueAxis.valueStep = limit_step[1]
     bc.categoryAxis.labels.dx = 8
     bc.categoryAxis.labels.dy = -10
     bc.categoryAxis.labels.angle = 20
     bc.categoryAxis.categoryNames = ax
     bc.bars.strokeColor = Config_Charts.chose_colors[148]
     for index, item in enumerate(items):
         bc.bars[index].fillColor = item[0]
     # 图示
     leg = Legend()
     leg.fontName = Config_Charts.typeface
     leg.alignment = 'right'
     leg.boxAnchor = 'ne'
     leg.x = 465
     leg.y = 220
     leg.dxTextSpace = 0
     leg.columnMaximum = 10
     leg.colorNamePairs = items
     drawing.add(leg)
     drawing.add(bc)
     return drawing
Esempio n. 41
0
def draw_req_risk_histogram(risk_values: List[int], passed_by_risk: List[int],
                            failed_by_risk: List[int],
                            not_run_by_risk: List[int]) -> Drawing:
    d = Drawing(width=350, height=130)
    vbc = VerticalBarChart()
    vbc.x = 0
    vbc.y = 0
    vbc.width = 350
    vbc.height = 130
    vbc.data = _normalize([passed_by_risk, failed_by_risk, not_run_by_risk])
    vbc.bars[0].fillColor = COLOR_GREEN
    vbc.bars[1].fillColor = COLOR_RED
    vbc.bars[2].fillColor = COLOR_GRAY
    vbc.valueAxis.valueMin = 0
    vbc.valueAxis.valueMax = 110
    vbc.valueAxis.valueStep = 20
    vbc.valueAxis.labels.fontName = MAIN_FONT_NAME
    vbc.valueAxis.labels.fontSize = AXIS_FONT_SIZE
    vbc.categoryAxis.categoryNames = [str(x) for x in risk_values]
    vbc.categoryAxis.style = 'stacked'
    vbc.categoryAxis.labels.fontName = MAIN_FONT_NAME
    vbc.categoryAxis.labels.fontSize = AXIS_FONT_SIZE
    d.add(vbc)
    return d
    def draw_bar(bar_data=[], ax=[], items=[]):

        drawing = Drawing(600, 250)
        bc = VerticalBarChart()
        bc.x = 35
        bc.y = 100
        bc.height = 120
        bc.width = 350
        bc.data = bar_data
        bc.strokeColor = colors.black
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = 100
        bc.valueAxis.valueStep = 10
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -10
        bc.categoryAxis.labels.angle = 20
        bc.categoryAxis.categoryNames = ax

        # 图示
        leg = Legend()

        leg.fontName = 'SimSun'
        leg.alignment = 'right'
        leg.boxAnchor = 'ne'

        leg.x = 505
        leg.y = 220

        leg.dxTextSpace = 10
        leg.columnMaximum = 4

        leg.colorNamePairs = items
        drawing.add(leg)
        drawing.add(bc)

        return drawing
        def vertical_bar_chart(self):
            """
            Draws a vertical bar chart
            :return: vertical bar chart
            """

            drawing = Drawing(200, 280)
            graph = VerticalBarChart()
            graph.x = self.graph_x
            graph.y = self.graph_y

            graph.width = self.width
            graph.height = self.height

            graph.valueAxis.forceZero = 1
            graph.valueAxis.valueMin = self.value_min
            graph.valueAxis.valueMax = self.value_max
            graph.valueAxis.valueStep = self.value_step

            graph.data = self.data
            graph.categoryAxis.categoryNames = self.categories

            graph.barLabels.nudge = 15
            graph.barLabelFormat = '%dº'
            graph.barLabels.dx = 0
            graph.barLabels.dy = 0
            graph.barLabels.boxAnchor = 'n'
            graph.barLabels.fontName = 'Vera'
            graph.barLabels.fontSize = 10

            graph.bars[0].fillColor = PCMYKColor(45, 45, 0, 0, alpha=85)
            graph.bars[1].fillColor = PCMYKColor(70, 75, 0, 0, alpha=100)
            graph.bars.fillColor = PCMYKColor(64, 62, 0, 18, alpha=85)
            drawing.add(graph, '')

            return [drawing]
Esempio n. 44
0
    def __init__(self, width, height, labels, data):
        IRender.__init__(self, width, height, labels, data)

        #self.w = self.width
        #self.h = self.height
        #data = [[int(line[1])] for line in self.data]
        #labels = [line[0] for line in self.data]
        #plot = cairoplot.VerticalBarPlot('/tmp/tmp.png', data, self.w*2, self.h*2, x_labels=labels, grid=True, display_values=True)
        ##plot.font_size *= 2
        #plot.render()
        #plot.commit()
        #with open('/tmp/tmp.png') as f:
        #    self.image = Image(StringIO(f.read()), self.w, self.h)
        bc = VerticalBarChart()
        bc.x = 40
        bc.y = 50
        bc.height = self.height - 60
        bc.width = self.width - 60
        bc.data = [[int(line[1]) for line in self.data]]
        bc.strokeColor = colors.white
        bc.bars.strokeColor = RED
        bc.bars.fillColor = RED
        bc.bars[0].fillColor = RED
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = max([int(line[1]) for line in self.data])
        bc.valueAxis.valueStep = bc.valueAxis.valueMax/10
        if not bc.valueAxis.valueStep:
            bc.valueAxis.valueStep = 1
            bc.valueAxis.valueMax = 10
        bc.categoryAxis.labels.boxAnchor = 'ne'
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        bc.categoryAxis.labels.angle = 30
        bc.categoryAxis.categoryNames = [line[0] for line in self.data]
        self.drawing = Drawing(self.width, self.height)
        self.drawing.add(bc)
        def _rawDraw(self, x, y):
            from reportlab.lib import colors 
            from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS
            from reportlab.graphics.charts.linecharts import HorizontalLineChart, Label
            from reportlab.graphics.charts.barcharts  import VerticalBarChart
            from reportlab.graphics.widgets.markers import makeMarker
            self._setScale([self.dataBar])
            (x1, y1, Width, Height) = self._getGraphRegion(x, y)
            #self._drawBox(x1, y1, Width, Height)

            #Build the graph
            self.drawing = Drawing(self.width, self.height)

            #Size of the Axis
            SizeXaxis = 14
            SizeYaxis = 0.0
            countSteps = int(self.valueMax / self.valueStep)
            for n in range(countSteps + 1):
                eachValue = self.valueMin + n * self.valueStep
                SizeYaxis = max(SizeYaxis, self._stringWidth(self._customSecondsLabelFormat(eachValue), STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) )
            
            bc = VerticalBarChart()
            SizeYaxis += bc.valueAxis.tickLeft   
            bc.x = x1 - x + SizeYaxis
            bc.y = y1 - y + SizeXaxis
            bc.height = Height - SizeXaxis
            bc.width  = Width  - SizeYaxis
            self.graphCenterX = bc.x + bc.width/2
            self.graphCenterY = bc.y + bc.height/2
            if self.validData:
                bc.data = self.dataBar
                bc.categoryAxis.categoryNames = self.dataNames
                if len(self.dataNames) < 16:
                    bc.barLabelFormat = self._customSecondsLabelFormat
                    bc.barLabels.dy = 0.08*inch
                    bc.barLabels.fontSize = 9
            else:
                bc.data = [ (0, ), ]
                bc.categoryAxis.categoryNames = [ '' ]
                Nodata = Label()
                Nodata.fontSize = 12
                Nodata.angle = 0
                Nodata.boxAnchor = 'c'
                Nodata.dx = self.graphCenterX
                Nodata.dy = self.graphCenterY
                Nodata.setText("NO VALID DATA")
                self.drawing.add(Nodata)
                
            (R,G,B) = VeriwaveYellow
            bc.bars[0].fillColor   = colors.Color(R,G,B)
            bc.valueAxis.valueMin  = self.valueMin
            bc.valueAxis.valueMax  = self.valueMax
            bc.valueAxis.valueStep = self.valueStep
            bc.valueAxis.labelTextFormat = self._customSecondsLabelFormat
            bc.categoryAxis.labels.boxAnchor = 'ne'
            bc.categoryAxis.labels.dx = 8
            bc.categoryAxis.labels.dy = -2
            bc.categoryAxis.labels.angle = 0
            self.drawing.add(bc)

            #Put the labels on the center of the graph
            self._drawLabels(self.title, "Trial", "Clients")
Esempio n. 46
0
]

tabla = Table()

tabla.setStyle([('TEXTCOLOR', (1, -4), (7, -4), colors.red),
                ('TEXTCOLOR', (0, 0), (0, 3), colors.blue)])
tabla.setStyle([('BACKGROUND', (1, 1), (-1, -1), colors.aliceblue)])
tabla.setStyle([('INNERGRID', (1, 1), (-1, -1), 0.25, colors.darkgray)])

doc = [tabla]

d = Drawing(400, 400)
gb = VerticalBarChart()
gb.x = 50
gb.y = 50
gb.height = 125
gb.width = 300
gb.data = listaDatosEdade
gb.strokeColor = colors.black
gb.valueAxis.valueMin = 0
gb.valueAxis.valueMax = 100
gb.valueAxis.valueStep = 10
gb.categoryAxis.labels.boxAnchor = 'ne'
gb.categoryAxis.labels.dx = 8
gb.categoryAxis.labels.dy = -2
gb.categoryAxis.labels.angle = 30
gb.categoryAxis.categoryNames = listaDatosNome
gb.groupSpacing = 10
gb.barSpacing = 2

d.add(gb)
Esempio n. 47
0
def relatorio_final(request, id):
    analise = get_object_or_404(AnaliseSensorial, id=id)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="relatorio.pdf"'

    # Iniciando variáveis importantes
    buff = BytesIO()

    # Criando arquivos com as dimensões de margem
    arquivo = SimpleDocTemplate(
        buff, rightMargin=40, leftMargin=40, topMargin=40, bottomMargin=18)
    elements = []

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='centered', alignment=TA_JUSTIFY))
    styles.add(ParagraphStyle(name='body', alignment=TA_JUSTIFY, fontSize=10))

    # Iniciando um dicionário de dados sobre o pdf
    dictionary = {'analise': analise, 'elements': elements, 'styles': styles}

    # Renderizando o título do documento
    dictionary['size'] = '20'
    dictionary['text'] = 'Relatório sobre a analise sensorial: ' + \
        str(analise.nome)
    dictionary['style'] = 'title'
    dictionary['spacer'] = 20
    dictionary['type'] = 'normal'
    put_string(dictionary)
    #-------------------------------------------------------------------------

    # Renderizando informações sobre a análise
    dictionary['size'] = '14'
    dictionary['spacer'] = 12
    dictionary['style'] = 'BodyText'
    dictionary['type'] = 'normal'

    dictionary['text'] = 'Nome: ' + str(analise.nome)
    put_string(dictionary)

    dictionary['text'] = 'Descrição: ' + str(analise.descricao)
    put_string(dictionary)

    dictionary['text'] = 'Quantidade de provadores: ' + \
        str(analise.quantidade_pessoas)
    put_string(dictionary)

    dictionary['text'] = 'Quantidade de amostras: ' + \
        str(analise.quantidade_amostras)
    put_string(dictionary)

    dictionary['text'] = 'Fabricante: ' + str(analise.user.first_name)
    put_string(dictionary)
    #-------------------------------------------------------------------------

    # Recebendo perguntas
    perguntas = Pergunta.objects.filter(analise_id=analise.id)

    # Renderizar as perguntas
    dictionary['elements'].append(Spacer(1, 24))
    dictionary['type'] = 'negrito'

    for pergunta in perguntas:
        dictionary['text'] = pergunta.pergunta
        dictionary['size'] = '18'
        dictionary['type'] = 'negrito'
        put_string(dictionary)

        for index in range(analise.quantidade_amostras):
            dictionary['text'] = 'Amostra %s' % transcricao_numero_letra(index)
            dictionary['type'] = 'Normal'
            dictionary['size'] = '14'
            put_string(dictionary)

            grafico = Drawing(400, 150)
            cartoon = VerticalBarChart()

            # Colocar tamanho do gráfico
            cartoon.height = 125
            cartoon.width = 500

            # Colocando os dados no gráfico
            cartoon.strokeColor = colors.black

            # Aplicando valores maximos e minimos para o gráfico
            cartoon.valueAxis.valueMin = 0
            # Aqui ficará a 'quantidade_pessoas'
            cartoon.valueAxis.valueMax = analise.quantidade_pessoas
            cartoon.valueAxis.valueStep = (analise.quantidade_pessoas / 10)

            # Arrumando as labels do gráfico
            cartoon.categoryAxis.labels.boxAnchor = 'ne'
            cartoon.categoryAxis.labels.dx = 10

            # Perguntas sim ou nção
            # Aqui ficará a divisão
            if pergunta.tipo == 'PSN':
                respostas = Boolean.objects.filter(
                    analise_id=id,
                    pergunta_id=pergunta.id,
                    amostra__tipo=transcricao_numero_letra(index)
                )

                contador_true = 0
                contador_false = 0

                for resposta in respostas:
                    if resposta.resposta == True:
                        contador_true += 1
                    else:
                        contador_false += 1

                # Caracterizando o grafico de acordo
                data = [(contador_true, contador_false), ]
                cartoon.data = data
                cartoon.categoryAxis.categoryNames = ['Sim', 'Não']
                cartoon.bars[(0, 0)].fillColor = colors.green
                cartoon.bars[(0, 1)].fillColor = colors.red

                grafico.add(cartoon)
                elements.append(grafico)
                elements.append(Spacer(1, 20))
                total = contador_true + contador_false
                porcentagem_sim = porcentagem(contador_true, total)
                porcentagem_nao = porcentagem(contador_false, total)
                dictionary['text'] = """Nessa questão {por_sim:.2f}{symbol} dos
				provadores responderam SIM - {n} pessoa(s)
				-  e {por_nao:.2f}{symbol} responderam
				NÃO - {n2} pessoa(s).""" .format(symbol="%", por_sim=(porcentagem_sim), n=contador_true,
                                     por_nao=porcentagem_nao, n2=contador_false)

                dictionary['type'] = "Normal"
                dictionary['size'] = "12"
                put_string(dictionary)

                elements.append(Spacer(1, 20))

            # Perguntas Hedônicas
            elif pergunta.tipo == 'PHD':
                respostas = Hedonica.objects.filter(
                    analise_id=id,
                    pergunta_id=pergunta.id,
                    amostra__tipo=transcricao_numero_letra(index)
                )

                # Variáveis
                h_01 = 0
                h_02 = 0
                h_03 = 0
                h_04 = 0
                h_05 = 0
                h_06 = 0
                h_07 = 0
                h_08 = 0
                h_09 = 0

                for resposta in respostas:
                    if resposta.resposta == 1:
                        h_01 += 1
                    elif resposta.resposta == 2:
                        h_02 += 1
                    elif resposta.resposta == 3:
                        h_03 += 1
                    elif resposta.resposta == 4:
                        h_04 += 1
                    elif resposta.resposta == 5:
                        h_05 += 1
                    elif resposta.resposta == 6:
                        h_06 += 1
                    elif resposta.resposta == 7:
                        h_07 += 1
                    elif resposta.resposta == 8:
                        h_08 += 1
                    else:
                        h_09 += 1

                data = [(h_01, h_02, h_03, h_04, h_05, h_06, h_07, h_08, h_09,)]
                cartoon.data = data
                cartoon.categoryAxis.categoryNames = [
                    'Desgostei extremamente',
                    'Desgostei muito',
                    'Desgostei moderadamente',
                    'Desgostei ligeiramente',
                    'Nem gostei / Nem desgostei',
                    'Gostei ligeiramente',
                    'Gostei moderadamente',
                    'Gostei muito',
                    'Gostei muitíssimo'
                ]

                cartoon.bars[(0, 0)].fillColor = colors.green
                cartoon.bars[(0, 1)].fillColor = colors.red
                cartoon.bars[(0, 2)].fillColor = colors.yellow
                cartoon.bars[(0, 3)].fillColor = colors.blue
                cartoon.bars[(0, 4)].fillColor = colors.pink
                cartoon.bars[(0, 5)].fillColor = colors.gray
                cartoon.bars[(0, 6)].fillColor = colors.purple
                cartoon.bars[(0, 7)].fillColor = colors.black
                cartoon.bars[(0, 8)].fillColor = colors.orange

                cartoon.categoryAxis.labels.dx = 8
                cartoon.categoryAxis.labels.dy = -2
                cartoon.categoryAxis.labels.angle = 30

                grafico.add(cartoon)
                elements.append(grafico)
                elements.append(Spacer(1, 60))

                # Variável de menor nome
                q_p = h_01 + h_02 + h_03 + h_04 + h_05 + h_06 + h_07 + h_08 + h_09

                dictionary['size'] = '12'
                dictionary['type'] = 'Normal'
                dictionary['text'] = "Resultados: "
                dictionary['spacer'] = 20
                put_string(dictionary)

                dictionary['spacer'] = 10

                if h_01 != 0:
                    dictionary['text'] = """>{p_01:.2f}{symbol} - {n_01} pessoa(s) -
					responderam que <b>desgostaram
					extremamente</b> dessa amostra.""".format(symbol="%",
                                               p_01=porcentagem(h_01, q_p), n_01=h_01)
                    put_string(dictionary)

                if h_02 != 0:
                    dictionary['text'] = """>{p_02:.2f}{symbol} - {n_02} pessoa(s) -
					responderam que <b>desgostaram muito
					</b> dessa amostra.""".format(symbol="%",
                                   p_02=porcentagem(h_02, q_p), n_02=h_02)
                    put_string(dictionary)

                if h_03 != 0:
                    dictionary['text'] = """>{p_03:.2f}{symbol} - {n_03} pessoa(s) -
					responderam que <b>desgostaram
					moderadamente</b> dessa amostra.""".format(symbol="%",
                                                p_03=porcentagem(h_03, q_p), n_03=h_03)
                    put_string(dictionary)

                if h_04 != 0:
                    dictionary['text'] = """>{p_04:.2f}{symbol} - {n_04} pessoa(s) -
					responderam que <b>desgostaram
					ligeiramente</b> dessa amostra.""".format(symbol="%",
                                               p_04=porcentagem(h_04, q_p), n_04=h_04)
                    put_string(dictionary)

                if h_05 != 0:
                    dictionary['text'] = """>{p_05:.2f}{symbol} - {n_05} pessoa(s) -
					responderam que <b>nem gostaram, nem desgostaram</b>
					dessa amostra.""".format(symbol="%",
                              p_05=porcentagem(h_05, q_p), n_05=h_05)
                    put_string(dictionary)

                if h_06 != 0:
                    dictionary['text'] = """>{p_06:.2f}{symbol} - {n_06} pessoa(s) -
					responderam que <b>gostaram
					ligeiramente</b> dessa amostra.""".format(symbol="%",
                                               p_06=porcentagem(h_06, q_p), n_06=h_06)
                    put_string(dictionary)

                if h_07 != 0:
                    dictionary['text'] = """>{p_07:.2f}{symbol} - {n_07} pessoa(s) -
					responderam que <b>gostaram
					moderadamente</b> dessa amostra.""".format(symbol="%",
                                                p_07=porcentagem(h_07, q_p), n_07=h_07)
                    put_string(dictionary)

                if h_08 != 0:
                    dictionary['text'] = """>{p_08:.2f}{symbol} - {n_08} pessoa(s) -
					responderam que <b>gostaram
					muito</b> dessa amostra.""".format(symbol="%",
                                        p_08=porcentagem(h_08, q_p), n_08=h_08)
                    put_string(dictionary)

                if h_09 != 0:
                    dictionary['text'] = """>{p_09:.2f}{symbol} - {n_09} pessoa(s) -
					responderam que <b>gostaram
					extremamente</b> dessa amostra.""".format(symbol="%",
                                               p_09=porcentagem(h_09, q_p), n_09=h_09)
                    put_string(dictionary)

                elements.append(Spacer(1, 30))

            # Perguntas dissertativas
            elif pergunta.tipo == 'PDT':
                respostas = Dissertativa.objects.filter(
                    analise_id=id,
                    pergunta_id=pergunta.id,
                    amostra__tipo=transcricao_numero_letra(index)
                )

                if respostas:
                    for resposta in respostas:
                        if resposta.resposta != "":
                            dictionary['text'] = "> " + str(resposta.resposta)
                            dictionary['type'] = 'Normal'
                            dictionary['size'] = '12'
                            dictionary['spacer'] = 10
                            put_string(dictionary)
                else:
                    dictionary['text'] = "Nenhuma resposta cadastrada."
                    dictionary['type'] = 'Normal'
                    dictionary['size'] = '12'
                    dictionary['spacer'] = 10
                    put_string(dictionary)

            # Perguntas de intenção de compra
            else:
                respostas = IntencaoCompra.objects.filter(
                    analise_id=id,
                    pergunta_id=pergunta.id,
                    amostra__tipo=transcricao_numero_letra(index)
                )

                ic_01 = 0
                ic_02 = 0
                ic_03 = 0
                ic_04 = 0
                ic_05 = 0
                q_p = analise.quantidade_pessoas
                for resposta in respostas:
                    if resposta.resposta == 1:
                        ic_01 += 1
                    elif resposta.resposta == 2:
                        ic_02 += 1
                    elif resposta.resposta == 3:
                        ic_03 += 1
                    elif resposta.resposta == 4:
                        ic_04 += 1
                    else:
                        ic_05 += 1

                data = [(ic_01, ic_02, ic_03, ic_04, ic_05), ]
                cartoon.data = data
                cartoon.categoryAxis.categoryNames = [
                    'Certamente não compraria',
                    'Possivelmente não compraria',
                    'Talvez comprasse ou não comprasse',
                    'Possivelmente compraria',
                    'Certamente compraria'
                ]

                cartoon.bars[(0, 0)].fillColor = colors.green
                cartoon.bars[(0, 1)].fillColor = colors.red
                cartoon.bars[(0, 2)].fillColor = colors.yellow
                cartoon.bars[(0, 3)].fillColor = colors.blue
                cartoon.bars[(0, 4)].fillColor = colors.pink

                cartoon.categoryAxis.labels.dx = 8
                cartoon.categoryAxis.labels.dy = -2
                cartoon.categoryAxis.labels.angle = 30

                grafico.add(cartoon)
                elements.append(grafico)
                elements.append(Spacer(1, 60))
                dictionary['size'] = '12'
                dictionary['type'] = 'Normal'
                dictionary['text'] = "Resultados: "
                dictionary['spacer'] = 20
                put_string(dictionary)

                q_p = ic_01 + ic_02 + ic_03 + ic_04 + ic_05

                if ic_01 != 0:
                    dictionary['spacer'] = 10
                    dictionary['text'] = """>{p_01:.2f}{symbol} - {n_01} pessoa(s) -
					responderam que <b>Certamente não compraria
					</b> dessa amostra.""".format(symbol="%",
                                   p_01=porcentagem(ic_01, q_p), n_01=ic_01)
                    put_string(dictionary)

                if ic_02 != 0:
                    dictionary['text'] = """>{p_02:.2f}{symbol} - {n_02} pessoa(s) -
					responderam que <b>possivelmente não compraria
					</b> dessa amostra.""".format(symbol="%",
                                   p_02=porcentagem(ic_02, q_p), n_02=ic_02)
                    put_string(dictionary)

                if ic_03 != 0:
                    dictionary['text'] = """>{p_03:.2f}{symbol} - {n_03} pessoa(s) -
					responderam que <b>talvez não comprasse ou talvez comprasse
					</b> dessa amostra.""".format(symbol="%",
                                   p_03=porcentagem(ic_03, q_p), n_03=ic_03)
                    put_string(dictionary)

                if ic_04 != 0:
                    dictionary['text'] = """>{p_04:.2f}{symbol} - {n_04} pessoa(s) -
					responderam que <b>possivelmente
					compraria</b> dessa amostra.""".format(symbol="%",
                                            p_04=porcentagem(ic_04, q_p), n_04=ic_04)
                    put_string(dictionary)

                if ic_05 != 0:
                    dictionary['text'] = """>{p_05:.2f}{symbol} - {n_05} pessoa(s) -
					responderam que <b>certamente compraria</b>
					dessa amostra.""".format(symbol="%",
                              p_05=porcentagem(ic_05, q_p), n_05=ic_05)
                    put_string(dictionary)

                elements.append(Spacer(1, 60))
        elements.append(PageBreak())
    #-------------------------------------------------------------------------

    arquivo.build(elements)
    response.write(buff.getvalue())
    buff.close()
    return response
Esempio n. 48
0
from reportlab.lib import colors
from reportlab.graphics.shapes import Drawing
from reportlab.graphics import renderPDF
from reportlab.graphics.charts.barcharts import VerticalBarChart

draw = Drawing(640, 320)

data = [
    (13, 25, 35,  4, 30, 35),
    (15, 15, 20, 25, 33, 38)
]

vbc = VerticalBarChart()
vbc.x = 120
vbc.y = 50
vbc.height = 125
vbc.width = 300
vbc.data = data
vbc.strokeColor = colors.black

vbc.valueAxis.valueMin = 0
vbc.valueAxis.valueMax = 50
vbc.valueAxis.valueStep = 10

vbc.categoryAxis.labels.boxAnchor = 'ne'
vbc.categoryAxis.labels.dx = 8
vbc.categoryAxis.labels.dy = -2
vbc.categoryAxis.labels.angle = 30
vbc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99',
    'May-99','Jun-99','Jul-99','Aug-99']
Esempio n. 49
0
def makeDocument(filename, pageCallBack=None):
    #the extra arg is a hack added later, so other
    #tests can get hold of the canvas just before it is
    #saved
    global titlelist, closeit
    titlelist = []
    closeit = 0

    c = Canvas(filename)
    c.setPageCompression(0)
    c.setPageCallBack(pageCallBack)
    framePageForm(c)  # define the frame form
    framePage(c, 'PDFgen graphics API test script')
    makesubsection(c, "PDFgen", 10 * inch)
    story = []
    #add some flowables
    story.append(box(Paragraph("Champions", styleT)))
    story.append(Paragraph("Philosophizing", styleH))
    story.append(Paragraph("""
    This is a paragraph in <i>Normal</i> style.  We do understand exactly why
    the system hates me.  I really really hate the autocorrect.  I really do
    not mind the tab-complete function, but the rest of this is shit.""",
                           styleN))
    data = [[query("cid"), query("total_price"), query("gross_margin"), '03',
            '04'],
            ['10', '11', '12', '13', '14'],
            ['20', '21', '22', '23', '24'],
            ['30', '31', '32', '33', '34']]
    t = Table(data)
    t.setStyle(TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green),
                           ('TEXTCOLOR', (0, 0), (1, -1), colors.red)]))
    story.append(t)
    f = Frame(inch, inch, 6.5 * inch, 9 * inch, showBoundary=0)
    f.addFromList(story, c)
    c.showPage()
# END OF PAGE 1
    framePage(c, 'Line Drawing Styles')
    st = []
    st.append(Spacer(0, 0.5 * inch))
    g = Drawing(3, 4)
    f2 = Frame(inch, inch, 6.5 * inch, 9 * inch, showBoundary=0)
    #St.append(g.add(star(c, title="Title", aka="comments", xcenter=2 * inch,
     #                    ycenter=3 * inch, nvertices=5)))
    chart = VerticalBarChart()
    # Set the starting point to be (0, 0).  Changing this value changes
    # the position that the chart is rendered at within it's 'Drawing'
    # space, which we create below.

    chart.x = 0
    chart.y = 0
    # This determines the width, in centimeters (you could use 'inch'
    # as well) of the chart on the paper, as well as the height.
    chart_width = 5 * inch
    chart_height = 4 * inch
    chart.height = chart_height
    chart.width = chart_width
    # The vertical ticks will be labeled from 0 with a value every
    # 15 units, spaced so that the maximum value is 60.
    chart.valueAxis.valueMin = 0
    chart.valueAxis.valueMax = 60
    chart.valueAxis.valueStep = 15
    # Put the labels at the bottom with an interval of 8 units,
    # -2 units below the axis, rotated 30 degrees from horizontal
    chart.categoryAxis.labels.dx = 8
    chart.categoryAxis.labels.dy = -2
    chart.categoryAxis.labels.angle = 30
    # The text box's NE corner (top right) is located at the above
    # coordinate
    chart.categoryAxis.labels.boxAnchor = 'ne'

    # Our various horizontal axis labels
    catNames = ['Jan-06', 'Feb-06', 'Mar-06', 'Apr-06', 'May-06',
                'Jun-06', 'Jul-06', 'Aug-06']
    chart.categoryAxis.categoryNames = catNames

    # Some random data to populate the chart with.
    chart.data = [(8, 5, 20, 22, 37, 28, 30, 47)]

    # Since the 'Chart' class itself isn't a 'Flowable', we need to
    # create a 'Drawing' flowable to contain it.  We want the basic
    # area to be the same size as the chart itself, so we will
    # initialize it with the chart's size.
    g = Drawing(chart_width, chart_height)
    g.add(chart)

    # Add the Chart containing Drawing to our elements list
    st.append(box(g))
    g.add(star(c, title="Right", aka="comments", xcenter=7 * inch,
               ycenter=7 * inch, nvertices=5))
    g.add(star(c, title="Left", aka="comments", xcenter=3 * inch,
               ycenter=7 * inch, nvertices=6))
    st.append(Spacer(1, 1 * inch))
    st.append(box(Paragraph("""
        Well, its now hard to argue that this is working pretty well.  Possibly
        make some nice output charts, and import an image.""", styleH)))
    f2.addFromList(st, c)
    c.showPage()
    c.save()
    return c
Esempio n. 50
0
for algo in data:
  speedup = [[]]
  graphs = []
  for graph in data[algo]:
    cpu_time = data[algo][graph]['time_cpu']
    gpu_time = data[algo][graph]['time_gpu']
    speedup[0].append(cpu_time / gpu_time)
    graphs.append(graph)

  drawing = Drawing(400, 300)

  bc = VerticalBarChart()
  bc.x = 50
  bc.y = 50
  bc.height = 200
  bc.width = 300
  bc.data = speedup
  bc.strokeColor = colors.black

  bc.valueAxis.valueMin = 0
  bc.valueAxis.valueMax = max(speedup[0]) + 1
  bc.valueAxis.valueStep = max(1, int(floor(max(speedup[0]) / 5.)))
  bc.valueAxis.tickRight = 300
  bc.valueAxis.strokeDashArray = [2, 2]

  bc.categoryAxis.labels.boxAnchor = 'ne'
  bc.categoryAxis.labels.dx = 8
  bc.categoryAxis.labels.dy = -2
  bc.categoryAxis.labels.angle = 30
  bc.categoryAxis.categoryNames = graphs
for algo in data:
    speedup = [[]]
    graphs = []
    for graph in data[algo]:
        cpu_time = data[algo][graph]['time_cpu']
        gpu_time = data[algo][graph]['time_gpu']
        speedup[0].append(cpu_time / gpu_time)
        graphs.append(graph)

    drawing = Drawing(400, 300)

    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 200
    bc.width = 300
    bc.data = speedup
    bc.strokeColor = colors.black

    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = max(speedup[0]) + 1
    bc.valueAxis.valueStep = max(1, int(floor(max(speedup[0]) / 5.)))
    bc.valueAxis.tickRight = 300
    bc.valueAxis.strokeDashArray = [2, 2]

    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = graphs
        def _rawDraw(self, x, y):
            from reportlab.lib import colors 
            from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS
            from reportlab.graphics.charts.axes import XCategoryAxis,YValueAxis
            from reportlab.graphics.charts.textlabels import Label
            from reportlab.graphics.charts.barcharts  import VerticalBarChart
            
            self.originX = x
            self.originY = y
            self._setScale([self.dataBar])
            (x1, y1, Width, Height) = self._getGraphRegion(x, y)

            #Build the graph
            self.drawing = Drawing(self.width, self.height)

            #Size of the Axis
            SizeXaxis = 14
            countSteps = int(self.valueMax / self.valueStep)
            SizeYaxis = 0.0
            for n in range(countSteps + 1):
                eachValue = self.valueMin + n * self.valueStep
                textString = self._customSecondsLabelFormat( eachValue )
                SizeYaxis = max(SizeYaxis, self._stringWidth(textString, STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) )

            bc = VerticalBarChart()
            SizeYaxis += bc.valueAxis.tickLeft
            bc.x = x1 - x + SizeYaxis
            bc.y = y1 - y + SizeXaxis
            bc.height = Height - SizeXaxis
            bc.width  = Width  - SizeYaxis
            self.graphCenterX = bc.x + bc.width/2
            self.graphCenterY = bc.y + bc.height/2
            if self.validData:
                # add valid data to chart
                bc.data = self.dataBar
                bc.categoryAxis.categoryNames = self.dataNames
                # axis values
                bc.valueAxis.valueMin  = self.valueMin
                bc.valueAxis.valueMax  = self.valueMax
                bc.valueAxis.valueStep = self.valueStep
                # add value labels above bars
                bc.barLabelFormat = self._customSecondsLabelFormat
                bc.barLabels.dy = 0.08*inch
                bc.barLabels.fontSize = 6
            else:
                # no valid data
                bc.data = [ (0, ), ]
                bc.categoryAxis.categoryNames = [ '' ]
                bc.valueAxis.valueMin  = 0
                bc.valueAxis.valueMax  = 1
                bc.valueAxis.valueStep = 1
                Nodata = Label()
                Nodata.fontSize = 12
                Nodata.angle = 0
                Nodata.boxAnchor = 'c'
                Nodata.dx = self.graphCenterX
                Nodata.dy = self.graphCenterY
                Nodata.setText("NO VALID DATA")
                self.drawing.add(Nodata)
            
            # chart formatting
            (R,G,B) = VeriwaveYellow
            bc.bars[0].fillColor   = colors.Color(R,G,B)
            bc.valueAxis.labelTextFormat = self._customSecondsLabelFormat
            # axis labels
            bc.categoryAxis.labels.boxAnchor = 'c'
            bc.categoryAxis.labels.dx    = 0
            bc.categoryAxis.labels.dy    = -10
            bc.categoryAxis.labels.angle = 0
            bc.categoryAxis.labels.fontSize = 8

            # add chart
            self.drawing.add(bc)

            #Adjust the labels to be the center of the graph
            self._drawLabels(self.title, "", "")

            # Add Legend in upper right corner
            legendHeight  = 9 
            legendX = bc.x + 5
            legendY = bc.y + bc.height - 12
            self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[0].fillColor, strokeWidth=3 ))
            self.drawing.add(String(legendX + 22, legendY, 'MIN', fontName='Helvetica', fontSize=8))
            legendY -= legendHeight
            self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[1].fillColor, strokeWidth=3 ))
            self.drawing.add(String(legendX + 22, legendY, 'MAX', fontName='Helvetica', fontSize=8))
            legendY -= legendHeight
            self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[2].fillColor, strokeWidth=3 ))
            self.drawing.add(String(legendX + 22, legendY, 'AVG', fontName='Helvetica', fontSize=8))
            legendY -= legendHeight
Esempio n. 53
0
def main(argv):
    parser = argparse.ArgumentParser()

    # the following options are provided on the commandline
    parser.add_argument("-f", "--file", action="store", dest="cleanupfile",
                        help="path to cleanup result file", metavar="FILE")
    parser.add_argument("-o", "--output", action="store", dest="outputfile",
                        help="path to output file", metavar="FILE")
    args = parser.parse_args()

    # path of the gzip compressed releases file
    if args.cleanupfile is None:
        parser.error("cleanup file missing")

    if args.outputfile is None:
        parser.error("output file missing")

    if os.path.isdir(args.outputfile):
        print("outputfile %s is a directory, cannot overwrite" % args.outputfile, file=sys.stderr)
        sys.exit(1)

    if not os.path.exists(args.cleanupfile):
        print("result file missing", file=sys.stderr)
        sys.exit(1)

    unique_releases = set()
    cleanupfile = open(args.cleanupfile, 'r')

    # store the number of the last release found with a small in the
    # dataset. This is to ensure that the right amount of columns will
    # be generated in the end through an ugly hack
    max_release_number = 0

    # store the release number for releases with a smell
    for l in cleanupfile:
        if 'https://www.discogs.com/release/' in l and ' -- ' in l:
            #release_number = int(l.rsplit('/', 1)[1])
            release_number = int(l.rsplit('/', 1)[1].split()[0])
            max_release_number = max(max_release_number, release_number)
            unique_releases.add(release_number)
        else:
            print(l)
    cleanupfile.close()

    # count the number of releases, with a smell
    statistics = collections.Counter()
    statistics.update(map(lambda x: x//1000000, unique_releases))

    last_index = max_release_number//1000000

    bardata = (sorted(statistics.items()))
    barwidth = 20

    # sometimes some dummy data need to be inserted to
    # ensure that empty bars are generated if needed
    if len(bardata) != last_index:
        for i in range(0, last_index):
            if bardata[i][0] != i:
                for d in range(0, bardata[i][0] - i):
                    bardata.append((i, 0))
                    bardata.sort()

    print("Unique releases:", len(unique_releases))
    print(bardata)

    maximumvalue = max(map(lambda x: x[1], bardata))
    step = int(math.log(maximumvalue, 10))
    valueStep = pow(10, step)

    # calculate a possible good value for startx so labels are not cut off
    startx = max(10 + step * 10, 30)

    # make sure that the chart is large enough
    chartwidth = len(bardata) * barwidth + 10 * len(bardata)
    drawheight = 225
    drawwidth = chartwidth + startx + 20

    # create the drawing that the barchart will be added to
    drawing = Drawing(drawwidth, drawheight)
    barchart = VerticalBarChart()
    barchart.x = startx
    barchart.y = 20
    barchart.height = 200
    barchart.width = chartwidth
    barchart.data = [tuple(map(lambda x: x[1], bardata))]
    barchart.strokeColor = colors.white
    barchart.valueAxis.valueMin = 0
    barchart.valueAxis.labels.fontSize = 16
    barchart.valueAxis.valueMax = maximumvalue
    barchart.valueAxis.valueStep = valueStep
    barchart.categoryAxis.labels.boxAnchor = 'w'
    barchart.categoryAxis.labels.dx = 0
    barchart.categoryAxis.labels.dy = -10
    #barchart.categoryAxis.labels.angle = -90
    barchart.categoryAxis.labels.fontSize = 16
    barchart.categoryAxis.categoryNames = list(map(lambda x: str(x[0]), bardata))
    barchart.barWidth = barwidth

    drawing.add(barchart)
    renderPM.drawToFile(drawing, args.outputfile, fmt='PNG')
Esempio n. 54
0
""")

from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart

drawing = Drawing(400, 200)

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

bc = VerticalBarChart()
bc.x = 50
bc.y = 50
bc.height = 125
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 = 8
bc.categoryAxis.labels.dy = -2
bc.categoryAxis.labels.angle = 30
bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99',
       'Apr-99','May-99','Jun-99','Jul-99','Aug-99']
Esempio n. 55
0
from reportlab.graphics.shapes import Drawing
from reportlab.platypus import SimpleDocTemplate
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.graphics.charts.piecharts import Pie

d = Drawing(400, 200)

datos = [(13, 5, 14, 31, 24, 42, 7, 10), (1, 3, 6, 6, 6, 15, 27, 31),
         (13, 20, 16, 26, 36, 5, 7, 31)]

gBarra = VerticalBarChart()

gBarra.x = 50
gBarra.y = 50
gBarra.height = 125
gBarra.width = 300
gBarra.data = datos
gBarra.valueAxis.valueMin = 0
gBarra.valueAxis.valueMax = 50
gBarra.valueAxis.valueStep = 10
# podemos ponerle un estilo, sino pondrá el predeterrminado
gBarra.categoryAxis.style = 'stacked'
gBarra.categoryAxis.labels.boxAnchor = 'ne'  # noroeste
gBarra.categoryAxis.labels.dx = 8
gBarra.categoryAxis.labels.dy = -2
gBarra.categoryAxis.labels.angle = 30
gBarra.categoryAxis.categoryNames = [
    'Xan-17', 'Feb-17', 'Mar-17', 'Abr-17', 'Mai-17', 'Xun-17', 'Xul-17',
    'Ago-17'
]
Esempio n. 56
0
def generar_pdf_usuarios_mes(request):
    #print "Genero el PDF"
    mes =0
    anio =0
    story =[]
    fecha_usuarios = x
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "reporte_usuarios_mes.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    

    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    reportes = []
    styles = getSampleStyleSheet()
    fichero_imagen="biblioteca/media/images/Reports-banner.jpg" 

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




    header = Paragraph("Fecha del reporte: "+str(date.today()), styles['Heading1'])
    header2 = Paragraph("Reporte de los usuarios que prestaron espacio en el mes "+str(fecha_usuarios.month)+" del "+str(fecha_usuarios.year), styles['Normal'])
    salto_linea = Paragraph("\n\n", styles["Normal"])





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


    
    headings = ('Fecha préstamo', 'Usuario', 'Nombre del espacio', 'Fecha devolución')
    mes = x.month
    anio = x.year
    n = mes 
    f = mes

  

    
    allreportes = [(i.fecha_prestamo, i.usuario.nombre, i.espacio.nombre_espacio, i.fecha_devolucion) for i in Prestamo.objects.filter(fecha_prestamo__month =mes,fecha_prestamo__year = anio)]
    #print allreportes

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


    #GRAFICA DE BARRAS

    titulo1 = Paragraph("Gráfica comparativa de usuarios que prestaron espacios en el mes "+str(fecha_usuarios.month)+" y el mes anterior a éste. ", estilo['title'])
    drawing = Drawing(400, 200)
    data = [(u1, u2)]
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = data
    bc.bars[0].fillColor = colors.blue
    bc.bars[1].fillColor = colors.red
    bc.strokeColor = colors.black
    bc.fillColor = colors.silver
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = u2+10
    try:
        o = u2 / 2
        if type(o) == 'float':
            bc.valueAxis.valueStep = u2+0.5
        if type(o) == 'int':
            bc.valueAxis.valueStep = o

    except:
        "No se puede"


    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 0
    if mes == 1:
        n = mes + 11
    else:
        f = mes - 1 



    bc.categoryAxis.categoryNames = [ datetime.date(anio, f, 1).strftime('%B'), datetime.date(anio, n, 1).strftime('%B')]
    drawing.add(bc)

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

    



    reportes.append(t)
    reportes.append(Spacer(0, inch*.1))
    reportes.append(Spacer(0, inch*.1))
    reportes.append(titulo1)
    reportes.append(drawing)
    doc.build(reportes)
    response.write(buff.getvalue())
    buff.close()
    return response
Esempio n. 57
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
Esempio n. 58
0
 def createCitationHistogram(self):
     '''
     Routine to create a histogram of citations:
     1. refereed papers to refereed papers
     2. refereed papers to non-refereed papers
     3. non-refereed papers to refereed papers
     4. non-refereed papers to non-refereed papers
     (where 'to X' means 'to the papers of type X in the publication set, used to generate the metrics)
     '''
     # The vertical bar chart will get added to the 'drawing' object
     drawing = Drawing(400, 200)
     # Now we can start constructing the vertical bar chart
     lc = VerticalBarChart()
     lc.x = 30
     lc.y = 50
     lc.height = 125
     lc.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['citation histogram'].keys())))
     # This list will hold the data points for the histogram
     lc.data = []
     # Record the counts for the 4 different types of citations
     ref_ref = []
     ref_non = []
     non_ref = []
     non_non = []
     # The maximum number of citations will be used to scale the y axis
     max_citations = 0
     # Take only the first four values of each value string in the histogram data
     for year in years:
         values = map(lambda a: int(a),self.data['citation histogram'][str(year)].split(':')[:4])
         all2all = values[0]
         all2ref = values[2]
         ref2ref = values[3]
         ref2all = values[1]
         all2non = all2all - all2ref
         ref2non = ref2all - ref2ref
         non2all = all2all - ref2all
         non2ref = all2ref - ref2ref
         non2non = non2all - non2ref
         ref_ref.append(ref2ref)
         ref_non.append(ref2non)
         non_ref.append(non2ref)
         non_non.append(non2non)
         max_citations = max(max_citations,ref2ref,ref2non,non2ref,non2non)
     lc.data.append(ref_ref)
     lc.data.append(ref_non)
     lc.data.append(non_ref)
     lc.data.append(non_non)
     # If there are no citations, just omit this histogram:
     if max_citations == 0:
         return
     # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly
     lc.categoryAxis.labels.dx = -6
     lc.categoryAxis.labels.dy = -6
     # and rotate the labels by 90 degrees
     lc.categoryAxis.labels.angle = 90
     # The label names are the publication years
     lc.categoryAxis.categoryNames = map(lambda a: str(a), years)
     # Define the colors for the various bars
     lc.bars[0].fillColor = colors.red
     lc.bars[1].fillColor = colors.green
     lc.bars[2].fillColor = colors.blue
     lc.bars[3].fillColor = colors.orange
     # Define the value step and maximum for the y axis
     lc.valueAxis.valueMax = int(math.ceil(float(max_citations)/10.0))*10
     lc.valueAxis.valueStep = max(int(math.floor(float(max_citations)/10.0)),1)
     # Now add the histogram to the 'drawing' object
     drawing.add(lc)
     # Add a legend to the histogram so that we now which color means what
     legend = Legend()
     legend.alignment = 'right'
     legend.x = 380
     legend.y = 160
     legend.deltax = 60
     legend.dxTextSpace = 10
     legend.columnMaximum = 6
     items = [(colors.red, 'refereed to refereed'), (colors.green, 'refereed to non-refereed'),(colors.blue, 'non-refereed to refereed'),(colors.orange, 'non-refereed to non-refereed')]
     legend.colorNamePairs = items
     drawing.add(legend, 'legend')
     # Finally add a title to the histogram
     drawing.add(String(200,190,"citation histogram", textAnchor="middle", fillColor='blue'))
     # Append the result to the 'story'
     self.story.append(drawing)
Esempio n. 59
0
def get_pdf_results(task_id):

    # Flask response
    response = Response()
    response.status_code = 200

    task = data.get_task_result(task_id)
    #Saving file to a in-memory file
    output_file = StringIO.StringIO()

    def header_footer(canvas, doc):

        canvas.saveState()

        background = 'static/img/pdf_bg.png'
        canvas.drawImage(background,
                         1 * inch,
                         5.75 * inch,
                         width=8 * inch,
                         height=6 * inch,
                         mask='auto')

        # Header
        logo = Image('static/img/logo/logo.png')
        logo.drawHeight = 0.5 * inch
        logo.drawWidth = 1.75 * inch
        date = datetime.now().strftime("%y-%m-%d %H:%M")
        headerData = [[logo, '', date]]
        headerTable = Table(headerData,
                            colWidths=[2 * inch, 3.58 * inch, 1.2 * inch],
                            style=[('LINEBELOW', (0, 0), (2, 0), 1,
                                    colors.HexColor(0xcccccc)),
                                   ('TEXTCOLOR', (0, 0), (2, 0),
                                    colors.HexColor(0x807F83)),
                                   ('VALIGN', (1, 0), (1, 0), 'MIDDLE'),
                                   ('VALIGN', (2, 0), (2, 0), 'MIDDLE')])
        headerTable.wrapOn(canvas, doc.width, doc.topMargin)
        headerTable.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin)

        pageNum = "Page %d" % doc.page
        footerData = [[
            'KAPSARC Building Energy Assessment Tool (BEAT)', pageNum
        ]]
        footerTable = Table(footerData,
                            colWidths=[5.76 * inch, 1 * inch],
                            style=[('LINEABOVE', (0, 0), (1, 0), 2,
                                    colors.HexColor(0xcccccc)),
                                   ('TEXTCOLOR', (0, 0), (1, 0),
                                    colors.HexColor(0x807F83)),
                                   ('ALIGN', (1, 0), (1, 0), 'RIGHT')])
        footerTable.wrapOn(canvas, doc.width, doc.bottomMargin)
        footerTable.drawOn(canvas, doc.leftMargin, 0.5 * inch)

        canvas.restoreState()

    pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
    pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))
    styles = getSampleStyleSheet()
    # Title
    styles.add(
        ParagraphStyle(name='styleTitle',
                       alignment=TA_CENTER,
                       fontSize=16,
                       fontName='Vera',
                       textColor=colors.HexColor(0x61a659),
                       leading=30,
                       spaceBefore=35,
                       spaceAfter=10))
    # Headings
    styles.add(
        ParagraphStyle(name='styleHeading',
                       parent=styles['Heading2'],
                       fontSize=14,
                       textColor=colors.HexColor(0x807F83),
                       leading=20,
                       spaceBefore=10,
                       underlineProportion=1.1,
                       spaceAfter=10))
    styles.add(
        ParagraphStyle(name='styleHeading2',
                       parent=styles['Heading2'],
                       fontSize=14,
                       textColor=colors.HexColor(0x61a659),
                       leading=20,
                       spaceBefore=20,
                       underlineProportion=1.1,
                       spaceAfter=20))
    styles.add(
        ParagraphStyle(
            name='styleHeading3',
            #alignment= TA_CENTER,
            fontSize=12,
            fontName='Vera',
            textColor=colors.HexColor(0x61a659),
            leading=20,
            spaceBefore=10,
            spaceAfter=5))
    # Body text
    styles.add(
        ParagraphStyle(name='styleBodyText',
                       parent=styles['Normal'],
                       fontSize=9,
                       textColor=colors.HexColor(0x666666),
                       spaceBefore=5,
                       spaceAfter=15))

    styleTitle = styles['styleTitle']
    styleHeading = styles['styleHeading']
    styleHeading2 = styles['styleHeading2']
    styleHeading3 = styles['styleHeading3']
    styleBodyText = styles['styleBodyText']
    pdf_chart_colors = [
        "#3D6531",
        "#61a24f",
        "#89B97B",
        "#B0D1A7",
        "#cde5c7",
        "#7e7f82",
        "#9E9FA1",
        "#BFBFC1",
        "#DFDFE0",
        "#ffd200",
        "#FFE360",
        "#FFEE9F",
    ]

    Elements = []
    doc = BaseDocTemplate(output_file,
                          showBoundary=0,
                          pagesize=A4,
                          title='KASPSARC BEAT Report',
                          author="KAPSARC",
                          leftMargin=0.75 * inch,
                          rightMargin=0.75 * inch,
                          topMargin=inch,
                          bottomMargin=inch)

    frame = Frame(doc.leftMargin,
                  doc.topMargin,
                  doc.width,
                  doc.height,
                  topPadding=0.3 * inch,
                  showBoundary=0)
    template = PageTemplate(id='template',
                            frames=[frame],
                            onPage=header_footer)
    doc.addPageTemplates([template])

    ## PAGE 1
    #add some flowables
    Elements.append(
        Paragraph("KAPSARC Building Energy Assessment Tool (BEAT)",
                  styleTitle))
    Elements.append(Paragraph("Your Building Description", styleHeading))
    rowHeights = 0.3 * inch
    calibrationData = task['calibrationData']
    Elements.append(Paragraph("General Information:", styleHeading3))
    infoTableData = [
        [
            Paragraph('<b>- Name: </b>' + calibrationData['txtBldgName'],
                      styleBodyText),
            Paragraph('<b>- Address: </b>' + calibrationData['txtBldgAddress'],
                      styleBodyText),
            Paragraph('<b>- Type: </b>' + calibrationData['cmbBldgType'],
                      styleBodyText)
        ],
        [
            Paragraph(
                '<b>- Location: </b>' + calibrationData['cmbBldgLocation'],
                styleBodyText),
            Paragraph('<b>- Shape: </b>' + calibrationData['cmbBldgShape'],
                      styleBodyText),
            Paragraph(
                '<b>- Floor Area (m' + u"\u00b2" + '): </b>' +
                str(calibrationData['txtFloorArea']), styleBodyText)
        ]
    ]
    infoTable = Table(infoTableData,
                      colWidths=[160, 165, 150],
                      rowHeights=rowHeights)
    Elements.append(infoTable)

    Elements.append(Paragraph('<br />', styleBodyText))
    Elements.append(Paragraph("Envelope Construction Details:", styleHeading3))
    envTableData = [
        [
            Paragraph(
                '<b>- South Wall: </b>' + calibrationData['cmbSouthWall'],
                styleBodyText),
            Paragraph('<b>- West Wall: </b>' + calibrationData['cmbWestWall'],
                      styleBodyText)
        ],
        [
            Paragraph(
                '<b>- North Wall: </b>' + calibrationData['cmbNorthWall'],
                styleBodyText),
            Paragraph('<b>- East Wall: </b>' + calibrationData['cmbEastWall'],
                      styleBodyText)
        ],
        [
            Paragraph('<b>- Roof: </b>' + calibrationData['cmbRoof'],
                      styleBodyText),
            Paragraph(
                '<b>- Floor: </b>' + calibrationData['cmbFirstFloorContact'],
                styleBodyText)
        ],
        [
            Paragraph('<b>- Windows Type: </b>' + calibrationData['glasstype'],
                      styleBodyText),
            Paragraph(
                '<b>- Overhang Depth (m): </b>' +
                str(calibrationData['txtWinSouthOverhang']), styleBodyText)
        ]
    ]
    envTable = Table(envTableData, colWidths=[240, 235], rowHeights=rowHeights)
    Elements.append(envTable)

    Elements.append(Paragraph('<br />', styleBodyText))
    Elements.append(Paragraph("Air Conditioning Systems", styleHeading3))
    hvacTableData = [[
        Paragraph(
            '<b>- HVAC  System Type: </b>' + calibrationData['cmbBldgSystem'],
            styleBodyText),
        Paragraph(
            '<b>- Cooling Temperature Setting (' + u"\u00b0" + 'C): </b>' +
            str(calibrationData['txtCoolSetTemp']), styleBodyText)
    ],
                     [
                         Paragraph(
                             '<b>- Energy Efficiency Ratio (EER): </b>' +
                             str(calibrationData['eir']), styleBodyText),
                         Paragraph(
                             '<b>- Heating Temperature Setting (' + u"\u00b0" +
                             'C): </b>' +
                             str(calibrationData['txtHeatSetTemp']),
                             styleBodyText)
                     ]]
    hvacTable = Table(hvacTableData,
                      colWidths=[240, 235],
                      rowHeights=rowHeights)
    Elements.append(hvacTable)

    Elements.append(Paragraph('<br />', styleBodyText))
    Elements.append(Paragraph("Overall Assessment", styleHeading))
    Elements.append(
        Paragraph(
            "Based on your description and current SASO requirements, the tool provides the following assessments:",
            styleBodyText))

    if task['compliant']:
        compliant = "<strong><font color=green>meets</font></strong>"
    else:
        compliant = "<strong><font color=red>does not meet</font></strong>"
    if (task['ngEnergyDiff'] < 0):
        energyDiff = "<strong><font color=green>" + str(
            task['energyDiff']) + " kWh/year, less</font></strong>"
    else:
        energyDiff = "<strong><font color=red>" + str(
            task['energyDiff']) + " kWh/year, more</font></strong>"

    Elements.append(
        Paragraph(
            "- Your building " + compliant +
            " SASO requirements for all building envelope", styleBodyText))
    Elements.append(
        Paragraph(
            "- Your building consumed " + energyDiff +
            " than the SASO Baseline", styleBodyText))

    if task['compliant']:
        Elements.append(
            Paragraph(
                "- You may reduce even more your energy consumption in your building by using LED lamps and high efficient appliances and air conditioning system",
                styleBodyText))
    else:
        Elements.append(
            Paragraph(
                " - You need to add more insulation to the walls and/or roof, or use more efficient window glazing to comply with SASO requirements",
                styleBodyText))
    if not task['compliant'] and (task['ngEnergyDiff'] >= 0):
        Elements.append(
            Paragraph(
                " - You may also consider using LED lamps and energy efficient appliances and air conditioning system",
                styleBodyText))

    Elements.append(PageBreak())
    Elements.append(
        Paragraph("How electricity is used in your building?", styleHeading3))
    Elements.append(
        Paragraph(
            "Your building needs electricity to operate several types of equipment including: air-conditioning, lighting, appliances and domestic hot water.",
            styleBodyText))

    #add image
    Elements.append(
        Image('static/img/results-intro.png',
              width=4 * inch,
              height=1.2 * inch))
    #add text
    Elements.append(
        Paragraph(
            "Based on the description you provided as well as typical lighting and appliances used in households, here how your building consumes electricity on annual basis:",
            styleBodyText))

    bepuPieData = task['bepuPieData']
    bepuTableData = [[0 for i in xrange(len(bepuPieData[0]))]
                     for i in xrange(len(bepuPieData) + 1)]
    bepuChartLabel = [0 for i in xrange(len(bepuPieData))]
    bepuChartData = [0 for i in xrange(len(bepuPieData))]
    bepuTableData[0][0] = 'End-Use'
    bepuTableData[0][1] = 'Annual Electricity Use'
    for i, result in enumerate(bepuPieData):
        # write body cells
        bepuTableData[i + 1][0] = str(result['label'])
        bepuTableData[i + 1][1] = int(result['value'])
        bepuChartLabel[i] = str(result['label'])
        bepuChartData[i] = result['value']

    #add chart
    bepuChart = Drawing(400, 200)
    pc = Pie()
    pc.data = bepuChartData
    labelc = [0 for i in xrange(len(bepuChartData))]
    for i, r in enumerate(bepuChartData):
        labelc[i] = str(round(r / sum(bepuChartData) * 100, 1)) + "%"
    pc.labels = labelc
    pc._seriesCount = len(bepuChartLabel)
    pc.slices.strokeColor = colors.HexColor(0xffffff)
    pc.slices.strokeWidth = 0.5
    bepu_chart_colors = ['#FFC43E', '#A4A4A4', '#F67A40', '#5894D0', '#98cd99']
    for i, r in enumerate(bepuChartLabel):
        pc.slices[i].fillColor = colors.HexColor(bepu_chart_colors[i])

    pc.width = pc.height = 120
    pc.x = 40
    pc.y = 30
    # add_legend(d, pc)
    legend = Legend()
    legend.alignment = 'right'
    legend.x = pc.width + pc.x + 80
    legend.y = pc.height - 10
    legend.dx = 8
    legend.dy = 8
    legend.fontName = 'Helvetica'
    legend.fillColor = colors.HexColor(0x807F83)
    legend.fontSize = 10
    legend.boxAnchor = 'nw'
    legend.columnMaximum = 8
    legend.strokeWidth = 0.5
    legend.strokeColor = colors.HexColor(0xffffff)
    legend.deltax = 75
    legend.deltay = 10
    legend.autoXPadding = 10
    legend.yGap = 0
    legend.dxTextSpace = 5
    legend.dividerLines = 1 | 2 | 4
    legend.dividerOffsY = 6
    legend.subCols.rpad = 70
    legend.dividerColor = colors.HexColor(0xdedede)
    legend.colorNamePairs = [(pc.slices[i].fillColor,
                              (bepuChartLabel[i][0:20],
                               '  %s ' % "{:,}".format(int(pc.data[i]))))
                             for i in xrange(len(pc.data))]
    legendHeader = Legend()
    legendHeader.colorNamePairs = [
        ('', ('End-Use', 'Annual Electricity Use\n(kWh/year)'))
    ]
    legendHeader.alignment = 'right'
    legendHeader.x = legend.x - 20
    legendHeader.y = legend.y + 30
    legendHeader.fontName = 'Helvetica'
    legendHeader.fillColor = colors.HexColor(0x807F83)
    legendHeader.fontSize = 10
    legendHeader.boxAnchor = 'nw'
    legendHeader.subCols.rpad = 80
    legendFooter = Legend()
    legendFooter.colorNamePairs = [
        ('', ('Total', str("{:,}".format(int(sum(bepuChartData)))) + ''))
    ]
    legendFooter.alignment = 'right'
    legendFooter.x = legendHeader.x + 5
    legendFooter.y = legend.y - (len(bepuChartLabel) + 1) * 10
    legendFooter.fontName = 'Helvetica-Bold'
    legendFooter.fillColor = colors.HexColor(0x807F83)
    legendFooter.fontSize = 10
    legendFooter.boxAnchor = 'nw'
    legendFooter.subCols.rpad = 145
    bepuChart.add(legend)
    bepuChart.add(legendHeader)
    bepuChart.add(legendFooter)
    pc.slices.fontColor = colors.HexColor(0x807F83)
    n = len(pc.data)
    bepuChart.add(pc, '')
    Elements.append(bepuChart)

    ## PAGE 2
    Elements.append(
        Paragraph("When electricity is consumed in your building?",
                  styleHeading3))
    Elements.append(
        Paragraph(
            "Based on the weather of your location as well as typical lighting and appliances used in households, your building consumes electricity as noted in the following monthly profile:",
            styleBodyText))
    #add chart
    pseBarData = task['pseBarData']

    pseTableData = [[0 for i in xrange(len(pseBarData[0]['values']) + 1)]
                    for i in xrange(len(pseBarData) + 1)]
    pseChartData = [[0 for i in xrange(len(pseBarData[0]['values']))]
                    for i in xrange(len(pseBarData))]
    pseChartLegend = [0 for i in xrange(len(pseBarData))]
    pseTableData[0][0] = 'Key'
    month = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
    ]
    for i, m in enumerate(month):
        pseTableData[0][i + 1] = str(month[i])
    for i, result in enumerate(pseBarData):
        # write body cells
        pseTableData[i + 1][0] = str(result['key'])
        pseChartLegend[i] = str(result['key'])
        for j, value in enumerate(result['values']):
            pseTableData[i + 1][j + 1] = int(result['values'][j]['y'])
            pseChartData[i][j] = int(result['values'][j]['y'])

    pseChart = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 70
    bc.y = 0
    bc.height = 200
    bc.width = 300
    bc.data = pseChartData
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.strokeWidth = 0
    bc.valueAxis.valueMin = 0
    bc.categoryAxis.style = 'stacked'
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 10
    bc.categoryAxis.labels.dy = -2
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.strokeWidth = 0.5
    bc.valueAxis.strokeColor = colors.HexColor(0x807F83)
    bc.categoryAxis.strokeWidth = 0.5
    bc.categoryAxis.strokeColor = colors.HexColor(0x807F83)
    bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 10
    bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.categoryNames = month
    # create a list and add the elements of our document (image, paragraphs, table, chart) to it
    #add our barchart and legend
    bc.barWidth = .3 * inch
    bc.groupSpacing = .2 * inch

    bc.bars.strokeColor = colors.HexColor(0xffffff)
    bc.bars.strokeWidth = 0.
    pse_chart_colors = ['#FFC43E', '#A4A4A4', '#F67A40', '#5894D0']
    for i, r in enumerate(pseChartLegend):
        bc.bars[i].fillColor = colors.HexColor(pse_chart_colors[i])
    #  = colors.blue
    legend = Legend()
    legend.alignment = 'right'
    legend.x = bc.width + bc.x + 5
    legend.y = bc.height + bc.y
    legend.deltax = 40
    legend.dxTextSpace = 5
    legend.dx = 8
    legend.dy = 8
    legend.fontName = 'Helvetica'
    legend.fillColor = colors.HexColor(0x807F83)
    legend.fontSize = 10
    legend.boxAnchor = 'nw'
    legend.columnMaximum = (len(bc.data) + 1) / 2
    legend.strokeWidth = 0.5
    legend.strokeColor = colors.HexColor(0xffffff)
    legend.deltax = 75
    legend.deltay = 12
    legend.dividerColor = colors.HexColor(0xdedede)
    legend.columnMaximum = len(pseChartLegend)
    legend.colorNamePairs = [(bc.bars[i].fillColor, pseChartLegend[i])
                             for i in xrange(len(bc.data))]
    #pseChart.hAlign = 'RIGHT'

    label = Label()
    label.setOrigin(10, bc.height / 2)
    #label.boxAnchor = 'sw'
    label.angle = 90
    label.fillColor = colors.HexColor(0x807F83)
    label.setText('Electricity Consumption (kWh)')
    label.fontName = 'Helvetica'

    pseChart.add(legend, 'legend')
    pseChart.add(bc)
    pseChart.add(label)
    Elements.append(pseChart)

    Elements.append(PageBreak())

    ## PAGE 3
    Elements.append(
        Paragraph(
            "Does your building meet SASO Thermal Performance Requirements?",
            styleHeading3))
    Elements.append(
        Paragraph(
            "Based on your description, the thermal transmittance properties of the walls, roof and glazing are calculated, and compared with SASO thermal building performance requirements:",
            styleBodyText))

    #add chart
    lvdData = task['lvdData']
    lvdChartData = [[0 for i in xrange(len(lvdData[0]['values']))]
                    for i in xrange(len(lvdData))]
    lvdChartCategoryNames = [0 for i in xrange(len(lvdData[0]['values']))]
    lvdComparedObjKey = [0 for i in xrange(len(lvdData))]
    for i, result in enumerate(lvdData):
        # write body cells
        lvdComparedObjKey[i] = str(lvdData[i]['key'])
        for j, value in enumerate(result['values']):
            lvdChartCategoryNames[j] = value['label']
            lvdChartData[i][j] = value['value']

    lvdChart = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 70
    bc.y = 0
    bc.height = 200
    bc.width = 300
    bc.data = lvdChartData
    bc.strokeColor = colors.black
    # bc.fillColor=colors.blue
    bc.valueAxis.valueMin = 0
    bc.strokeWidth = 0
    bc.valueAxis.valueMin = 0
    bc.categoryAxis.labels.boxAnchor = 'n'
    bc.categoryAxis.labels.dx = 0
    bc.categoryAxis.labels.dy = -2
    # bc.categoryAxis.labels.angle = 20
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.strokeWidth = 0.5
    bc.valueAxis.strokeColor = colors.HexColor(0x807F83)
    bc.categoryAxis.strokeWidth = 0.5
    bc.categoryAxis.strokeColor = colors.HexColor(0x807F83)
    bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 8
    bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.categoryNames = lvdChartCategoryNames
    bc.categoryAxis.labels.angle = 0
    # create a list and add the elements of our document (image, paragraphs, table, chart) to it
    #add our barchart and legend
    bc.barWidth = .3 * inch
    bc.groupSpacing = .2 * inch

    bc.bars.strokeColor = colors.HexColor(0xffffff)
    bc.bars.strokeWidth = 0.5
    lvd_chart_colors = ['#5894D0', '#F67A40']
    for i, r in enumerate(lvdComparedObjKey):
        bc.bars[i].fillColor = colors.HexColor(lvd_chart_colors[i])

    #  = colors.blue
    legend = Legend()
    legend.alignment = 'right'
    legend.x = bc.width + bc.x + 5
    legend.y = bc.height + bc.y
    legend.deltax = 40
    legend.dxTextSpace = 5
    legend.dx = 8
    legend.dy = 8
    legend.fontName = 'Helvetica'
    legend.fillColor = colors.HexColor(0x807F83)
    legend.fontSize = 10
    legend.boxAnchor = 'nw'
    legend.columnMaximum = (len(bc.data) + 1) / 2
    legend.strokeWidth = 0.5
    legend.strokeColor = colors.HexColor(0xffffff)
    legend.deltax = 75
    legend.deltay = 12
    legend.dividerColor = colors.HexColor(0xdedede)
    legend.columnMaximum = len(lvdComparedObjKey)
    legend.colorNamePairs = [(bc.bars[i].fillColor, lvdComparedObjKey[i])
                             for i in xrange(len(bc.data))]
    #pseChart.hAlign = 'RIGHT'

    label = Label()
    label.setOrigin(10, bc.height / 2)
    #label.boxAnchor = 'sw'
    label.angle = 90
    label.fillColor = colors.HexColor(0x807F83)
    label.setText('Envelope U-value (W/m' + u'\u00b2' + '.k)')
    label.fontName = 'Helvetica'

    lvdChart.add(label)
    lvdChart.add(legend, 'legend')
    lvdChart.add(bc)
    Elements.append(lvdChart)

    #Elements.append(PageBreak())
    Elements.append(Paragraph('<br /><br />', styleBodyText))
    ## PAGE 4
    Elements.append(
        Paragraph("How energy efficient is your building?", styleHeading3))
    Elements.append(
        Paragraph(
            "Using your input specifications, the annual electricity consumption is calculated and compared with a similar building that meets SASO requirements:",
            styleBodyText))

    #add chart
    bepuComparisonData = task['bepuComparisonData']

    bepuComparisonChartData = [[
        0 for i in xrange(len(bepuComparisonData[0]['values']))
    ] for i in xrange(len(bepuComparisonData))]
    bepuChartCategoryNames = [
        0 for i in xrange(len(bepuComparisonData[0]['values']))
    ]
    bepuComparedObjKey = [0 for i in xrange(len(bepuComparisonData))]
    for i, result in enumerate(bepuComparisonData):
        # write body cells
        bepuComparedObjKey[i] = str(bepuComparisonData[i]['key'])
        for j, value in enumerate(result['values']):
            bepuChartCategoryNames[j] = value['label']
            bepuComparisonChartData[i][j] = value['value']

    bepuComparisonChart = Drawing(400, 200)
    bc = VerticalBarChart()
    bc.x = 70
    bc.y = 0
    bc.height = 200
    bc.width = 300
    bc.data = bepuComparisonChartData
    bc.strokeColor = colors.black
    # bc.fillColor=colors.blue
    bc.valueAxis.valueMin = 0
    bc.strokeWidth = 0
    bc.valueAxis.valueMin = 0
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 10
    bc.categoryAxis.labels.dy = -2
    # bc.categoryAxis.labels.angle = 20
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.strokeWidth = 0.5
    bc.valueAxis.strokeColor = colors.HexColor(0x807F83)
    bc.categoryAxis.strokeWidth = 0.5
    bc.categoryAxis.strokeColor = colors.HexColor(0x807F83)
    bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 10
    bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83)
    bc.categoryAxis.categoryNames = bepuChartCategoryNames
    bc.categoryAxis.labels.angle = 30
    # create a list and add the elements of our document (image, paragraphs, table, chart) to it
    #add our barchart and legend
    bc.barWidth = .3 * inch
    bc.groupSpacing = .2 * inch

    bc.bars.strokeColor = colors.HexColor(0xffffff)
    bc.bars.strokeWidth = 0.5
    bepu_chart_colors = ['#5894D0', '#F67A40']
    for i, r in enumerate(bepuComparedObjKey):
        bc.bars[i].fillColor = colors.HexColor(bepu_chart_colors[i])
    #  = colors.blue
    # bc.bars[1].fillColor = colors.lightblue
    legend = Legend()
    legend.alignment = 'right'
    legend.x = bc.width + bc.x + 5
    legend.y = bc.height + bc.y
    legend.deltax = 40
    legend.dxTextSpace = 5
    legend.dx = 8
    legend.dy = 8
    legend.fontName = 'Helvetica'
    legend.fillColor = colors.HexColor(0x807F83)
    legend.fontSize = 10
    legend.boxAnchor = 'nw'
    legend.columnMaximum = (len(bc.data) + 1) / 2
    legend.strokeWidth = 0.5
    legend.strokeColor = colors.HexColor(0xffffff)
    legend.deltax = 75
    legend.deltay = 12
    legend.dividerColor = colors.HexColor(0xdedede)
    legend.columnMaximum = len(bepuComparedObjKey)
    legend.colorNamePairs = [(bc.bars[i].fillColor, bepuComparedObjKey[i])
                             for i in xrange(len(bc.data))]
    #pseChart.hAlign = 'RIGHT'

    label = Label()
    label.setOrigin(10, bc.height / 2)
    #label.boxAnchor = 'sw'
    label.angle = 90
    label.fillColor = colors.HexColor(0x807F83)
    label.setText('Annual Energy Use (kWh/year)')
    label.fontName = 'Helvetica'

    bepuComparisonChart.add(label)
    bepuComparisonChart.add(legend, 'legend')
    bepuComparisonChart.add(bc)
    Elements.append(bepuComparisonChart)

    Elements.append(PageBreak())

    doc.build(Elements)

    output_file.seek(0)

    # Set filname and mimetype
    file_name = 'K-BEAT_export_{}.pdf'.format(
        datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    #Returning the file from memory
    return send_file(output_file,
                     attachment_filename=file_name,
                     as_attachment=True)