コード例 #1
0
def main():
	f = file("Translate1-2004-01-09-g(9.8).txt")
	timex = []
	timey = []
	timez = []
	for line in f:		
		list = line.split(' ')
		timex.append((float(list[0]), float(list[1])))
		timey.append((float(list[0]), float(list[2])))

	drawing = Drawing(400,600)
	
	max_time, _ = timex[len(timex)-1]
	_, max_x = timex[len(timex)-1]	
	
	lineplot_x = LinePlot()	
	lineplot_x.x = max_time+1
	##lineplot_x.x = 50
	lineplot_x.y = max_x+1
	##lineplot_x.y = 50
	lineplot_x.height = 125
	lineplot_x.width = 300	
	lineplot_x.data = [timex]
	drawing.add(lineplot_x)
	
	_, max_y = timey[len(timey)-1]
	lineplot_y = LinePlot()
	lineplot_y.x = max_time+1
	lineplot_y.y = max_y+1
	lineplot_y.height = 125
	lineplot_y.width = 300
	lineplot_y.data = [timey]
	##drawing.add(lineplot_y)
	
##	renderPDF.drawToFile(drawing, 'XVal1VsTime-2004-01-09-g(9.8).pdf', 'XvsTime')
##	_, max_y = timex[len(timey)-1]
##	lineplot_y = LinePlot()	
	
	##write data to files
	file_x = file("xpos.txt", 'w')
	for item in timex:
		str = item.__str__()
		str = str.replace('(', '')
		str = str.replace(')', '')
		str = str.replace(',', '')
		file_x.write(str + '\n')
		
	file_y = file("ypos.txt", 'w')
	for item in timey:
		str = item.__str__()
		str = str.replace('(', '')
		str = str.replace(')', '')
		str = str.replace(',', '')
		file_y.write(str + '\n')
コード例 #2
0
def line_plot(final_dis_angle):

    drawing = Drawing()
    data = [final_dis_angle]
    lp = LinePlot()
    lp.x = 0
    lp.y = -120
    lp.height = 300
    lp.width = 450
    lp.data = data
    lp.joinedLines = 0
    lp.lines[0].symbol = makeMarker('FilledCircle')
    lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    # lp.xValueAxis.valueMin = 0
    # lp.xValueAxis.valueMax = 5
    # lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    # lp.yValueAxis.valueMin = 0
    # lp.yValueAxis.valueMax = 7
    # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)

    return drawing
コード例 #3
0
def getHumPlot():
    drawing = Drawing(400, 200)
    humedad = [getHumedad()]
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = humedad

    ydlabel = Label()
    ydlabel.setText("Humedad (%)")
    ydlabel.angle = 90
    ydlabel.setOrigin(20, 120)

    lp.joinedLines = 2
    lp.lines[0].symbol = makeMarker('Circle')
    lp.lines[0].strokeColor = colors.blue
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 30
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 100
    #lp.xValueAxis.visible=False
    #lp.yValueAxis.visible=False #Hide 2nd plot its Yaxis
    drawing.add(lp)
    drawing.add(ydlabel)
    drawing.add(String(130, 200, "Gráfico de humedad", fontSize=16))

    return drawing
コード例 #4
0
    def _draw_scatter_plot(self, cur_drawing, x_start, y_start, x_end, y_end):
        """Draw a scatter plot on the drawing with the given coordinates."""
        scatter_plot = LinePlot()

        # set the dimensions of the scatter plot
        scatter_plot.x = x_start
        scatter_plot.y = y_start
        scatter_plot.width = abs(x_start - x_end)
        scatter_plot.height = abs(y_start - y_end)

        scatter_plot.data = self.display_info

        scatter_plot.joinedLines = 0

        # set the axes of the plot
        x_min, x_max, y_min, y_max = self._find_min_max(self.display_info)
        scatter_plot.xValueAxis.valueMin = x_min
        scatter_plot.xValueAxis.valueMax = x_max
        scatter_plot.xValueAxis.valueStep = (x_max - x_min) / 10.0

        scatter_plot.yValueAxis.valueMin = y_min
        scatter_plot.yValueAxis.valueMax = y_max
        scatter_plot.yValueAxis.valueStep = (y_max - y_min) / 10.0

        self._set_colors_and_shapes(scatter_plot, self.display_info)

        cur_drawing.add(scatter_plot)
コード例 #5
0
def line_plot_demo():
    d = Drawing(400, 400)
    line = LinePlot()
    line.x = 50
    line.y = 85
    line.height = 150
    line.width = 250
    line.lineLabelFormat = '%2.0f'

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

    line.lines[0].strokeColor = colors.green
    line.lines[1].strokeColor = colors.blue
    line.lines[0].strokeWidth = 3

    line.lines[0].symbol = makeMarker('Circle')
    line.lines[1].symbol = makeMarker('Hexagon')

    line.xValueAxis.valueMin = 0
    line.xValueAxis.valueMax = 10
    line.xValueAxis.valueSteps = [1, 2, 4]
    line.xValueAxis.labelTextFormat = '%2.1f'

    line.yValueAxis.valueMin = 0
    line.yValueAxis.valueMax = 12

    d.add(line, '')
    d.save(formats=['pdf'], outDir='.', fnRoot='line_plot_demo')
コード例 #6
0
def getLineChartWithMarkers():
    data = [((2, 3), (3, 2), (5, 3)), ((2, 6), (3, 4), (4, 3), (5, 1))]

    chart = LinePlot()
    chart.data = data
    chart.x = 5
    chart.y = 5
    chart.width = 240
    chart.height = 100

    chart.fillColor = colors.yellowgreen

    chart.lines[0].strokeWidth = 3.5
    chart.lines[1].strokeWidth = 1
    chart.lines[0].strokeColor = colors.brown

    chart.xValueAxis.valueMin = 1
    chart.xValueAxis.valueMax = 6
    chart.yValueAxis.valueMin = 1
    chart.yValueAxis.valueMax = 7

    chart.lines[0].symbol = makeMarker('Diamond')
    chart.lines[0].symbol.fillColor = colors.pink
    chart.lines[1].symbol = makeMarker(
        'EU_Flag',  # 'Triangle',
        fillColor=colors.red)

    title = String(50, 110, 'Line Plot Chart', fontSize=14)

    drawing = Drawing(240, 120)
    drawing.add(title)
    drawing.add(chart)
    return drawing
コード例 #7
0
 def line_plot(O, xy_max, data, label_font_size):
   if (reportlab is None): return
   from reportlab.graphics.charts.lineplots import LinePlot
   from reportlab.graphics.widgets.markers import makeMarker
   from reportlab.lib import colors
   lp = LinePlot()
   lp.x = 40
   lp.y = 40
   lp.height = 120
   lp.width = 120
   lp.data = [[(0,0),(xy_max,xy_max)], data]
   lp.lines[0].strokeColor = colors.Color(*[0.8]*3)
   lp.lines[0].strokeWidth = 0.5
   lp.lines[1].strokeColor = colors.white
   lp.lines[1].strokeWidth = 0
   lp.lines[1].symbol = makeMarker("Circle")
   lp.lines[1].symbol.strokeWidth = 0.5
   lp.joinedLines = 1
   lp.strokeColor = colors.Color(*[0.8]*3)
   lp.strokeWidth = 1
   lp.xValueAxis.valueMin = 0
   lp.xValueAxis.valueMax = xy_max
   lp.xValueAxis.valueSteps = range(xy_max+1)
   lp.xValueAxis.strokeWidth = 1
   lp.xValueAxis.tickDown = 3
   lp.xValueAxis.labels.fontSize = label_font_size
   lp.yValueAxis.valueMin = 0
   lp.yValueAxis.valueMax = xy_max
   lp.yValueAxis.valueSteps = range(xy_max+1)
   lp.yValueAxis.strokeWidth = 1
   lp.yValueAxis.tickLeft = 3
   lp.yValueAxis.labels.fontSize = label_font_size
   return lp
コード例 #8
0
def drawing_chinese():
    from reportlab.graphics.charts.lineplots import LinePlot
    from reportlab.graphics.charts.textlabels import Label
    from reportlab.graphics import renderPDF
    from reportlab.graphics.widgets.markers import makeMarker
    data = [((1, 100), (2, 200), (3, 300), (4, 400), (5, 500)),
            ((1, 50), (2, 80), (3, 400), (4, 40), (5, 70))]
    drawing = Drawing(500, 300)

    lp = LinePlot()
    lp.x = 50  #������������
    lp.y = 30
    lp.height = 250
    lp.width = 400
    lp.data = data
    lp.joinedLines = 1
    lp.lines.symbol = makeMarker('FilledCircle')

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

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

    title = Label()
    #����Ҫ��ʾ���ģ���Ҫ��ע��һ����������
    title.fontName = "msyh"
    title.fontSize = 12
    title_text = u'你好吗'
    #title_text = "abc"
    title._text = title_text
    title.x = 250
    title.y = 280
    title.textAnchor = 'middle'
    drawing.add(title)

    Xlabel = Label()
    Xlabel._text = 'x'
    Xlabel.fontSize = 12
    Xlabel.x = 480
    Xlabel.y = 30
    Xlabel.textAnchor = 'middle'
    drawing.add(Xlabel)

    Ylabel = Label()
    Ylabel._text = "y"
    Ylabel.fontSize = 12
    Ylabel.x = 40
    Ylabel.y = 295
    Ylabel.textAnchor = 'middle'
    drawing.add(Ylabel)

    try:
        drawing.save(formats=['gif'], outDir=".", fnRoot="abc")
    except:
        import traceback
        traceback.print_exc()
コード例 #9
0
def main():
    URL = 'http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt'
    COMMENT_CHARS = '#:'

    drawing = Drawing(400, 200)
    data = []

    for line in urlopen(URL).readlines():
        if not line.isspace() and not line[0] in COMMENT_CHARS:
            data.append([float(n) for n in line.split()])

    pred = [row[2] for row in data]
    high = [row[3] for row in data]
    low = [row[4] for row in data]
    times = [row[0] + row[1] / 12.0 for row in data]

    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = [zip(times, pred), zip(times, high), zip(times, low)]
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.green

    drawing.add(lp)

    drawing.add(String(250, 150, 'Sunspots', fontSize=14,
                       fillColor=colors.red))

    renderPDF.drawToFile(drawing, 'report.pdf', 'Sunspots')
コード例 #10
0
        def sample9c():
            lp = LinePlot()
            lp.yValueAxis = LogYValueAxis()
            lp.x += 20
            lp.y += 20
            lp.height = 250
            lp.width = 350
            data = [[(i, float(i)**2.) for i in range(10, 1001, 10)], ]
            data.append([(i, float(i)**3.) for i in range(10, 1001, 10)])
            data.append([(i, float(i)**1.6) for i in range(10, 1001, 10)])
            lp.data = data
            lp.lines.strokeWidth = .2
            lp.lines[0].strokeColor = colors.red
            lp.lines[1].strokeColor = colors.blue
            lp.lines[2].strokeColor = colors.green

            lp.xValueAxis.visibleGrid = 1
            lp.xValueAxis.gridStrokeDashArray = [1, 1]
            lp.yValueAxis.visibleGrid = 1
            lp.yValueAxis.visibleSubTicks = 1
            lp.yValueAxis.visibleSubGrid = 1
            lp.yValueAxis.subTickNum = 4
            lp.yValueAxis.gridStrokeDashArray = [.3, 1]
            lp.yValueAxis.subGridStrokeDashArray = [.15, 1]

            drawing = Drawing(400,300)
            drawing.add(lp)

            return drawing
コード例 #11
0
ファイル: 21draw.py プロジェクト: binger233/study
def test03():
    # 最终太阳黑子图形程序
    from urllib import urlopen
    from reportlab.graphics.shapes import *
    from reportlab.graphics.charts.lineplots import LinePlot
    from reportlab.graphics.charts.textlabels import Label
    from reportlab.graphics import renderPDF

    URL = "http://services.swpc.noaa.gov/text/predicted-sunspot-radio-flux.txt"
    COMMENT_CHARS = "#:"
    drawing = Drawing(400, 200)
    data = []
    for line in urlopen(URL).readlines():
        if not line.isspace() and not line[0] in COMMENT_CHARS:
            data.append([float(n) for n in line.split()])
    pred = [row[2] for row in data]
    high = [row[3] for row in data]
    low = [row[4] for row in data]
    times = [row[0] + row[1] / 12.0 for row in data]
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = [zip(times, pred), zip(times, high), zip(times, low)]
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.green
    drawing.add(lp)
    drawing.add(String(250, 150, "Sunsports", fontSize=14, fillColor=colors.red))
    renderPDF.drawToFile(drawing, "report2.pdf", "Sunsports")
コード例 #12
0
ファイル: Comparative.py プロジェクト: sip958/biopython
    def _draw_scatter_plot(self, cur_drawing, x_start, y_start,
                           x_end, y_end):
        """Draw a scatter plot on the drawing with the given coordinates."""
        scatter_plot = LinePlot()

        # set the dimensions of the scatter plot
        scatter_plot.x = x_start
        scatter_plot.y = y_start
        scatter_plot.width = abs(x_start - x_end)
        scatter_plot.height = abs(y_start - y_end)

        scatter_plot.data = self.display_info

        scatter_plot.joinedLines = 0

        # set the axes of the plot
        x_min, x_max, y_min, y_max = self._find_min_max(self.display_info)
        scatter_plot.xValueAxis.valueMin = x_min
        scatter_plot.xValueAxis.valueMax = x_max
        scatter_plot.xValueAxis.valueStep = (x_max - x_min) / 10.0

        scatter_plot.yValueAxis.valueMin = y_min
        scatter_plot.yValueAxis.valueMax = y_max
        scatter_plot.yValueAxis.valueStep = (y_max - y_min) / 10.0

        self._set_colors_and_shapes(scatter_plot, self.display_info)

        cur_drawing.add(scatter_plot)
コード例 #13
0
 def line_plot(O, xy_max, data, label_font_size):
     if (reportlab is None): return
     from reportlab.graphics.charts.lineplots import LinePlot
     from reportlab.graphics.widgets.markers import makeMarker
     from reportlab.lib import colors
     lp = LinePlot()
     lp.x = 40
     lp.y = 40
     lp.height = 120
     lp.width = 120
     lp.data = [[(0, 0), (xy_max, xy_max)], data]
     lp.lines[0].strokeColor = colors.Color(*[0.8] * 3)
     lp.lines[0].strokeWidth = 0.5
     lp.lines[1].strokeColor = colors.white
     lp.lines[1].strokeWidth = 0
     lp.lines[1].symbol = makeMarker("Circle")
     lp.lines[1].symbol.strokeWidth = 0.5
     lp.joinedLines = 1
     lp.strokeColor = colors.Color(*[0.8] * 3)
     lp.strokeWidth = 1
     lp.xValueAxis.valueMin = 0
     lp.xValueAxis.valueMax = xy_max
     lp.xValueAxis.valueSteps = range(xy_max + 1)
     lp.xValueAxis.strokeWidth = 1
     lp.xValueAxis.tickDown = 3
     lp.xValueAxis.labels.fontSize = label_font_size
     lp.yValueAxis.valueMin = 0
     lp.yValueAxis.valueMax = xy_max
     lp.yValueAxis.valueSteps = range(xy_max + 1)
     lp.yValueAxis.strokeWidth = 1
     lp.yValueAxis.tickLeft = 3
     lp.yValueAxis.labels.fontSize = label_font_size
     return lp
コード例 #14
0
        def sample9b():
            lp = LinePlot()
            lp.yValueAxis = LogYValueAxis()
            lp.x += 20
            lp.y += 20
            lp.height = 250
            lp.width = 350
            data = [
                [(i, float(i)**2.) for i in range(10, 1001, 10)],
            ]
            data.append([(i, float(i)**3.) for i in range(10, 1001, 10)])
            data.append([(i, float(i)**1.6) for i in range(10, 1001, 10)])
            lp.data = data
            lp.lines.strokeWidth = .2
            lp.lines[0].strokeColor = colors.red
            lp.lines[1].strokeColor = colors.blue
            lp.lines[2].strokeColor = colors.green

            lp.xValueAxis.visibleGrid = 1
            lp.xValueAxis.gridStrokeDashArray = [1, 1]
            lp.yValueAxis.visibleGrid = 1
            lp.yValueAxis.visibleSubTicks = 1
            lp.yValueAxis.visibleSubGrid = 1
            lp.yValueAxis.gridStrokeDashArray = [1, 1]
            lp.yValueAxis.subGridStrokeDashArray = [1, 1]

            drawing = Drawing(400, 300)
            drawing.add(lp)

            return drawing
コード例 #15
0
ファイル: ChartBlock.py プロジェクト: yudevan/noWord
    def makePlotChart(self, context, width, height, data, xvalues, linecolors):
        content = []

        drawing = Drawing(width, height)

        plot = LinePlot()
        plot.x = 0
        plot.y = self.padding
        plot.height = height - 2 * self.padding
        plot.width = width
        plot.data = data
        plot.joinedLines = 1
        plot.lineLabelFormat = '%2.0f'

        i = 0
        for color in linecolors :
            plot.lines[i].strokeColor = colors.HexColor(color)
            i+=1

        if xvalues :
            plot.xValueAxis.valueSteps = xvalues

        drawing.add(plot)

        content.append( drawing )

        return content
コード例 #16
0
ファイル: main.py プロジェクト: satiago/workplace
def main():
    URL = 'http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt'
    COMMENT_CHARS = '#:'
    
    drawing = Drawing(400, 200)
    data = []
    
    for line in urlopen(URL).readlines():
        if not line.isspace() and not line[0] in COMMENT_CHARS:
            data.append([float(n) for n in line.split()])
            
    pred = [row[2] for row in data]
    high = [row[3] for row in data]
    low = [row[4] for row in data]
    times = [row[0] + row[1]/12.0 for row in data]
       
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = [zip(times, pred), zip(times, high), zip(times, low)]
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.green
    
    drawing.add(lp)
    
    drawing.add(String(250, 150, 'Sunspots', fontSize = 14, fillColor = colors.red))
    
    renderPDF.drawToFile(drawing, 'report.pdf', 'Sunspots')
コード例 #17
0
ファイル: Drawing.py プロジェクト: xlmysjz/Python
def draw():
    '''
    data=[(2007,8,113.2,114.2,112.2),
          (2007,9,112.8,115.8,109.8),
          (2007,10,111.0,116.0,106.0),
          (2007,11,109.8,116.8,102.8),
          (2007,12,107.3,115.3,99.3),
          (2008,1,105.2,114.2,96.2),
          (2008,2,104.1,114.1,94.1),
          (2008,3,99.9,110.9,88.9),
          (2008,4,94.8,106.8,82.8),
          (2008,5,91.2,104.2,78.2)]
          '''
    '''
    #这个是在pdf里画一个 hello word 的例子,
    d=Drawing(100,100)
    s=String(50,50,"hello word",textAnchor="middle")
    d.add(s)
    renderPDF.drawToFile(d,"hello.pdf","A simple PDF file")#renderPDF.drawToFile调用后会把你的pdf文件存到当前目录下一个叫hello.pdf的文件中
    '''
    URL="http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt"#见364页,这个网址记录的是太阳黑子的全部数据
    COMMENT_CHARS="#:"
    drawing=Drawing(400,200)
    data=[]
    for line in urlopen(URL).readlines():
        #not isspace()是判断 这一行不为空字符串,not line[0] in COMMENT_CHARS是说 在网页里去掉 # 和 . 的部分
        if not line.isspace() and not line[0] in COMMENT_CHARS:
            data.append([float(n) for n in line.split()])
    #print data
    
    pred=[row[2] for row in data]
    high=[row[3] for row in data]
    low=[row[4] for row in data]
    times=[row[0]+row[1]/12.0 for row in data]
    
    lp=LinePlot()
    #设置 x,y,height,width,以及data
    lp.x=50 
    lp.y=50
    lp.height=125
    lp.width=300
    lp.data=[zip(times,pred),zip(times,high),zip(times,low)]
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.green
    
    
    '''
    drawing.add(PolyLine(zip(times,pred),storkeColor=colors.blue))
    drawing.add(PolyLine(zip(times,high),storkeColor=colors.red))
    drawing.add(PolyLine(zip(times,low),storkeColor=colors.green))
    #drawing.add(PolyLine([(10,50),(100,50),(80,80)],storkeColor=colors.red))#这个是直接画一条线
    '''
    drawing.add(lp)
    drawing.add(String(250,150,"SunSpots",fontSize=14,fillColor=colors.red))
    
    renderPDF.drawToFile(drawing,"report.pdf","SunSpots")#renderPDF.drawToFile调用后会把你的pdf文件存到当前目录下一个叫report.pdf的文件中
コード例 #18
0
def draw_recent_week_pdf(filename, data_list):
    """
    画最近七天的流量计报表
    :param filename:
    :param data_list
    :return:
    """
    data = []
    max_val = 0
    for index in range(0, len(data_list)):
        data.append((index + 1, data_list[index]))
        max_val = max(max_val, data_list[index])

    drawing = Drawing(500, 800)
    lp = LinePlot()
    lp.x = 50
    lp.y = 80
    lp.height = 600
    lp.width = 400
    lp.data = [data]
    lp.joinedLines = 1
    lp.lines.symbol = makeMarker('FilledCircle')
    lp.xValueAxis.valueMin = 1
    lp.xValueAxis.valueMax = 7
    lp.xValueAxis.valueStep = 1
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = (int(max_val / 100) + 1) * 100
    lp.yValueAxis.valueStep = 100
    drawing.add(lp)

    x_title = Label()
    # 若需要显示中文,需要先注册一个中文字体
    pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc"))
    x_title.fontName = "haha"
    x_title.fontSize = 12
    title_text = '用气量'
    x_title._text = title_text
    x_title.x = 20
    x_title.y = 100
    x_title.textAnchor = 'middle'
    drawing.add(x_title)

    y_title = Label()
    # 若需要显示中文,需要先注册一个中文字体
    pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc"))
    y_title.fontName = "haha"
    y_title.fontSize = 12
    title_text = '最近七天'
    y_title._text = title_text
    y_title.x = 80
    y_title.y = 50
    y_title.textAnchor = 'middle'
    drawing.add(y_title)
    drawing.save(formats=['pdf'],
                 outDir=TMP_FILE_DIRECTORY_PATH,
                 fnRoot=filename)
コード例 #19
0
ファイル: graphs.py プロジェクト: zcc24/pdf
 def drawline(self,width,height,*args):
     drawing=Drawing(width,height)
     ab=LinePlot()
     ab.x=180
     ab.y=0
     ab.height=200
     ab.width=420
     ab.xValueAxis._valueMin = 0
     ab.yValueAxis._valueMin=0
     ab.joinedLines=1
     ab.data=[args]
     ab.lines[0].strokeColor=colors.red
     drawing.add(ab)
     return drawing
コード例 #20
0
def addElectricPrice(canvas_param, pos_x, pos_y, width, height):

    # 电价数据
    data = electricityPriceData

    # 定义各曲线标签
    # data_name = ['一般工商业电价(1-10千伏)', '大工业电价(1-10千伏)', '一般工商业电价(35-110千伏)', '大工业电价(35-110千伏)']
    data_name = ['一般工商业电价(35-110千伏)']

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

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

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

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

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

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

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

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

    return c
コード例 #21
0
def MakePDF(times, list, reportname, pdfname):
    drawing = Drawing(500, 300)
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = [zip(times, list)]
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.green

    drawing.add(lp)
    drawing.add(String(350, 150, reportname, fontSize=14, fillColor=colors.red))

    renderPDF.drawToFile(drawing, pdfname, reportname)
コード例 #22
0
ファイル: reportpdf.py プロジェクト: acekillersg/KaerProject
def drawrelationshipcs(can, resultsbuffer):
    can.setFont("Helvetica", 24)
    sec_title = "System Heat Balance"
    can.drawString(25, 750, sec_title)

    desc_text = "The following figure shows the relationship between the chilled water" \
                " system operating efficiency and the cooling load. As the figure shows, with " \
                "the Cooling load ranges between 800 RT to 1100 RT, the efficiency hovers between " \
                "0.75/RT to 0.91KW/RT."
    stylesheet = getSampleStyleSheet()
    paragraph = Paragraph(desc_text, stylesheet['Normal'])
    aW, aH = 500, 600
    w, h = paragraph.wrap(aW, aH)
    if w <= aW and h <= aH:
        paragraph.drawOn(can, 25, 700)

    drawing = Drawing(600, 400)
    data = [((801, 0.7), (903, 0.8), (799, 0.84), (1002, 0.97), (1101, 0.89)),
            ((987, 0.98), (1007, 1.1), (1102, 0.98), (987, 0.95), (908, 0.89))]
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 250
    lp.width = 400
    lp.data = data
    lp.joinedLines = 0
    lp.lines.symbol = makeMarker('FilledCircle')
    # lp.lines.symbol = makeMarker('Circle')
    # lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 1200
    lp.xValueAxis.valueSteps = [
        0.00, 200.00, 400.00, 600.00, 800.00, 1000.00, 1200.00
    ]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 1.2
    lp.yValueAxis.valueSteps = [
        0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2
    ]
    drawing.add(lp)
    drawing.drawOn(can, 50, 350)

    can.showPage()
コード例 #23
0
ファイル: getGPU_report.py プロジェクト: zjjfx88/py3preject
def getLp(reportDict,init_num,height):
	lp = LinePlot()
	lp.x = 100
	lp.y = height-(200*(init_num+1))
	lp.height = 125
	lp.width = 600
	lp.data = []
	lp.lines[0].strokeColor = colors.blue
	lst=[]
	infile=reportDict[0]
	with open(infile,'r') as f:
		for line in f.readlines():
			line_lst=line.split('\t')
			lst_time=int(line_lst[0])
			lst_data=int(line_lst[1])
			lst.append((lst_time,lst_data))
		lp.data.append(lst)
	return lp
コード例 #24
0
ファイル: views.py プロジェクト: fossabot/noc
    def render_graph(self, request_opts, graph_opts):
        def label_fmt(x):
            print "@@@", x
            return str(x)

        ld = len(graph_opts["data"])
        palette = [Color(*x) for x in get_float_pallete(ld)]
        w = graph_opts["width"]
        h = graph_opts["height"]
        drawing = Drawing(w, h)
        # Legend
        legend = LineLegend()
        legend.colorNamePairs = [
            (palette[i], graph_opts["data"][i].name)
            for i in range(ld)
        ]
        legend.boxAnchor = "sw"
        legend.columnMaximum = 2
        legend.alignment = "right"
        drawing.add(legend)
        lh = legend._calcHeight() + self.X_PADDING / 2
        # Plot
        lp = LinePlot()
        lfs = lp.xValueAxis.labels.fontSize
        lp.x = self.X_PADDING
        lp.y = self.Y_PADDING + lh + lfs
        lp.width = w - 2 * self.X_PADDING
        lp.height = h - self.Y_PADDING - lp.y
        lp.data = [
            [(t, v) for v, t in ts] for ts in graph_opts["data"]
        ]
        for i in range(ld):
            lp.lines[i].strokeColor = palette[i]
        drawing.add(lp)
        # Render
        cdata = drawing.asString(format="png")
        response = self.render_plain_text(
            cdata,
            mimetype="image/png"
        )
        if not request_opts["noCache"]:
            cache.set(request_opts["requestKey"], response,
                      request_opts["cacheTimeout"])
        return response
コード例 #25
0
def getLp(reportDict, init_num, height, mode):
    lp = LinePlot()
    lp.x = 100
    lp.y = height - 300 * (init_num + 1)
    lp.height = 200
    lp.width = 400
    if mode == 'used':
        lp.yValueAxis.valueMin = 0
        lp.yValueAxis.valueMax = 100
        lp.yValueAxis.valueSteps = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    elif mode == 'mem':
        lp.yValueAxis.valueMin = 0
        lp.yValueAxis.valueMax = 24000
        lp.yValueAxis.valueSteps = [
            2000, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 18000, 20000,
            22000, 24000
        ]
    lp.data = []
    lp.lines[0].strokeColor = colors.blue
    lst = []
    lst_sum = []
    xValue = []
    infile = reportDict[0]
    with open(infile, 'r') as f:
        for line in f.readlines():
            line_lst = line.split('\t')
            lst_time = float(line_lst[0])
            xValue.append(lst_time)
            lst_data = float(line_lst[1])
            lst_sum.append(lst_data)
            lst.append((lst_time, lst_data))
        lp.data.append(lst)
    avgData = round(sum(lst_sum) / len(lst_sum), 2)
    lp.xValueAxis.valueMin = xValue[0]
    lp.xValueAxis.valueMax = int(xValue[-1]) + 1
    lp.xValueAxis.valueSteps = range(0, int(xValue[-1]) + 2)
    result = []
    result.append(lp)
    result.append(avgData)
    return result
コード例 #26
0
def line_plot(data, elements):
    drawing = Drawing(0, 400)  # for indices
    lp = LinePlot()
    lp.x = 0
    lp.y = 50
    lp.height = 300
    lp.width = 600
    lp.data = data
    lp.joinedLines = 1
    lp.lines[0].symbol = makeMarker('FilledCircle')
    lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 5
    lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 7
    lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    elements.append(drawing)
コード例 #27
0
ファイル: pb_draw.py プロジェクト: meyerson/BOUT
   def graphout(name, datain,xaxis=None):
       if xaxis is None:
           xaxis=range(datain.size)
       if xlabel is None:
           xlabel = ''
       if ylabel is None:
           ylabel = ''
 
       drawing = Drawing(400, 200)
    # data = [
    #    ((1,1), (2,2), (2.5,1), (3,3), (4,5)),
    #    ((1,2), (2,3), (2.5,2), (3.5,5), (4,6))
    #    ]
       dataview = [tuple([(xaxis[i],datain[i]) for i in range(datain.size)])]
       lp = LinePlot()
       lp.x = 50
       lp.y = 50
       lp.height = 125
       lp.width = 300
       lp.data = dataview
       lp.xValueAxis.xLabelFormat       = '{mmm} {yy}'  
       lp.lineLabels.fontSize           = 6  
       lp.lineLabels.boxStrokeWidth     = 0.5  
       lp.lineLabels.visible            = 1  
       lp.lineLabels.boxAnchor          = 'c'  
    # lp.joinedLines = 1
    # lp.lines[0].symbol = makeMarker('FilledCircle')
    # lp.lines[1].symbol = makeMarker('Circle')
    # lp.lineLabelFormat = '%2.0f'
    # lp.strokeColor = colors.black
    # lp.xValueAxis.valueMin = min(xaxis)
    # lp.xValueAxis.valueMax = max(xaxis)
    # lp.xValueAxis.valueSteps = xaxis
    # lp.xValueAxis.labelTextFormat = '%2.1f'
    # lp.yValueAxis.valueMin = min(datain)
    # lp.yValueAxis.valueMax = max(datain)
    # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
       drawing.add(lp)
       return drawing
コード例 #28
0
def draw_lines(data, height=125, width=220, use_colors=[]):
    lp = LinePlot()
    '''
    title = Label() 
    title.fontName  = "song"  
    title.fontSize  = 12  
    title_text = "ceshi"  
    title._text = title_text 
    '''
    lp.x = 50  #坐标轴中心坐标
    lp.y = 50
    lp.height = height
    lp.width = width
    thex = data.iloc[:, 0].tolist()
    datalist = []
    for lines in range(len(data.columns) - 1):
        datalist.append(list(zip(thex, data.iloc[:, lines + 1].tolist())))
    lp.data = datalist
    if use_colors != []:
        for i, col in enumerate(use_colors):
            lp.lines[i].strokeColor = col
    return lp
コード例 #29
0
    def test_23_linePlotCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.lineplots import LinePlot
        from reportlab.graphics.widgets.markers import makeMarker

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

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

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

        d = Drawing(400, 200)
        data = [
            [(1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)],
        ]
        lp = LinePlot()
        lp.x = 5
        lp.y = 5
        lp.height = 190
        lp.width = 390
        lp.data = data
        lp.joinedLines = 1
        lp.lines[0].symbol = makeMarker('FilledCircle')
        d.add(lp)

        elements.append(d)

        doc.build(elements)
コード例 #30
0
ファイル: resources.py プロジェクト: tianyouzhu/you
    def draw_line(self, line_data, *args, **kw):
        drawing = Drawing(400, 200)
        lp = LinePlot()
        lp.x = 30
        lp.y = -20
        lp.height = 200
        lp.width = 400
        lp.data = line_data
        lp.xValueAxis.labels.fontName = 'Helvetica'
        lp.xValueAxis.labels.fontSize = 7
        lp.xValueAxis.forceZero = 0
        lp.xValueAxis.avoidBoundFrac = 1
        lp.xValueAxis.gridEnd = 115
        lp.xValueAxis.tickDown = 3
        lp.xValueAxis.labelTextFormat = lambda x: time.strftime(
            '%Y-%m-%d %H:%M:%S', time.localtime(int(x) / 1000))

        lp.yValueAxis.tickLeft = 3
        lp.yValueAxis.labels.fontName = 'Helvetica'
        lp.yValueAxis.labels.fontSize = 7
        for i in range(len(line_data)):
            lp.lines[i].strokeColor = colors.toColor('hsl(%s,80%%,40%%)' %
                                                     (i * 60))
        drawing.add(lp)

        title = Label()
        title.fontName = 'Helvetica-Bold'
        title.fontSize = 14
        title.x = 200
        title.y = 180
        title._text = 'Chart Title'
        title.maxWidth = 180
        title.height = 20
        title.textAnchor = 'middle'
        drawing.add(title)

        return drawing
コード例 #31
0
ファイル: test_pdf.py プロジェクト: zenist/ZLib
    def test_23_linePlotCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.lineplots import LinePlot
        from reportlab.graphics.widgets.markers import makeMarker

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

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

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

        d = Drawing(400,200)
        data = [
            [(1,1), (2,2), (2.5,1), (3,3), (4,5)],
        ]
        lp = LinePlot()
        lp.x = 5
        lp.y = 5
        lp.height = 190
        lp.width = 390
        lp.data = data
        lp.joinedLines = 1
        lp.lines[0].symbol = makeMarker('FilledCircle')
        d.add(lp)

        elements.append(d)

        doc.build(elements)
コード例 #32
0
def draw_report():
    data = init_data()
    pred = [row[2] for row in data]
    high = [row[3] for row in data]
    low = [row[4] for row in data]
    times = [(row[0] + row[1] / 12.0) for row in data]
    d = Drawing(400, 200)
    title = String(250, 180, 'Sunspots', fontsize=14, fillColor=colors.red)
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    lp.data = [
        list(zip(times, pred)),
        list(zip(times, high)),
        list(zip(times, low))
    ]
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.green
    d.add(title)
    d.add(lp)
    renderPDF.drawToFile(d, 'report.pdf', 'Sunspots')
コード例 #33
0
def get_figure_drawing(input_data, x_margin, y_margin, width, height):
    time = np.arange(len(input_data))
    prefix_sums = np.cumsum(input_data)

    # Data in needed for Drawing format (pairs array)
    data = [np.column_stack((time, prefix_sums))]
    data = [tuple(map(tuple, data[0]))]

    # Create drawing.
    drawing = Drawing()

    # Create graph.
    our_graph = LinePlot()
    our_graph.data = data

    our_graph.x = x_margin
    our_graph.y = y_margin

    our_graph.height = height
    our_graph.width = width

    drawing.add(our_graph)

    return drawing
コード例 #34
0
from reportlab.pdfgen import canvas
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie

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

drawing = Drawing(400, 200)
data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)),
        ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))]
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
lp.data = data
lp.joinedLines = 1
lp.lines[0].symbol = makeMarker('FilledCircle')
lp.lines[1].symbol = makeMarker('Circle')
lp.lineLabelFormat = '%2.0f'
lp.strokeColor = colors.black
lp.xValueAxis.valueMin = 0
lp.xValueAxis.valueMax = 5
lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5]
lp.xValueAxis.labelTextFormat = '%2.1f'
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 7
lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
drawing.add(lp)
drawing.save(formats=['pdf'], outDir='./pdfs', fnRoot='chart')
コード例 #35
0
ファイル: reporter.py プロジェクト: jhuguetn/WAD_Python
    def stackedGraphs(self,lxydata,tmin=None,tmax=None): # list of (label, [x,yarr]) with x in seconds

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

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

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

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

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

            drawing.add(self.addAutoLegend(lc,(lc.x,lc.y,lc.width,lc.height),len(lc.data),side='right'))
        return drawing
コード例 #36
0
ファイル: reporter.py プロジェクト: jhuguetn/WAD_Python
    def dategraph(self,lxydata,tmin=None,tmax=None): # list of (label, [x,yarr]) with x in seconds
        maxX = lxydata[0][1][0][0]
        maxY = 1.
        minX = maxX
        minY = -1
        for label,xyarr in lxydata:
            xarr = [x for (x,y) in xyarr]
            yarr = [y for (x,y) in xyarr]
            maxY = max(maxY, max(yarr))
            minY = min(minY, min(yarr))
            maxX = max(maxX, max(xarr))
            minX = min(minX, min(xarr))
        if not tmin is None:
            minX = tmin
        if not tmax is None:
            maxX = tmax
        lxydata.append(('CritMax',[[minX,1.],[maxX,1.]]))
        lxydata.append(('CritMin',[[minX,-1.],[maxX,-1.]]))

        drawing = Drawing(self.PAGE_WIDTH-150, 200)
        lc = LinePlot()
        lc.x = 30
        lc.y = 50
        lc.height = 125
        lc.width = self.PAGE_WIDTH-150-30
        lc.data = [xy for (l,xy) in lxydata]
        datalabels = [ l for (l,xy) in lxydata]

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

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

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

        self.addLabels(drawing,ylabel="geschaalde waarde")
        drawing.add(lc)
        drawing.add(self.addAutoLegend(lc,(lc.x,lc.y),len(lc.data)))
        return drawing
コード例 #37
0
    (2007,  9,      112.8,      115.8,  109.8),
    (2007,  10,     111.0,      116.0,  106.0),
    (2007,  11,     109.8,      116.8,  102.8),
    (2007,  12,     107.3,      115.3,  99.3),
    (2008,  1,      105.2,      114.2,  96.2),
    (2008,  2,      104.1,      114.1,  94.1),
    (2008,  3,      99.9,       110.9,  88.9),
    (2008,  4,      94.8,       106.8,  82.8),
    (2008,  5,      91.2,       104.2,  78.2),
]

drawing = Drawing(400, 200)
pred = [row[2] for row in data]
high = [row[3] for row in data]
low = [row[4] for row in data]
times = [row[0] + row[1] / 12.0 for row in data]

lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
lp.data = [zip(times, pred), zip(times, high), zip(times, low)]
lp.lines[0].strokeColor = colors.blue
lp.lines[1].strokeColor = colors.red
lp.lines[2].strokeColor = colors.green

drawing.add(lp)
drawing.add(String(200, 180, 'Sunspots', fontSize = 14, fillColor = colors.red))
renderPDF.drawToFile(drawing, 'report2.pdf', 'Sunspots')
コード例 #38
0
ファイル: csummary.py プロジェクト: pearsomark/CiliaC
def makeSummary(self, stype):
    logger.debug('StartQT4::makeSummary(%s)' % stype)
    pinfo = self.imageViews[-1].getSummaryDemographics()
    if pinfo is None:
        return

    reportname = self.imageViews[-1].getReportName() + '.pdf'
    filename = QtGui.QFileDialog.getSaveFileName(
        self,
        directory=reportname,
        filter='PDF Files *.pdf(*.pdf);;All Files *(*)')
    #filename = QtGui.QFileDialog.getSaveFileName(self, filter='PDF Files *.pdf(*.pdf);;All Files *(*)')
    if len(filename) == 0:
        return
    doc = SimpleDocTemplate(str(filename),
                            pagesize=A4,
                            rightMargin=1.5 * cm,
                            leftMargin=2 * cm,
                            topMargin=2 * cm,
                            bottomMargin=3 * cm)
    elements = []
    #data = pinfo.items()

    for iv in self.imageViews:
        vt = iv.getVelocityText()
        if stype == 'BOTH' or stype == iv.getViewShortName():
            pinfo.append(vt)
    t = Table(pinfo, rowHeights=12)
    t.setStyle(
        TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green),
                    ('TEXTCOLOR', (0, 0), (1, -1), colors.black),
                    ('ALIGNMENT', (0, 0), (0, -1), 'RIGHT')]))

    elements.append(t)
    for iv in self.imageViews:
        if stype == 'BOTH' or stype == iv.getViewShortName():
            drawing = Drawing(400, 280)
            cd = iv.getDataPointer()
            vt = iv.getVelocityText()
            pinfo.append(vt)
            #ydata = cd.getCOMYScaled(False, 'mm').tolist()
            ydata = cd.getCOMYScaled(True, 'mm').tolist()
            xPlaneFit = cd.getYPlaneFit(units='mm', bothAxes=True).tolist()
            vdata = cd.getVelocitySlopeScaled(units='mm', bothAxes=True)
            gdata = [ydata, xPlaneFit]
            if vdata is not None:
                gdata.append(vdata.tolist())
            title = Label()
            title.setOrigin(150, 240)
            title.setText(iv.getViewName())
            ylabel = Label()
            ylabel.setOrigin(0, 100)
            ylabel.angle = 90
            ylabel.setText("Millimeters")
            xlabel = Label()
            xlabel.setOrigin(70, 0)
            xlabel.setText("Seconds")
            lp = LinePlot()
            lp.height = 230
            lp.width = 400
            lp.data = gdata
            lp.lines[0].strokeColor = colors.blue
            lp.lines[1].strokeColor = colors.red
            lp.lines[2].strokeColor = colors.green
            #lp.xValueAxis.xLabel = "Seconds"
            drawing.add(title)
            drawing.add(ylabel)
            drawing.add(xlabel)
            drawing.add(lp)
            elements.append(drawing)

    doc.build(elements,
              onFirstPage=self.pdfHeaderFooter,
              onLaterPages=self.pdfHeaderFooter)
コード例 #39
0
    def make_graphs(self, canvas=None, left_margin=None):  #text=None):
        from reportlab.graphics import renderPDF
        from reportlab.lib.pagesizes import letter
        from reportlab.graphics.shapes import Drawing, String
        from reportlab.graphics.charts.legends import Legend
        from reportlab.graphics.charts.lineplots import LinePlot
        from reportlab.graphics.widgets.markers import makeMarker
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        #help(colors)

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

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

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

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

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

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

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

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

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

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

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

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

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

        # draw everything
        renderPDF.draw(d_dxdy, canvas, plot_dxdy_pos[0], plot_dxdy_pos[1])
        renderPDF.draw(d_cdf, canvas, plot_cdf_pos[0], plot_cdf_pos[1])
        renderPDF.draw(d_pdf, canvas, plot_pdf_pos[0], plot_pdf_pos[1])
コード例 #40
0
ファイル: SubFunction.py プロジェクト: dxcv/My_Quant
def addAcTemp(canvas_param, opc_df_today,pos_x, pos_y, width, height):

    total_df = opc_df_today

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    renderPDF.draw(drawing=drawing, canvas=c, x=pos_x, y=pos_y)
コード例 #41
0
ファイル: backup.py プロジェクト: veeruravi/pdf-generator
def generate_certificate(elements):
    styles = ParagraphStyle(
        name='Normal',
        fontName='Helvetica-Bold',
        fontSize=15,
        alignment=1,
    )
    elements.append(Spacer(1, 0.5 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(0, 200)  # for indices
    data = [
        (13, 5, 20, 22, 37, 45, 19, 4),
        (14, 6, 21, 23, 38, 46, 20, 5)
    ]  # data for drawing bar graphs
    bc = VerticalBarChart()
    bc.x = 0  # x,y define the left bottom of graph
    bc.y = 0
    bc.height = 150
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 50
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 6  # next 3 lines is for naming indices
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 60
    bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99',
                                     'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99']
    drawing.add(bc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
    drawing = Drawing(0, 175)  # for indices
    lc = HorizontalLineChart()
    lc.x = 0
    lc.y = 10
    lc.height = 150
    lc.width = 300
    lc.data = data
    lc.joinedLines = 1
    catnames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ')
    lc.categoryAxis.categoryNames = catnames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 60
    lc.valueAxis.valueStep = 15
    lc.lines[0].strokeWidth = 2
    lc.lines[1].strokeWidth = 1.5
    drawing.add(lc)
    elements.append(drawing)
    drawing = Drawing(0, 400)  # for indices
    data = [
        ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)),
        ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))
    ]
    elements.append(Spacer(1, 0.1 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    lp = LinePlot()
    lp.x = 0
    lp.y = 50
    lp.height = 300
    lp.width = 600
    lp.data = data
    lp.joinedLines = 1
    lp.lines[0].symbol = makeMarker('FilledCircle')
    lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 5
    lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 7
    lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    elements.append(drawing)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = [10, 20, 30, 40, 50, 60]
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.7 * inch))
    styles = ParagraphStyle(
        name='Normal',
        fontName='Helvetica',
        fontSize=15,
        alignment=0,
    )
    elements.append(Spacer(1, 0.5* inch))
    i = Paragraph(str("Please click on black square to play the video."), styles)
    elements.append(i)
    
    elements.append(platypus.flowables.Macro('canvas.saveState()'))
    elements.append(platypus.flowables.Macro('canvas.linkURL("fun.mp4",(400,510,410,500),relative=0,thickness=10)'))
    elements.append(platypus.flowables.Macro('canvas.restoreState()'))
    return elements
Date: 25th Feb 2012

"""

from reportlab.graphics.shapes import Drawing
from reportlab.lib import colors
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.graphics.charts.legends import Legend
from reportlab.graphics.charts.textlabels import Label

d = Drawing(620, 430)

lp = LinePlot()
lp.width = 520
lp.height = 320
lp.x = 70
lp.y = 80

FH = open("finalOutPut.csv", 'r')
data_lines = FH.readlines()
FH.close()

TP = 20
TN = 14
TOT = 7129

dat_dict = {}

num_clust = -1
num_clust_prev = -1
コード例 #43
0
def generate_certificate(elements):
    style = TableStyle([('TEXTALIGN', (0, 0), (-1, -1), 'CENTER'),
                        ('TEXTCOLOR', (0, 0), (-1, -1), colors.red),
                        ('VALIGN', (0, 0), (0, -1), 'TOP'),
                        ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.red),
                        ('BOX', (0, 0), (-1, -1), 0.50, colors.green),
                        ('BACKGROUND', (0, 0), (-1, -1), colors.blue),
                        ])
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = "RGB"
    styles = ParagraphStyle(
        name='Normal',
        fontName='Helvetica-Bold',
        fontSize=15,
        alignment=1,
    )
    elements.append(Spacer(1, 0.5 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(0, 200)  # for indices
    data = [
        (13, 5, 20, 22, 37, 45, 19, 4),
        (14, 6, 21, 23, 38, 46, 20, 5)
    ]  # data for drawing bar graphs
    bc = VerticalBarChart()
    bc.x = 0  # x,y define the left bottom of graph
    bc.y = 0
    bc.height = 150
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 50
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 6  # next 3 lines is for naming indices
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 60
    bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99',
                                     'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99']
    drawing.add(bc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
    drawing = Drawing(0, 175)  # for indices
    lc = HorizontalLineChart()
    lc.x = 0
    lc.y = 10
    lc.height = 150
    lc.width = 300
    lc.data = data
    lc.joinedLines = 1
    catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ')
    lc.categoryAxis.categoryNames = catNames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 60
    lc.valueAxis.valueStep = 15
    lc.lines[0].strokeWidth = 2
    lc.lines[1].strokeWidth = 1.5
    drawing.add(lc)
    elements.append(drawing)
    drawing = Drawing(0, 400)  # for indices
    data = [
        ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)),
        ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))
    ]
    elements.append(Spacer(1, 0.1 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    lp = LinePlot()
    lp.x = 0
    lp.y = 50
    lp.height = 300
    lp.width = 600
    lp.data = data
    lp.joinedLines = 1
    lp.lines[0].symbol = makeMarker('FilledCircle')
    lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 5
    lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 7
    lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    elements.append(drawing)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = [10, 20, 30, 40, 50, 60]
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
    return elements
コード例 #44
0
def run(self):
    def weight_sort(a, b):
        return cmp(a.getWeight(), b.getWeight())
        
    drawing = Drawing(600, 300)
    lc = LinePlot()
     
    # Determine axis dimensions and create data set
    maxval = 0
    minval = 0    
    dimension_one_values = []
    dimension_two_values = []
    dimension_one_answeroptions_as_objects = []
    dimension_two_answeroptions_as_objects = []
    counter = 0
    for question in self.getQuestions():        
        weights = [int(weight) for weight in question.getAnswerOptionsWeights()]
        answeroptions = list(question.getAnswerOptions())

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

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

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

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

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

    drawing.add(lc)

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

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

    # Write out
    data = drawing.asString('png')
    request = self.REQUEST
    response = request.RESPONSE
    response.setHeader('Content-Type', 'image/png')
    response.setHeader('Content-Disposition','inline; filename=%s.png' % self.getId())
    response.setHeader('Content-Length', len(data))           
    response.setHeader('Cache-Control', 's-maxage=0')
    
    return data
コード例 #45
0
  def make_graphs(self,canvas=None,left_margin=None):#text=None):
    from reportlab.graphics import renderPDF
    from reportlab.lib.pagesizes import letter
    from reportlab.graphics.shapes import Drawing,String
    from reportlab.graphics.charts.legends import Legend
    from reportlab.graphics.charts.lineplots import LinePlot
    from reportlab.graphics.widgets.markers import makeMarker
    from reportlab.lib import colors
    from reportlab.lib.units import inch
    #help(colors)

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


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

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

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

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

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

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

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

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

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

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

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

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

    # draw everything
    renderPDF.draw(d_dxdy,canvas,plot_dxdy_pos[0],plot_dxdy_pos[1])
    renderPDF.draw(d_cdf,canvas,plot_cdf_pos[0],plot_cdf_pos[1])
    renderPDF.draw(d_pdf,canvas,plot_pdf_pos[0],plot_pdf_pos[1])
コード例 #46
0
ファイル: mmparse.py プロジェクト: cokesprite/memory-tool
class PDFGen(object):
    Date = datetime.datetime.now().strftime("%Y-%m-%d")
    FileLeft = None
    FileRight = None
    Color = [colors.red, colors.blue, colors.green, colors.pink, colors.gray, colors.cyan, colors.orange, colors.purple, colors.yellow, colors.black]

    def drawLineChart(self, (names, start, end, data, title), reserved=None):
        w = PAGE_WIDTH - 2 * inch
        h = w * 0.6
        drawing = Drawing(w, h)

        lp = LinePlot()
        lp.x = 0
        lp.y = 0
        lp.height = h - 30
        lp.width = w
        lp.data = data
        lp.joinedLines = 1
        lp.strokeColor = colors.black

        lp.xValueAxis = XValueAxis()
        lp.xValueAxis.valueMin = start
        lp.xValueAxis.valueMax = end
        lp.xValueAxis.valueSteps = [(start + i * (end - start) / 5) for i in range(6)]
        lp.xValueAxis.labelTextFormat = lambda seconds: time.strftime("%m/%d %H:%M", time.localtime(seconds))
        lp.xValueAxis.labels.angle = 35
        lp.xValueAxis.labels.fontName = 'Helvetica'
        lp.xValueAxis.labels.fontSize = 7
        lp.xValueAxis.labels.dy = -10
        lp.xValueAxis.labels.boxAnchor = 'e'
コード例 #47
0
from urllib import urlopen
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF
URL = 'http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt'
COMMENT_CHARS = '#:'
drawing = Drawing(400,200)
data = []
for line in urlopen(url).readlines():
    if not line.isspace() and not line[0] in COMMENT_CHARS:
        data.append(float(n) for n in line.split())


pred = [row[2] for row in data]
high = [row[3] for row in data]
low = [row[4] for row in data]
times = [row[0] + row[1]/12.0 for row in data]
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 155
lp.width = 150
lp.data = [zip(times,pred),zip(times,high),zip(times,low)]
lp.lines[0].strokeColor = colors.blue
lp.lines[1].strokeColor = colors.red
lp.lines[2].strokeColoe = colors.green

drawing.add(lp)
drawing.add(String(250,150,'Sunspots',fontSize=14,fillColor=colors.red))
renderPDF.drawToFile(drawing,'report3.pdf','Sunspots')
コード例 #48
0
drawing = Drawing(500, 300)
data = []
with open(File, encoding="utf-8") as source:
    for line in source.readlines():
        if not line.isspace() and line[0] not in COMMENT_CHARS:
            data.append([float(n) for n in line.split()])

predict = [row[2] for row in data]
high = [row[3] for row in data]
low = [row[4] for row in data]
times = [row[0] + row[1] / 12.0 for row in data]

lp = LinePlot()  # 实例化LinePlot
lp.x = 50  # 设置属性
lp.y = 50
lp.height = 200
lp.width = 400
lp.data = [
    list(zip(times, predict)),
    list(zip(times, high)),
    list(zip(times, low))
]
lp.lines[0].strokeColor = colors.blue  # 设置折线颜色
lp.lines[1].strokeColor = colors.red
lp.lines[2].strokeColor = colors.green

drawing.add(lp)
drawing.add(String(250, 150, 'Sunspots', fontSize=14, fillColor=colors.red))
renderPDF.drawToFile(drawing, 'report.pdf', 'Sunspots')

# ### reportlab.graphics.charts.lineplots.LinePlot
コード例 #49
0
ファイル: csummary.py プロジェクト: pearsomark/CiliaC
def makeSummary(self, stype):
  logger.debug('StartQT4::makeSummary(%s)' % stype)
  pinfo = self.imageViews[-1].getSummaryDemographics()
  if pinfo is None:
    return

  reportname = self.imageViews[-1].getReportName()+'.pdf'
  filename = QtGui.QFileDialog.getSaveFileName(self, directory=reportname, filter='PDF Files *.pdf(*.pdf);;All Files *(*)')
  #filename = QtGui.QFileDialog.getSaveFileName(self, filter='PDF Files *.pdf(*.pdf);;All Files *(*)')
  if len(filename) == 0:
    return
  doc = SimpleDocTemplate(str(filename), pagesize=A4, rightMargin=1.5*cm, leftMargin=2*cm, topMargin=2*cm, bottomMargin=3*cm)
  elements = []
  #data = pinfo.items()

  for iv in self.imageViews:
    vt = iv.getVelocityText()
    if stype == 'BOTH' or stype == iv.getViewShortName():
      pinfo.append(vt)
  t=Table(pinfo, rowHeights=12)
  t.setStyle(TableStyle([('BACKGROUND',(1,1),(-2,-2),colors.green),
			('TEXTCOLOR',(0,0),(1,-1),colors.black),
			('ALIGNMENT', (0,0),(0,-1), 'RIGHT')]))

  elements.append(t)
  for iv in self.imageViews:
    if stype == 'BOTH' or stype == iv.getViewShortName():
      drawing = Drawing(400, 280)
      cd = iv.getDataPointer()
      vt = iv.getVelocityText()
      pinfo.append(vt)
      #ydata = cd.getCOMYScaled(False, 'mm').tolist()
      ydata = cd.getCOMYScaled(True, 'mm').tolist()
      xPlaneFit = cd.getYPlaneFit(units='mm', bothAxes=True).tolist()
      vdata = cd.getVelocitySlopeScaled(units='mm', bothAxes=True)
      gdata = [ydata, xPlaneFit]
      if vdata is not None:
	gdata.append(vdata.tolist())
      title = Label()
      title.setOrigin(150, 240)
      title.setText(iv.getViewName())
      ylabel = Label()
      ylabel.setOrigin(0, 100)
      ylabel.angle = 90
      ylabel.setText("Millimeters")
      xlabel = Label()
      xlabel.setOrigin(70, 0)
      xlabel.setText("Seconds")
      lp = LinePlot()
      lp.height = 230
      lp.width = 400
      lp.data = gdata
      lp.lines[0].strokeColor = colors.blue
      lp.lines[1].strokeColor = colors.red
      lp.lines[2].strokeColor = colors.green
      #lp.xValueAxis.xLabel = "Seconds"
      drawing.add(title)
      drawing.add(ylabel)
      drawing.add(xlabel)
      drawing.add(lp)
      elements.append(drawing)

  doc.build(elements, onFirstPage=self.pdfHeaderFooter, onLaterPages=self.pdfHeaderFooter)
コード例 #50
0
ファイル: pdf_report.py プロジェクト: aburgm/adsabs
    def createTimeSeries(self,ser):
        if self.single_record:
            return
        # Time series are available for these quantities. The number indicates their position in the data string
        series = {'h':0, 'g':1, 'i10':2, 'i100':6, 'tori':3, 'Read10':7}
        # The time series plot will get added to the 'drawing' object
        drawing = Drawing(400, 200)
        # and it is of type 'LinePlot'
        lp = LinePlot()
        lp.x = 30
        lp.y = 50
        lp.height = 125
        lp.width = 350
        # Record the publication years, because these values will be used as x axis labels
        years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['metrics series'].keys())))
        lp.data = []
        series_data = []
        # The maximum value will be used to scale the y axis
        max_value = 0
        # This list will hold the data points for the histogram
        for year in years:
            values = map(lambda a: float(a),self.data['metrics series'][str(year)].split(':'))
            max_value = max(max_value,values[series[ser]])
            if ser == 'read10' and year > 1995:
                series_data.append((year,values[series[ser]]))
            else:
                series_data.append((year,values[series[ser]]))

        lp.data.append(series_data)
        lp.joinedLines = 1
        # Define the line color
        lp.lines[0].strokeColor = colors.orange
        # Actual data point will be marked by a filled circle
        lp.lines.symbol = makeMarker('FilledCircle')
        lp.strokeColor = colors.black
        # The extreme values for the x axis
        lp.xValueAxis.valueMin = years[0]
        lp.xValueAxis.valueMax = years[-1]
        # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly
        lp.xValueAxis.labels.dx = -6
        lp.xValueAxis.labels.dy = -18
        # and rotate the labels by 90 degrees
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.valueSteps = years
        # For both axes values will be displayed as integers
        lp.xValueAxis.labelTextFormat = '%2.0f'
        lp.yValueAxis.labelTextFormat = '%2.0f'
        # Define the maximum value of the y axis
        lp.yValueAxis.valueMax = int(math.ceil(float(max_value)/10.0))*10
        # Depending on the range of values, set a value step for the y axis
        if max_value > 10000:
            lp.yValueAxis.valueStep = 1000
        elif max_value > 1000:
            lp.yValueAxis.valueStep = 100
        else:
            lp.yValueAxis.valueStep = 10
        # The y axis always starts at 0
        lp.yValueAxis.valueMin = 0
        # Now add the line plot to the 'drawing' object
        drawing.add(lp)
        # Finally add the appropriate title to the plot
        drawing.add(String(200,190,"%s index time series" % ser, textAnchor="middle", fillColor='blue'))
        # Append the result to the 'story'
        self.story.append(drawing)
コード例 #51
0
ファイル: PDF生成.py プロジェクト: 13661892653/workspace
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.pdfbase import pdfmetrics, ttfonts

#注意data的类型,
#每一个数据点是一个元组
#一条曲线对应一个存储数据点元组的元组
#一个图形可以包含多条曲线,用列表存储曲线元组
data = [((1, 100), (2, 200), (3, 300), (4, 400), (5, 500)),
        ((1, 50), (2, 80), (3, 400), (4, 40), (5, 70))]

drawing = Drawing(500, 300)

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

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

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

title = Label()
コード例 #52
0
ファイル: SubFunction.py プロジェクト: dxcv/My_Quant
def genLPDrawing(data, data_note, width=letter[0]*0.8, height=letter[1]*0.25, timeAxis='day', y_min_zero=False):
    """
    函数功能:生成Drawing之用
    :return:
    """

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

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

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

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

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

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

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

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

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

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

    elif timeAxis=='quarter':

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

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

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

    elif timeAxis=='year':

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

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

    elif timeAxis=='month':

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

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

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

    return drawing
コード例 #53
0
def makeFrapFigure(session, commandArgs):
	"""
	Main method called to make the figure. 
	Returns fileID object of the child of the fileAnnotation
	"""
	roiService = session.getRoiService()
	queryService = session.getQueryService()
	updateService = session.getUpdateService()
	rawFileStore = session.createRawFileStore()
	rawPixelStore = session.createRawPixelsStore()
	renderingEngine = session.createRenderingEngine()
	
	imageId = commandArgs["imageId"]
	
	theC = 0
	if "theC" in commandArgs:
		theC = commandArgs["theC"]
	
	image = queryService.get("Image", imageId)
	imageName = image.getName().getValue()
	
	query_string = "select p from Pixels p join fetch p.image i join fetch p.pixelsType pt where i.id='%d'" % imageId
	pixels = queryService.findByQuery(query_string, None)
	
	#pixels = image.getPrimaryPixels()
	pixelsId = pixels.getId().getValue()
	
	
	#sizeX = pixels.getSizeX().getValue()
	#sizeY = pixels.getSizeY().getValue()
	#sizeZ = pixels.getSizeZ().getValue()
	#sizeC = pixels.getSizeC().getValue()
	#sizeT = pixels.getSizeT().getValue()
	
	bypassOriginalFile = True
	rawPixelStore.setPixelsId(pixelsId, bypassOriginalFile)

	roiLabels = ["FRAP", "Base", "Whole"]
	
	roiMap = getEllipses(roiService, imageId, roiLabels)
	
	for l in roiLabels:
		if l not in roiMap.keys():
			print "ROI: '%s' not found. Cannot calculate FRAP" % l
			return
			
			
	frapMap = roiMap["FRAP"]
	baseMap = roiMap["Base"]
	wholeMap = roiMap["Whole"]
	
	# make a list of the t indexes that have all 3 of the Shapes we need. 
	# and a list of the roiShapes for easy access.
	tIndexes = []
	frapROI = []
	baseROI = []
	wholeROI = []
	for t in frapMap.keys():
		if t in baseMap.keys() and t in wholeMap.keys():
			tIndexes.append(t)	
			frapROI.append(frapMap[t])	
			baseROI.append(baseMap[t])	
			wholeROI.append(wholeMap[t])
	tIndexes.sort()
	
	log("T Indexes, " + ",".join([str(t) for t in tIndexes]))
	
	# get the actual plane times. 
	timeMap = figUtil.getTimes(queryService, pixelsId, tIndexes, theZ=0, theC=0)
	timeList = []
	for t in tIndexes:
		if t in timeMap:	
			timeList.append(timeMap[t])
		else:	# handles images which don't have PlaneInfo
			timeMap[t] = t
			timeList.append(t)
			
	log("Plane times (secs), " + ",".join([str(t) for t in timeList]))
	
	# lists of averageIntensity for the 3 ROIs 
	frapValues = []
	baseValues = []
	wholeValues = []
	
	frapBleach = None
	
	theZ = 0
	for i, t in enumerate(tIndexes):
		shapes = [frapROI[i], baseROI[i], wholeROI[i]]
		theZ = frapROI[i][4]	# get theZ from the FRAP ROI
		# get a list of the average values of pixels in the three shapes. 
		averages = analyseEllipses(shapes, pixels, rawPixelStore, theC, t, theZ)
		if frapBleach == None:	
			frapBleach = averages[0]
		else:
			frapBleach = min(frapBleach, averages[0])
		frapValues.append(averages[0])
		baseValues.append(averages[1])
		wholeValues.append(averages[2])

	log("FRAP Values, " + ",".join([str(v) for v in frapValues]))
	log("Base Values, " + ",".join([str(v) for v in baseValues]))
	log("Whole Values, " + ",".join([str(v) for v in wholeValues]))
	
	# find the time of the bleach event (lowest intensity )
	tBleach = frapValues.index(frapBleach)
	log("Pre-bleach frames, %d" % tBleach)
	if tBleach == 0:
		print "No pre-bleach images. Can't calculate FRAP"
		return
		
	# using frames before and after tBleach - calculate bleach ranges etc. 
	frapPre = average(frapValues[:tBleach]) - average(baseValues[:tBleach])
	wholePre = average(wholeValues[:tBleach]) - average(baseValues[:tBleach])
	wholePost = average(wholeValues[tBleach:]) - average(baseValues[tBleach:])

	# use these values to get a ratio of FRAP intensity / pre-Bleach intensity * (corrected by intensity of 'Whole' ROI)
	frapNormCorr = []
	for i in range(len(tIndexes)):
		frapNormCorr.append( (float(frapValues[i] - baseValues[i]) / frapPre) * (wholePre / float(wholeValues[i] - baseValues[i])) )
	
	log("FRAP Corrected, " + ",".join([str(v) for v in frapNormCorr]))
	
	# work out the range of recovery (bleach -> plateau) and the time to reach half of this after bleach. 
	frapBleachNormCorr = frapNormCorr[tBleach]
	plateauNormCorr = average(frapNormCorr[-5:])
	plateauMinusBleachNormCorr = plateauNormCorr - frapBleachNormCorr
	mobileFraction = plateauMinusBleachNormCorr / float(1 - frapBleachNormCorr)
	immobileFraction = 1 - mobileFraction
	halfMaxNormCorr = plateauMinusBleachNormCorr /2 + frapBleachNormCorr
	
	log("Corrected Bleach Intensity, %f" % frapBleachNormCorr)
	log("Corrected Plateau Intensity, %f" % plateauNormCorr)
	log("Plateau - Bleach, %f" % plateauMinusBleachNormCorr)
	log("Mobile Fraction, %f" % mobileFraction)
	log("Immobile Fraction, %f" % immobileFraction)
	log("Half Recovered Intensity, %f" % halfMaxNormCorr)

	# Define the T-half for this FRAP. In place of fitting an exact curve to the
	# data, find the two time-points that the half Max of recovery sits between
	# and find the T-half using a linear approximation between these two points.
	# The T-half is this solved for halfMaxNormCorr - timestamp(tBleach)
	th = None
	for t in tIndexes[tBleach:]:
		if halfMaxNormCorr < frapNormCorr[t]:
			th = tIndexes[t]
			break
	
	y1 = frapNormCorr[th-1]
	y2 = frapNormCorr[th]
	
	
	x1 = timeList[th-1]
	x2 = timeList[th]
	m1 = (y2-y1)/(x2-x1); #Gradient of the line
	c1 = y1-m1*x1;  #Y-intercept
	tHalf = (halfMaxNormCorr-c1)/m1 - timeList[tBleach]
	
	log("Bleach time, %f seconds" % timeList[tBleach])
	log("T-Half, %f seconds" % tHalf)
	
	figLegend = "\n".join(logLines)
	print figLegend
	
	# make PIL image of the last frame before FRAP
	spacer = 5
	frames = []
	ellipses = [frapROI[tBleach-1], frapROI[tBleach], frapROI[-1]]
	frames.append(getPlaneImage(renderingEngine, pixelsId, theZ, tIndexes[tBleach-1]))
	frames.append(getPlaneImage(renderingEngine, pixelsId, theZ, tIndexes[tBleach]))
	frames.append(getPlaneImage(renderingEngine, pixelsId, theZ, tIndexes[-1]))
	figW = 450
	font = imgUtil.getFont(16)
	fontH = font.getsize("FRAP")[1]
	labels = ["Pre-Bleach", "Bleach", "Recovery"]
	imgW = (figW - (2 * spacer) ) / len(frames)
	# shrink the images by width, or maintain height if shrink not needed. 
	smallImages = [imgUtil.resizeImage(img, imgW, img.size[1]) for img in frames]
	zoomOut = 1/imgUtil.getZoomFactor(img.size, imgW, img.size[1])
	figH = smallImages[0].size[1] + spacer + fontH 
	frapCanvas = Image.new("RGB", (figW, figH), (255,255,255))
	draw = ImageDraw.Draw(frapCanvas)
	y = spacer + fontH
	x = 0
	for l, img in enumerate(frames):
		label = labels[l]
		indent = (imgW - font.getsize(label)[0]) / 2
		draw.text((x+indent, 0), label, font=font, fill=(0,0,0))
		roiImage = addEllipse(smallImages[l], ellipses[l], zoomOut)
		imgUtil.pasteImage(roiImage, frapCanvas, x, y)
		x += spacer + imgW
	#frapCanvas.show()		# bug-fixing only
	fileName = imageName + ".png"
	frapCanvas.save(fileName, "PNG")
	
	format = PNG
	output = fileName
	
	# if reportLab has imported...
	if reportLab:
		# we are going to export a PDF, not a JPEG
		format = PDF
		output = imageName + ".pdf"
		
		# create a plot of curve fitted to:  y = 1 - e(It)
		# where thalf = ln 0.5 / -I
		# http://www.embl.de/eamnet/frap/html/halftime.html
		import math
		i = 1/float(tHalf) * math.log(0.5)
		fittedPoints = []
		for t in timeList[3:]:
			print math.exp(t * i)
			f = frapBleachNormCorr + ((plateauNormCorr-frapBleachNormCorr) * (1 - math.exp(t * i)))
			fittedPoints.append(f)
		print fittedPoints
		log("Fitted: , " + str(fittedPoints))
		
		# create a plot of the FRAP data
		figHeight = 450
		figWidth = 400
		drawing = Drawing(figWidth, figHeight)
		lp = LinePlot()
		lp.x = 50
		lp.y = 50
		lp.height = 300
		lp.width = 300
		lp.data = [zip(timeList, frapNormCorr), zip(timeList[3:], fittedPoints)]
		lp.lines[0].strokeColor = colors.red
		lp.lines[0].symbol = makeMarker('Circle')
		lp.lines[1].strokeColor = colors.green
		lp.lines[1].symbol = makeMarker('Circle')
		
		drawing.add(lp)
	
		drawing.add(String(200,25, 'Time (seconds)', fontSize=12, textAnchor="middle"))
		drawing.add(String(200,figHeight-25, imageName, fontSize=12, textAnchor="middle"))
		drawing.add(String(200,figHeight-50, 'T(1/2) = %f' % tHalf, fontSize=12, textAnchor="middle"))
	
		# create an A4 canvas to make the pdf figure 
		figCanvas = canvas.Canvas(output, pagesize=A4)
		pasteX = 100
		pasteY = 75
		# add the FRAP image
		figCanvas.drawImage(fileName, pasteX-25, pasteY)
		# add the FRAP data plot
		renderPDF.draw(drawing, figCanvas, pasteX, 300, showBoundary=True)
		figCanvas.save()
	
	fileId = scriptUtil.uploadAndAttachFile(queryService, updateService, rawFileStore, image, output, format, figLegend)
	return fileId