Пример #1
0
def draw_temper_pulse(value, step, x_coord, y_coord):
    drawing = Drawing(x_coord, y_coord)
    data = []
    catNames = []
    min_value = 0
    max_value = 0
    for k, v in value.items():
        if k == 'data':
            data1 = tuple([i for i in v])
            data.append(data1)
        if k == 'xtext':
            catNames = [i.replace(' ', '\n') for i in v]
        if k == 'min_max':
            min_value = v[0] - step
            max_value = v[1] + step

    lc = HorizontalLineChart()
    lc.x = 15
    lc.y = 0
    lc.height = 28 * mm
    lc.width = 250 * mm
    lc.data = data
    lc.joinedLines = 1
    lc.strokeColor = colors.white
    lc.strokeColor = None
    # из markers
    lc.lines.symbol = makeMarker('FilledSquare')
    lc.lines.symbol.size = 4
    # lineLabels - свойства надбисей линии из textlabels class Label(Widget):
    lc.lineLabels.fontSize = 9
    lc.lineLabels.fontName = 'PTAstraSerifBold'
    lc.lineLabels.angle = 0
    lc.lineLabels.dx = 2
    lc.lineLabels.dy = 1
    lc.lines[0].strokeColor = colors.black
    lc.lineLabelFormat = '%3.1f'

    lc.categoryAxis.categoryNames = catNames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.categoryAxis.labels.angle = 0
    lc.categoryAxis.labels.dy = -2
    lc.categoryAxis.labels.dx = 0
    lc.categoryAxis.labels.fontSize = 9
    lc.categoryAxis.labels.fontName = 'PTAstraSerifReg'
    lc.categoryAxis.labels.leading = 8

    lc.valueAxis.valueMin = min_value
    lc.valueAxis.valueMax = max_value
    lc.valueAxis.valueStep = step
    lc.valueAxis.labels.fontName = 'PTAstraSerifReg'
    lc.valueAxis.labels.fontSize = 9
    drawing.add(lc)

    return drawing
Пример #2
0
def sample1line(data=[(13, 5, 20, 22, 37, 45, 19, 4)]):
    drawing = Drawing(400, 200)

    bc = HorizontalLineChart()
    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 = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ')
    catNames = [n+'-99' for n in catNames]
    bc.categoryAxis.categoryNames = catNames
    drawing.add(bc)

    return drawing
Пример #3
0
def sample1line(data=[(13, 5, 20, 22, 37, 45, 19, 4)]):
    drawing = Drawing(400, 200)

    bc = HorizontalLineChart()
    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
Пример #4
0
    def makeLineChart(self, context, width, height, data, xvalues, backgroundColor, borderColor, labelAngles,
                      labelXOffsets, labelYOffsets, lineColors, lineWidths, lineLabelFormat, yAxisMin, yAxisMax,
                      yAxisStep):
        content = []

        drawing = Drawing(width, height)

        lp = HorizontalLineChart()
        lp.x = 0
        lp.y = 0
        lp.height = height
        lp.width = width
        lp.data = data
        lp.joinedLines = 1

        if backgroundColor:
            lp.fillColor = colors.HexColor(backgroundColor)

        if borderColor:
            lp.strokeColor = colors.HexColor(borderColor)

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

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

        if yAxisStep:
            lp.valueAxis.valueStep = yAxisStep

        if xvalues:
            lp.categoryAxis.categoryNames = xvalues

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

        if labelXOffsets is not None:
            self.handleSingleOrList(lp.categoryAxis.labels, labelXOffsets, 'dx', len(data[0]))

        if labelYOffsets is not None:
            self.handleSingleOrList(lp.categoryAxis.labels, labelYOffsets, 'dy', len(data[0]))

        if lineLabelFormat:
            lp.lineLabelFormat = lineLabelFormat

        if lineColors:
            self.handleSingleOrList(lp.lines, lineColors, 'strokeColor', len(data), colors.HexColor)

        if lineWidths:
            self.handleSingleOrList(lp.lines, lineWidths, 'strokeWidth', len(data))

        drawing.add(lp)

        content.append( drawing )

        return content
Пример #5
0
def draw_pressure(value, step, x_coord, y_coord):
    drawing = Drawing(x_coord, y_coord)
    data = []
    data_diastolic = value['Диастолическое давление (мм рт.с)']
    data1 = [i for i in data_diastolic['data']]
    data.append(tuple(data1))
    min_max = data_diastolic['min_max']
    data_systolic = value['Систолическое давление (мм рт.с)']
    data1 = [i for i in data_systolic['data']]
    data.append(tuple(data1))
    catNames = [i.replace(' ', '\n') for i in data_diastolic['xtext']]
    min_max.extend(data_systolic['min_max'])
    min_value = min(min_max) - step
    max_value = max(min_max) + step

    lc = HorizontalLineChart()
    lc.x = 15
    lc.y = 0
    lc.height = 45 * mm
    lc.width = 250 * mm
    lc.data = data
    lc.joinedLines = 1
    lc.strokeColor = colors.white
    # из markers
    lc.lines[0].symbol = makeMarker('FilledCircle')
    lc.lines.symbol = makeMarker('FilledSquare')
    lc.lines.symbol.size = 4
    # lineLabels - свойства надбисей линии из textlabels class Label(Widget):
    lc.lineLabels.fontSize = 9
    lc.lineLabels.fontName = 'PTAstraSerifBold'
    lc.lineLabels.angle = 0
    lc.lineLabels.dx = 2
    lc.lineLabels.dy = -1
    lc.lines[0].strokeColor = colors.black
    lc.lines[1].strokeColor = colors.black
    lc.lines[0].strokeDashArray = [3, 3]
    lc.lineLabelFormat = '%3.1f'

    lc.categoryAxis.categoryNames = catNames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.categoryAxis.labels.angle = 0
    lc.categoryAxis.labels.dy = -2
    lc.categoryAxis.labels.dx = 0
    lc.categoryAxis.labels.fontSize = 9
    lc.categoryAxis.labels.fontName = 'PTAstraSerifReg'
    lc.categoryAxis.labels.leading = 8
    lc.valueAxis.valueMin = min_value
    lc.valueAxis.valueMax = max_value
    lc.valueAxis.valueStep = step
    lc.valueAxis.labels.fontName = 'PTAstraSerifReg'
    lc.valueAxis.labels.fontSize = 9
    drawing.add(lc)
    return drawing
Пример #6
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
Пример #7
0
    def pdf_drawPolyline(self,
                         table_data,
                         table_lable=[],
                         title="",
                         title_size=70,
                         title_font=FONTBLOD,
                         x=350,
                         y=1800,
                         width=2000,
                         height=1000,
                         line_width=8,
                         lable_color=HexColor(0x000000),
                         lable_angle=45,
                         lable_fontsize=30,
                         legend_y=450):
        '''
            @example:

                    chart_data_1 = {
                        'name': 'Occupancy ',
                        'data':   [1,2,3,5,6,8],
                        'color':  HexColor(0x2ebf70)
                        }
                    chart_data = []
                    chart_data.append(chart_data_1)
                    self.pdf_drawPolyline(chart_data)
        '''

        y = self.pdf_config_object.pdf_height - y
        chart_values = []
        size = len(table_data)
        if size == 0:
            return
        width_single = width / size / 4 / 3
        step = width / size
        x_position_tmp = x + step / 3
        y_position = y + 70 * 3 + height
        title_position = self.get_title_position(width, title, title_size)
        self.pdf_page_object.setFillColor(HexColor(0x000000))
        self.pdf_page_object.setFont(title_font, title_size)
        self.pdf_page_object.drawString(x + title_position - 120,
                                        y + height + title_size * 5 - 200,
                                        title)
        self.pdf_page_object.setLineWidth(line_width)
        i = 0
        for single in table_data:
            chart_values.append(single['data'])
            self.pdf_page_object.setStrokeColor(single['color'])
            x_position = x_position_tmp + (i) * step
            self.pdf_page_object.line(x_position,
                                      y_position - legend_y - height,
                                      x_position + width_single * 0.8,
                                      y_position - legend_y - height)
            self.pdf_page_object.setFont(FONTBLOD, 40)
            self.pdf_page_object.setFillColor(HexColor(0x000000))
            self.pdf_page_object.drawString(x_position + width_single,
                                            y_position - legend_y - height,
                                            single['name'])
            i = i + 1
        drawing = Drawing(x, y)
        lc = HorizontalLineChart()
        lc.valueAxis.visible = 0
        lc.categoryAxis.gridStrokeColor = colors.gray
        lc.valueAxis.gridStrokeColor = colors.gray
        lc.valueAxis.visibleGrid = 1
        lc.valueAxis.labels.visible = 0
        lc.height = height
        lc.width = width
        lc.data = chart_values
        lc.categoryAxis.categoryNames = table_lable
        lc.categoryAxis.labels.fontName = FONTBLOD
        lc.strokeColor = HexColor(0xffffff)
        lc.categoryAxis.labels.angle = 0
        lc.categoryAxis.labels.strokeColor = lable_color
        lc.categoryAxis.labels.angle = lable_angle
        lc.categoryAxis.labels.dy = -60
        lc.categoryAxis.labels.fontSize = lable_fontsize
        lc.valueAxis.valueMin = 0
        y_value_max = self.get_biggest_value(chart_values) + 20
        lc.valueAxis.valueMax = (y_value_max / 10) * 13
        lc.valueAxis.valueStep = (y_value_max / 10) * 13 / 5
        lc.lines.strokeWidth = line_width
        for i in range(size):
            lc.lines[i].strokeColor = table_data[i]['color']
        if len(chart_values[0]) == 0:
            return
        drawing.add(lc)
        drawing.drawOn(self.pdf_page_object, x, y)
        labelArr = []
        step = (y_value_max / 10) * 13 / 5
        valueMax = (y_value_max / 10) * 13
        for i in range(5):
            labelArr.append(i * step)
            self.pdf_page_object.drawString(x - 100,
                                            y + height * i * step / valueMax,
                                            format(i * step, ','))
        self.pdf_page_object.drawString(x - 100, y + height,
                                        format(5 * step, ','))
        lenthOfLabelLine = 100
        arrLabeled = []
        for item in table_data:
            self.pdf_page_object.setStrokeColor(item['color'], 1)
            self.pdf_page_object.setLineWidth(3)
            self.pdf_page_object.setFillColor(item['color'])
            peakData = self.get_max_data(item['data'])
            for peakInLoop in peakData:
                peakDataOne = peakInLoop['value']
                posInarry = peakInLoop['index']
                posYOfPeak = y + height * peakDataOne / valueMax + 10
                posXOfPeak = x + width / len(item['data']) * (
                    posInarry + 1) - width / len(item['data']) / 2 + 20
                if posInarry in arrLabeled:
                    lenthOfLabelLine = lenthOfLabelLine + 80
                deltaX, deltaY = self.get_randomdelta(lenthOfLabelLine)
                self.pdf_page_object.line(posXOfPeak, posYOfPeak,
                                          posXOfPeak + deltaX,
                                          posYOfPeak + deltaY)
                self.pdf_page_object.drawCentredString(
                    posXOfPeak + deltaX, posYOfPeak + deltaY + 10,
                    format(peakDataOne, ','))
                arrLabeled.append(posInarry)
                lenthOfLabelLine = 100
Пример #8
0
def sample1line(datastring="""
	1997 1998 1999 2000 2001 ,
	pink -10 11 40 22 30 ,
	blue 11 40 22 30 -10,
	cyan 40 22 30 -10 11
"""):
    # parse the data
    lines = datastring.split(",")
    titlestring = lines[0]
    titles = titlestring.split()
    data = []
    alldata = []
    linecolors = []
    for dataline in lines[1:]:
        sline = dataline.split()
        linecolor = sline[0]
        numbers = list(map(float, sline[1:]))
        linecolors.append(linecolor)
        data.append(numbers)
        alldata.extend(numbers)
    drawing = Drawing(400, 200)
    
    bc = HorizontalLineChart()
    bc.x = 25
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = data

    bc.strokeColor = colors.black

    bc.valueAxis.valueMin = min(0, min(alldata)-5) #-10
    bc.valueAxis.valueMax = max(20, max(alldata)+5) #40
    bc.valueAxis.valueStep = 10
    bc.valueAxis.visibleGrid = 1
    bc.valueAxis.gridStrokeColor = colors.blue
    bc.valueAxis.gridStart = 0
    bc.valueAxis.gridEnd = 300
    bc.valueAxis.labelTextFormat ="%s%%"
    #bc.valueAxis.joinAxisPos = -10
    
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 0
    bc.categoryAxis.joinAxis = bc.valueAxis
    bc.categoryAxis.joinAxisMode = "bottom"
    bc.categoryAxis.visibleGrid = 1
    
    #bc.lines[0].strokeColor = colors.pink
    #bc.lines[1].strokeColor = colors.lavender
    #bc.lines[2].strokeColor = colors.skyblue
    linenumber = 0
    for colorname in linecolors:
        bc.lines[linenumber].strokeColor = getattr(colors, colorname)
        bc.lines[linenumber].strokeWidth = 3
        linenumber = linenumber+1

    catNames = titles
    bc.categoryAxis.categoryNames = catNames
    drawing.add(bc)

    return drawing
Пример #9
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
Пример #10
0
    def makeLineChart(self, context, width, height, data, xvalues,
                      backgroundColor, borderColor, labelAngles, labelXOffsets,
                      labelYOffsets, lineColors, lineWidths, lineLabelFormat,
                      yAxisMin, yAxisMax, yAxisStep):
        content = []

        drawing = Drawing(width, height)

        lp = HorizontalLineChart()
        lp.x = 0
        lp.y = 0
        lp.height = height
        lp.width = width
        lp.data = data
        lp.joinedLines = 1

        if backgroundColor:
            lp.fillColor = colors.HexColor(backgroundColor)

        if borderColor:
            lp.strokeColor = colors.HexColor(borderColor)

        if yAxisMin:
            lp.valueAxis.valueMin = yAxisMin

        if yAxisMax:
            lp.valueAxis.valueMax = yAxisMax

        if yAxisStep:
            lp.valueAxis.valueStep = yAxisStep

        if xvalues:
            lp.categoryAxis.categoryNames = xvalues

        def handleSingleOrList(targetObject,
                               value,
                               propertyName,
                               defaultLength,
                               mapFunc=None):
            if isinstance(value, list):
                for i in range(0, len(value)):
                    setattr(targetObject[i], propertyName,
                            value[i] if not mapFunc else mapFunc(value[i]))
            else:
                for i in range(0, defaultLength):
                    setattr(targetObject[i], propertyName,
                            value if not mapFunc else mapFunc(value))

        if labelAngles:
            handleSingleOrList(lp.categoryAxis.labels, labelAngles, 'angle',
                               len(data[0]))

        if labelXOffsets:
            handleSingleOrList(lp.categoryAxis.labels, labelXOffsets, 'dx',
                               len(data[0]))

        if labelYOffsets:
            handleSingleOrList(lp.categoryAxis.labels, labelYOffsets, 'dy',
                               len(data[0]))

        if lineLabelFormat:
            lp.lineLabelFormat = lineLabelFormat

        if lineColors:
            handleSingleOrList(lp.lines, lineColors, 'strokeColor', len(data),
                               colors.HexColor)

        if lineWidths:
            handleSingleOrList(lp.lines, lineWidths, 'strokeWidth', len(data))

        drawing.add(lp)

        content.append(drawing)

        return content