Ejemplo n.º 1
0
def neighbours_to_svg(Prg, NeighBours, Spirals, Fname="svg_neighbours.html"):
    SvgObj = svg.obj_new()
    for CoordSpiralCenter, CoordsConnected in NeighBours.items():
        for CoordConnected in CoordsConnected:
            # print(Fname, "Debug:", CoordSpiralCenter, CoordConnected)
            SpiralLen = len(Spirals[CoordSpiralCenter])
            # Dash = str(SpiralLen) + "," + str(SpiralLen)
            svg.line(SvgObj,
                     CoordSpiralCenter,
                     CoordConnected,
                     StrokeWidth=SpiralLen,
                     HalfLine=True)

    # the dot has to cover the lines
    for CoordSpiralCenter, CoordsConnected in NeighBours.items():
        svg.dot(SvgObj, CoordSpiralCenter, R=len(Spirals[CoordSpiralCenter]))
        svg.text(SvgObj,
                 CoordSpiralCenter,
                 str(CoordSpiralCenter),
                 Color="green",
                 ShiftXAbs=-20)

    SvgSrc = svg.pack(SvgObj)
    # print(SvgSrc)
    util.file_write(Prg, Fname=Fname, Content=SvgSrc)
Ejemplo n.º 2
0
def makesaliencelegend():
    out = svg.svg(width=2000, height=100, viewbox='0 0 2000 100')
    if c.swapsaliencemagnitude:
        te = 'Magnitude:'
    else: 
        te = 'Salience:'
        
    out.add(svg.text(te, 70, 50, fontsize=c.font))
    for i in range(0,2):
        if i==0:
            red,green,blue = c.colorsbenefit[0]
        elif c.colorsbenefit[0]==c.colorscost[0]:
            return out
        else:
            red,green,blue = c.colorscost[0]
        
        for j in range(0,3+c.includezerosalience):
            out.add(svg.text(j + (1-c.includezerosalience), (i*950+290+j*(200-60*c.includezerosalience)), 50, fontsize=c.font))
            if(c.saliencebycolor):
                s = ((j+1)**c.saliencebycolor)/((3.0+c.includezerosalience)**c.saliencebycolor)
            else:
                s = 1
            if(c.saliencebywidth):
                out.add(svg.rect((i*950+320+j*(200-60*c.includezerosalience)),11,80,50, stroke='black', fill='none'))
                if(c.saliencebywidth>1):
                    w = 80.0/(c.saliencebywidth**3)*(c.saliencebywidth**(j+1-c.includezerosalience))
                else:
                    w = 80.0/(3+c.includezerosalience)*(j+1)
                out.add(svg.rect((i*950+360+j*(200-60*c.includezerosalience)-(w/2)),11,w,50, stroke='none', fill='rgb(%s,%s,%s)' % (red,green,blue), p='fill-opacity="%s"' % s))
            else:
                out.add(svg.rect((i*950+320+j*(200-60*c.includezerosalience)),11,80,50, stroke='none', fill='rgb(%s,%s,%s)' % (red,green,blue), p='fill-opacity="%s"' % s))
    return out
Ejemplo n.º 3
0
def write_polygon_projection_svg(f, facepaths, sheetwidth, padding, use_numbers, use_map, center_dot, comment):

    x, y = padding, padding
    w, cur_h = 0., 0.
    pos = []
    for i, face in enumerate(facepaths):
        min_x, min_y, max_x, max_y = face['bbox']
        face_w, face_h = max_x-min_x, max_y-min_y
        if x + face_w > sheetwidth:
            y += cur_h + padding
            x, cur_h = padding, 0.

        pos.append( (x-min_x, y-min_y) )
        cur_h = max(cur_h, face_h)
        x += face_w + padding
        w = max(w, x)

    h = y + cur_h + padding
    w, h = int(math.ceil(w)), int(math.ceil(h))

    f.write(svg.header(w,h))
    f.write('<title><![CDATA['+comment+']]></title>')

    for i, face in enumerate(facepaths):

        x, y = pos[i]
        borders_path = svg.polygon_path(face['borders'])
#        borders_path = svg.polygon_path(face['borders']) + ''.join(svg.polygon_path(s) for s in face['slots'])
        projection_path = svg.polygon_multipath(face['projection'])

        borders = svg.path( borders_path, style=cut )

        if use_map:
            engraving = svg.group( svg.path( borders_path, style=engrave )+
                                   svg.path( projection_path, style=engrave ),
                                   id='engrave_'+str(i) )
        else:
            engraving = ''

        if use_numbers:
            text = svg.text(0,2.5, str(i), style=commentstyle+';'+textstyle )

            for n, a, b in zip(face['neighbours'],
                               face['points'], face['points'][1:]+face['points'][:1]):
                x1, y1 = a
                x2, y2 = b
                dx, dy = (x1+x2)/3., (y1+y2)/3.+1.5
                text += svg.text(dx,dy, str(n), style=commentstyle+';'+smalltextstyle )
        else:
            text = ''

        if center_dot:
            dot = svg.circle(.1, style=cut)
        else:
            dot = ''

        f.write(svg.group( svg.group(borders + engraving) + text + dot, transform='translate('+str(x)+' '+str(y)+')', id='face_'+str(i) ))

    f.write(svg.footer())
Ejemplo n.º 4
0
def write_polygon_projection_svg(f, facepaths, sheetwidth, padding, use_numbers, use_map, center_dot, comment):

    x, y = padding, padding
    w, cur_h = 0., 0.
    pos = []
    for i, face in enumerate(facepaths):
        min_x, min_y, max_x, max_y = face['bbox']
        face_w, face_h = max_x-min_x, max_y-min_y
        if x + face_w > sheetwidth:
            y += cur_h + padding
            x, cur_h = padding, 0.

        pos.append( (x-min_x, y-min_y) )
        cur_h = max(cur_h, face_h)
        x += face_w + padding
        w = max(w, x)

    h = y + cur_h + padding
    w, h = int(math.ceil(w)), int(math.ceil(h))

    f.write(svg.header(w,h))
    f.write('<title><![CDATA['+comment+']]></title>')

    for i, face in enumerate(facepaths):

        x, y = pos[i]
        borders_path = svg.polygon_path(face['borders'])
#        borders_path = svg.polygon_path(face['borders']) + ''.join(svg.polygon_path(s) for s in face['slots'])
        projection_path = svg.polygon_multipath(face['projection'])

        borders = svg.path( borders_path, style=cut )

        if use_map:
            engraving = svg.group( svg.path( borders_path, style=engrave )+
                                   svg.path( projection_path, style=engrave ),
                                   id='engrave_'+str(i) )
        else:
            engraving = ''

        if use_numbers:
            text = svg.text(0,2.5, str(i), style=commentstyle+';'+textstyle )

            for n, a, b in zip(face['neighbours'],
                               face['points'], face['points'][1:]+face['points'][:1]):
                x1, y1 = a
                x2, y2 = b
                dx, dy = (x1+x2)/3., (y1+y2)/3.+1.5
                text += svg.text(dx,dy, str(n), style=commentstyle+';'+smalltextstyle )
        else:
            text = ''

        if center_dot:
            dot = svg.circle(.1, style=cut)
        else:
            dot = ''

        f.write(svg.group( svg.group(borders + engraving) + text + dot, transform='translate('+str(x)+' '+str(y)+')', id='face_'+str(i) ))

    f.write(svg.footer())
Ejemplo n.º 5
0
 def text(self, text,x=150,y=25, font_size=22,text_anchor="middle",
   style= {}):
   element = svg.text(text,x=x,y=y,
   font_size=font_size,text_anchor=text_anchor,
   style=style)
   self.panel <= element
   return element
Ejemplo n.º 6
0
def path_in_char_to_svg(Prg, Paths, Spirals, Fname="svg_paths_in_char.html"):
    SvgObj = svg.obj_new()

    # the dot has to cover the lines
    print("")
    print("Paths:", Paths)
    for Path in Paths:
        SpiralPrev = None
        for Spiral in Path:
            if SpiralPrev:
                svg.line(SvgObj, Spiral, SpiralPrev, StrokeWidth=5)

            print("path in char, svg, Spiral: ", Spiral)
            svg.dot(SvgObj, Spiral, R=len(Spirals[Spiral]))
            svg.text(SvgObj, Spiral, str(Spiral), Color="green", ShiftXAbs=-20)
            SpiralPrev = Spiral

    SvgSrc = svg.pack(SvgObj)
    # print(SvgSrc)
    util.file_write(Prg, Fname=Fname, Content=SvgSrc)
def plotXYSVG(drawSpace, dataX, dataY, rank=0, dataLabel=[], plotColor = "black", axesColor="black", labelColor="black", symbolColor="red", XLabel=None, YLabel=None, title=None, fitcurve=None, connectdot=1, displayR=None, loadingPlot = 0, offset= (80, 20, 40, 60), zoom = 1, specialCases=[], showLabel = 1):
    'displayR : correlation scatter plot, loadings : loading plot'

    dataXRanked, dataYRanked = webqtlUtil.calRank(dataX, dataY, len(dataX))

    # Switching Ranked and Unranked X and Y values if a Spearman Rank Correlation
    if rank == 0:
        dataXPrimary = dataX
        dataYPrimary = dataY
        dataXAlt = dataXRanked
        dataYAlt = dataYRanked

    else:
        dataXPrimary = dataXRanked
        dataYPrimary = dataYRanked
        dataXAlt = dataX
        dataYAlt = dataY



    xLeftOffset, xRightOffset, yTopOffset, yBottomOffset = offset
    plotWidth = drawSpace.attributes['width'] - xLeftOffset - xRightOffset
    plotHeight = drawSpace.attributes['height'] - yTopOffset - yBottomOffset
    if plotHeight<=0 or plotWidth<=0:
        return
    if len(dataXPrimary) < 1 or  len(dataXPrimary) != len(dataYPrimary) or (dataLabel and len(dataXPrimary) != len(dataLabel)):
        return

    max_X=max(dataXPrimary)
    min_X=min(dataXPrimary)
    max_Y=max(dataYPrimary)
    min_Y=min(dataYPrimary)

    #for some reason I forgot why I need to do this
    if loadingPlot:
        min_X = min(-0.1,min_X)
        max_X = max(0.1,max_X)
        min_Y = min(-0.1,min_Y)
        max_Y = max(0.1,max_Y)

    xLow, xTop, stepX=detScale(min_X,max_X)
    yLow, yTop, stepY=detScale(min_Y,max_Y)
    xScale = plotWidth/(xTop-xLow)
    yScale = plotHeight/(yTop-yLow)

    #draw drawing region
    r = svg.rect(xLeftOffset, yTopOffset, plotWidth,  plotHeight, 'none', axesColor, 1)
    drawSpace.addElement(r)

    #calculate data points
    data = map(lambda X, Y: (X, Y), dataXPrimary, dataYPrimary)
    xCoord = map(lambda X, Y: ((X-xLow)*xScale + xLeftOffset, yTopOffset+plotHeight-(Y-yLow)*yScale), dataXPrimary, dataYPrimary)
    labelFontF = "verdana"
    labelFontS = 11

    if loadingPlot:
        xZero = -xLow*xScale+xLeftOffset
        yZero = yTopOffset+plotHeight+yLow*yScale
        for point in xCoord:
            drawSpace.addElement(svg.line(xZero,yZero,point[0],point[1], "red", 1))
    else:
        if connectdot:
            pass
            #drawSpace.drawPolygon(xCoord,edgeColor=plotColor,closed=0)
        else:
            pass

    for i, item in enumerate(xCoord):
        if dataLabel and dataLabel[i] in specialCases:
            drawSpace.addElement(svg.rect(item[0]-3, item[1]-3, 6, 6, "none", "green", 0.5))
            #drawSpace.drawCross(item[0],item[1],color=pid.blue,size=5)
        else:
            drawSpace.addElement(svg.line(item[0],item[1]+5,item[0],item[1]-5,symbolColor,1))
            drawSpace.addElement(svg.line(item[0]+5,item[1],item[0]-5,item[1],symbolColor,1))
        if showLabel and dataLabel:
            pass
            drawSpace.addElement(svg.text(item[0], item[1]+14, dataLabel[i], labelFontS,
                    labelFontF, text_anchor="middle", style="stroke:blue;stroke-width:0.5;"))
            #canvas.drawString(, item[0]- canvas.stringWidth(dataLabel[i],
            #       font=labelFont)/2, item[1]+14, font=labelFont, color=pid.blue)

    #draw scale
    #scaleFont=pid.Font(ttf="cour",size=14,bold=1)
    x=xLow
    for i in range(stepX+1):
        xc=xLeftOffset+(x-xLow)*xScale
        drawSpace.addElement(svg.line(xc,yTopOffset+plotHeight,xc,yTopOffset+plotHeight+5, axesColor, 1))
        strX = cformat(d=x, rank=rank)
        drawSpace.addElement(svg.text(xc,yTopOffset+plotHeight+20,strX,13, "courier", text_anchor="middle"))
        x+= (xTop - xLow)/stepX

    y=yLow
    for i in range(stepY+1):
        yc=yTopOffset+plotHeight-(y-yLow)*yScale
        drawSpace.addElement(svg.line(xLeftOffset,yc,xLeftOffset-5,yc, axesColor, 1))
        strY = cformat(d=y, rank=rank)
        drawSpace.addElement(svg.text(xLeftOffset-10,yc+5,strY,13, "courier", text_anchor="end"))
        y+= (yTop - yLow)/stepY

    #draw label
    labelFontF = "verdana"
    labelFontS = 17
    if XLabel:
        drawSpace.addElement(svg.text(xLeftOffset+plotWidth/2.0,
                yTopOffset+plotHeight+yBottomOffset-10,XLabel,
                labelFontS, labelFontF, text_anchor="middle"))

    if YLabel:
        drawSpace.addElement(svg.text(xLeftOffset-50,
                 yTopOffset+plotHeight/2,YLabel,
                labelFontS, labelFontF, text_anchor="middle", style="writing-mode:tb-rl", transform="rotate(270 %d %d)" % (xLeftOffset-50,  yTopOffset+plotHeight/2)))
        #drawSpace.drawString(YLabel, xLeftOffset-50, yTopOffset+plotHeight- (plotHeight-drawSpace.stringWidth(YLabel,font=labelFont))/2.0,
        #       font=labelFont,color=labelColor,angle=90)


    if fitcurve:
        sys.argv = [ "mod_python" ]
        #from numarray import linear_algebra as la
        #from numarray import ones, array, dot, swapaxes
        fitYY = array(dataYPrimary)
        fitXX = array([ones(len(dataXPrimary)),dataXPrimary])
        AA = dot(fitXX,swapaxes(fitXX,0,1))
        BB = dot(fitXX,fitYY)
        bb = la.linear_least_squares(AA,BB)[0]

        xc1 = xLeftOffset
        yc1 = yTopOffset+plotHeight-(bb[0]+bb[1]*xLow-yLow)*yScale
        if yc1 > yTopOffset+plotHeight:
            yc1 = yTopOffset+plotHeight
            xc1 = (yLow-bb[0])/bb[1]
            xc1=(xc1-xLow)*xScale+xLeftOffset
        elif yc1 < yTopOffset:
            yc1 = yTopOffset
            xc1 = (yTop-bb[0])/bb[1]
            xc1=(xc1-xLow)*xScale+xLeftOffset
        else:
            pass

        xc2 = xLeftOffset + plotWidth
        yc2 = yTopOffset+plotHeight-(bb[0]+bb[1]*xTop-yLow)*yScale
        if yc2 > yTopOffset+plotHeight:
            yc2 = yTopOffset+plotHeight
            xc2 = (yLow-bb[0])/bb[1]
            xc2=(xc2-xLow)*xScale+xLeftOffset
        elif yc2 < yTopOffset:
            yc2 = yTopOffset
            xc2 = (yTop-bb[0])/bb[1]
            xc2=(xc2-xLow)*xScale+xLeftOffset
        else:
            pass

        drawSpace.addElement(svg.line(xc1,yc1,xc2,yc2,"green", 1))

    if displayR:
        labelFontF = "trebuc"
        labelFontS = 14
        NNN = len(dataX)

        corr = webqtlUtil.calCorrelation(dataXPrimary,dataYPrimary,NNN)[0]

        if NNN < 3:
            corrPValue = 1.0
        else:
            if abs(corr) >= 1.0:
                corrPValue = 0.0
            else:
                ZValue = 0.5*log((1.0+corr)/(1.0-corr))
                ZValue = ZValue*sqrt(NNN-3)
                corrPValue = 2.0*(1.0 - reaper.normp(abs(ZValue)))

        NStr = "N of Cases=%d" % NNN

        if rank == 1:
            corrStr = "Spearman's r=%1.3f P=%3.2E" % (corr, corrPValue)
        else:
            corrStr = "Pearson's r=%1.3f P=%3.2E" % (corr, corrPValue)

        drawSpace.addElement(svg.text(xLeftOffset,yTopOffset-10,NStr,
                labelFontS, labelFontF, text_anchor="start"))
        drawSpace.addElement(svg.text(xLeftOffset+plotWidth,yTopOffset-25,corrStr,
                labelFontS, labelFontF, text_anchor="end"))
    """
    """
    return
Ejemplo n.º 8
0
def plot(series,
         bins=40,
         smoothing=1,
         range_x=(0, 1),
         range_y=(0, 1),
         major=(0.1, 0.1),
         minor=(2, 2),
         title=None,
         subtitle=None,
         label_x=None,
         label_y=None,
         legend={},
         colors={}):

    resolution = 20 * bins
    kernel_width = smoothing / bins

    display = 800, 400
    margin_x = 120, 120
    margin_y = 80, 50 + 10 * (subtitle is not None) + 20 * (title is not None)

    area = display[0] - sum(margin_x), sum(margin_y) - display[1]
    offset = margin_x[0], display[1] - margin_y[0]

    start, end = range_x
    low, high = range_y

    # epsilon deals with floating point error
    cells = int((end - start) / major[0] * minor[0] +
                1e-5), int((high - low) / major[1] * minor[1] + 1e-5)

    grid_minor = []
    grid_major = []
    ticks = []
    labels = []
    for i in range(cells[0] + 1):
        x = i * major[0] / (minor[0] * (end - start))
        v = i * major[0] / minor[0] + start
        m = i % minor[0] == 0

        screen = tuple(
            tuple(map(round, transform(x, area, offset)))
            for x in ((x, 0), (x, 1)))
        length = 12 if m else 6
        (grid_major if m else grid_minor).append(
            svg.path(
                (transform(screen[0], (1, 1),
                           (0.5, 0)), transform(screen[1], (1, 1), (0.5, -1))),
                classes=('grid', 'grid-major' if m else 'grid-minor')))
        ticks.append(
            svg.path((transform(screen[0], (1, 1), (0.5, 8)),
                      transform(screen[0], (1, 1), (0.5, 8 + length))),
                     classes=('tick', )))

        if m:
            labels.append(
                svg.text(str(round(v, 3)),
                         position=transform(screen[0], (1, 1),
                                            (0, 16 + length)),
                         classes=('label-numeric', 'label-x')))

    for i in range(cells[1] + 1):
        y = i * major[1] / (minor[1] * (high - low))
        v = i * major[1] / minor[1] + low
        m = i % minor[1] == 0

        screen = tuple(
            tuple(map(round, transform(y, area, offset)))
            for y in ((0, y), (1, y)))
        length = 12 if m else 6

        (grid_major if m else grid_minor).append(
            svg.path(
                (transform(screen[0], (1, 1),
                           (0, -0.5)), transform(screen[1], (1, 1),
                                                 (1, -0.5))),
                classes=('grid', 'grid-major' if m else 'grid-minor')))
        ticks.append(
            svg.path((transform(screen[0], (1, 1), (-8, -0.5)),
                      transform(screen[0], (1, 1), (-8 - length, -0.5))),
                     classes=('tick', )))

        if m:
            labels.append(
                svg.text(str(round(v, 3)),
                         position=transform(screen[0], (1, 1),
                                            (-16 - length, 0)),
                         classes=('label-numeric', 'label-y')))

    paths = []
    # emit using the same ordering as `colors`
    for name, *_ in colors:
        scale = 1 / (bins * len(series[name]))
        curve = tuple((x / resolution, (sum(
            kernel(x / resolution, (point - start) /
                   (end - start), kernel_width)
            for point in series[name]) * scale - low) / (high - low))
                      for x in range(resolution + 1))

        paths.append(
            svg.path(map(lambda x: transform(x, area, offset), curve),
                     classes=(name, 'density-curve')))

    for i, (name, label) in enumerate(legend):
        base = tuple(map(round, transform((1, 1), area, offset)))
        dy = 20 * i
        paths.append(
            svg.path((transform(base, (1, 1),
                                (10, dy)), transform(base, (1, 1), (25, dy))),
                     classes=(name, 'density-curve')))
        labels.append(
            svg.text(label,
                     position=transform(base, (1, 1), (32, dy)),
                     classes=('label-legend', )))

    if type(title) is str:
        screen = tuple(map(round, transform((0.5, 1), area, offset)))
        labels.append(
            svg.text(title,
                     position=transform(screen, (1, 1), (0, -40)),
                     classes=('title', )))
    if type(subtitle) is str:
        screen = tuple(map(round, transform((0.5, 1), area, offset)))
        labels.append(
            svg.text(subtitle,
                     position=transform(screen, (1, 1), (0, -20)),
                     classes=('subtitle', )))

    if type(label_x) is str:
        screen = tuple(map(round, transform((0.5, 0), area, offset)))
        labels.append(
            svg.text(label_x,
                     position=transform(screen, (1, 1), (0, 50)),
                     classes=('label-axis', 'label-x')))
    if type(label_y) is str:
        screen = tuple(map(round, transform((0, 0.5), area, offset)))
        labels.append(
            svg.text(label_y,
                     position=transform(screen, (1, 1), (-80, 0)),
                     classes=('label-axis', 'label-y', 'label-vertical')))

    def linestyle(color, line):
        properties = [('stroke', color)]
        if line == 'dashed':
            properties.append(('stroke-dasharray', '6 3'))
        return '\n'.join('    {0}: {1};'.format(property, value)
                         for property, value in properties)

    style = '''
    rect.background 
    {
        fill:   white;
    }
    
    path.grid 
    {
        stroke-width: 1px;
        fill:   none;
    }
    path.grid-major 
    {
        stroke: #eeeeeeff;
    }
    path.grid-minor 
    {
        stroke: #f5f5f5ff;
    }
    
    path.tick 
    {
        stroke-width: 1px;
        stroke: #333333ff;
        fill:   none;
    }
    
    text
    {
        fill: #333333ff;
        font-family: 'SF Mono';
    }
    text.label-numeric 
    {
        font-size: 12px;
    }
    text.label-x 
    {
        text-anchor: middle; 
        dominant-baseline: hanging;
    }
    text.label-y 
    {
        text-anchor: end; 
        dominant-baseline: middle;
    }
    text.label-legend 
    {
        font-size: 12px;
        text-anchor: begin; 
        dominant-baseline: middle;
    }
    
    text.label-axis 
    {
        font-size: 14px;
        font-weight: 700;
    }
    text.label-vertical.label-y 
    {
        text-anchor: middle; 
        transform-box: fill-box;
        transform-origin: center;
        transform: rotate(-90deg);
    }
    
    text.title, text.subtitle 
    {
        text-anchor: middle; 
    }
    text.title 
    {
        font-size: 20px;
    }
    text.subtitle 
    {
        font-size: 12px;
    }
    
    path.density-curve 
    {
        stroke-linejoin: round;
        stroke-width: 2px;
        fill:   none;
    }
    ''' + ''.join('''
    path.{0} 
    {{
        {1}
    }}
    '''.format(name, linestyle(color, line)) for name, color, line in colors)

    return svg.svg(display, style,
                   grid_minor + grid_major + ticks + paths + labels)
Ejemplo n.º 9
0
def makebarsvert(magnitudebenefit,saliencebenefit,magnitudecost,saliencecost):

    if c.swapsaliencemagnitude:
        tm = saliencebenefit[:]
        saliencebenefit = magnitudebenefit[:]
        magnitudebenefit = tm
        tm = saliencecost[:]
        saliencecost = magnitudecost[:]
        magnitudecost = tm

    #general variables
    t = 0
    if c.centerlabel is not None:
        t = 50
    out = svg.svg(width = 1000, height = 2250+t, viewbox='0 0 1000 2150')
    barwidth = 2050/(21+c.spacebars*2)
    
    chart = svg.g('transform="translate(0 %s)"' % t)
    out.add(chart)
    
    for cb in range(0,2):
        if c.centerlabel is not None:
            out.add(svg.text(c.centerlabel[1-cb], 250+(cb)*500, 25, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
        
        if(cb==1):
            colors=c.colorsbenefit
            magnitude=magnitudebenefit
            salience=saliencebenefit
        else:    
            magnitude=magnitudecost
            salience=saliencecost
            colors=c.colorscost    

        #draw bars
        for i in range(0,21):
            h = barheight(magnitude[i]+c.includezeromagnitude)
            if(c.saliencebywidth==1):
                w = barwidth/(3+c.includezerosalience)*(salience[i]+c.includezerosalience)
            elif(c.saliencebywidth>1):
                w = barwidth/(c.saliencebywidth**3)*(c.saliencebywidth**salience[i])
            else:
                w = barwidth
            if(c.saliencebycolor):
                s = ((salience[i]+c.includezerosalience)**c.saliencebycolor)/((3.0+c.includezerosalience)**c.saliencebycolor)
            else:
                s = 1
            red,green,blue = colors[i//7]
            if(salience[i]>0 or c.includezerosalience):
                barlinecolor=(int(red*c.barlineshade),int(green*c.barlineshade),int(blue*c.barlineshade))
                chart.add(svg.rect(500+(cb-1)*h,(i+(i//7)*c.spacebars)*barwidth+(barwidth-w)/2,h,w, fill='rgb(%s,%s,%s)' % (red,green,blue), stroke='rgb(%s,%s,%s)' % (barlinecolor[0],barlinecolor[1],barlinecolor[2]), strokewidth=c.barline, p='fill-opacity="%s"' % s))

            #invisible link and tooltip box
            newrect = svg.rect(500+(cb-1)*c.textradius,(i+(i//7)*c.spacebars)*barwidth,c.textradius,barwidth, fill='white', p='fill-opacity="0.0"')
            newrect.add(svg.title(' %s: %s\n Magnitude %s\tSalience %s' % (c.indicatornames[i], c.indicatorfullnames[i], magnitude[i], salience[i])))
            chart.add(newrect)


        #draw ygrid
        for i in range(0,c.maxvalue+c.includezeromagnitude+1):
            if(i==c.includezeromagnitude):
                w=5
            else:
                w=1
            if (c.ygrid or i==0):
                x2 = 0
            else:
                x2 = 2050-c.ticksize
            chart.add(svg.line(500+barheight(i)*(cb-.5)*2,2050+c.ticksize,500+barheight(i)*(cb-.5)*2,x2,'black',w))   


    #draw xgrid dividers
    chart.add(svg.line(500-c.edgeradius,2050,500+c.edgeradius,2050,'black',5))
    for i in range(0,21+c.spacebars*2):
        if (c.xgrid or (c.saliencebywidth and c.drawsaliencedividers)):
            chart.add(svg.line(500-c.edgeradius,barwidth*i,500+c.edgeradius,barwidth*i, 'black', 1))
        elif(ticksize):
            chart.add(svg.line(500-c.ticksize,barwidth*i,500+c.ticksize,barwidth*i, 'black', 1))

    #draw salience dividers and column headings
    for i in range(0,21):
        if(c.saliencebywidth and c.drawsaliencedividers):
            for j in range(1-c.includezerosalience,3):
                if(c.saliencebywidth>1):
                    w = barwidth/2/(c.saliencebywidth**3)*(c.saliencebywidth**j)
                else:
                    w = barwidth/2/(3+c.includezerosalience)*(j+c.includezerosalience)
                for k in [1,-1]:
                    chart.add(svg.line(500-c.edgeradius,barwidth*(i+(i//7)+.5)+k*w,500+c.edgeradius,barwidth*(i+(i//7)+.5)+k*w, 'black', .5))

        x = (500 - c.textradius)
        y = ((i+(i//7)*c.spacebars+.5)*barwidth)
        chart.add(svg.text(c.indicatornames[i], x, y, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))

    #draw magnitude legend
    if c.magnitudelegend:
        if c.swapsaliencemagnitude:
            te = 'Salience'
        else: 
            te = 'Magnitude'
        mag=svg.g(p='transform="translate(0 2050)"')
        mag.add(svg.text(te, 500, 100, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))

        lastnumber=1
        for i in range(0,c.maxvalue+c.includezeromagnitude+1):
            if (i-c.includezeromagnitude==0):
                mag.add(svg.text(i-c.includezeromagnitude,502-barheight(i),40, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
                if (barheight(i)*2>c.font):
                    mag.add(svg.text(i-c.includezeromagnitude,502+barheight(i), 40, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
            elif (i-c.includezeromagnitude>0):
                # alternate top and bottom if axis lables too close
                mag.add(svg.text(i-c.includezeromagnitude, 502+barheight(i)*lastnumber,40, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
                if (barheight(i)-barheight(i-1)>c.font):
                    mag.add(svg.text(i-c.includezeromagnitude, 502-barheight(i)*lastnumber,40, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
                else:
                    lastnumber = lastnumber * -1
        chart.add(mag)


    return out
Ejemplo n.º 10
0
def makemagnitudelegend():
    angles = [-math.pi/2,math.pi/2]
    wedgeangle = math.pi*2/21
    
    out = svg.svg(width=250, height=1000, viewbox='0 0 250 1000')
    
    
    x = (500 + math.cos(angles[0])*c.textradius)
    y = (500 + math.sin(angles[0])*c.textradius)
    if c.swapsaliencemagnitude:
        te = 'Salience:'
    else: 
        te = 'Magnitude:'
    out.add(svg.text(te, 125, 25, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
    
    for angle in angles:
    
        x1 = (125 + math.cos(angle+wedgeangle/2)*c.centerradius)
        y1 = (500 + math.sin(angle+wedgeangle/2)*c.centerradius)
        x2 = (125 + math.cos(angle+wedgeangle/2)*c.textradius)
        y2 = (500 + math.sin(angle+wedgeangle/2)*c.textradius)
        x3 = (125 + math.cos(angle-wedgeangle/2)*c.textradius)
        y3 = (500 + math.sin(angle-wedgeangle/2)*c.textradius)
        x4 = (125 + math.cos(angle-wedgeangle/2)*c.centerradius)
        y4 = (500 + math.sin(angle-wedgeangle/2)*c.centerradius)
    
        out.add(svg.line(x1, y1, x2, y2, 'black', 2))
        out.add(svg.line(x3, y3, x4, y4, 'black', 2))
    
        
    
        if(c.drawsaliencedividers):
            x1 = (125 + math.cos(angle)*c.centerradius)
            y1 = (500 + math.sin(angle)*c.centerradius)
            x2 = (125 + math.cos(angle)*c.edgeradius)
            y2 = (500 + math.sin(angle)*c.edgeradius)
            out.add(svg.line(x1, y1, x2, y2, 'black', .5))
            for j in range(1-c.includezerosalience,3):
                if(c.saliencebywidth>1):
                    wedgewidth = wedgeangle/2/(c.saliencebywidth**3)*(c.saliencebywidth**j)
                else:
                    wedgewidth = wedgeangle/2/(3+c.includezerosalience)*(j+c.includezerosalience)
                x1 = (125 + math.cos(angle-wedgewidth)*c.centerradius)
                y1 = (500 + math.sin(angle-wedgewidth)*c.centerradius)
                x2 = (125 + math.cos(angle-wedgewidth)*c.edgeradius)
                y2 = (500 + math.sin(angle-wedgewidth)*c.edgeradius)
                out.add(svg.line(x1, y1, x2, y2, 'black', .5))
                x1 = (125 + math.cos(angle+wedgewidth)*c.centerradius)
                y1 = (500 + math.sin(angle+wedgewidth)*c.centerradius)
                x2 = (125 + math.cos(angle+wedgewidth)*c.edgeradius)
                y2 = (500 + math.sin(angle+wedgewidth)*c.edgeradius)
                out.add(svg.line(x1, y1, x2, y2, 'black', .5))
                
        for i in range(0,c.maxvalue+c.includezeromagnitude+1):
            if(i==c.includezeromagnitude):
                w=5
            else:
                w=1
            r=ringradii(i)
            x1 = (125 + math.cos(angle+wedgeangle/1.5)*r)
            y1 = (500 + math.sin(angle+wedgeangle/1.5)*r)
            x2 = (125 + math.cos(angle-wedgeangle/1.5)*r)
            y2 = (500 + math.sin(angle-wedgeangle/1.5)*r)
            d = 'M %s,%s A %s,%s 0 0,0 %s,%s' % (x1,y1,r,r,x2,y2)
            out.add(svg.path(d, stroke='black', strokewidth=w))

            y = y1
            if(i%2==0):
                x = x2 + 10*angle
            else:
                x = x1 - 10*angle
            if(i-c.includezeromagnitude>=0):
                out.add(svg.text(i-c.includezeromagnitude, x, y, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
    
    return out
Ejemplo n.º 11
0
def makecircle(magnitude, salience, benefit=1):
    if c.swapsaliencemagnitude:
        tm = salience[:]
        salience = magnitude[:]
        magnitude = tm
    
    #general variables
    indicatorseparatorangles = [-math.pi*2/21*i + math.pi/21 for i in range(0,22)]
    indicatorcenterangles = [-math.pi*2/21*i for i in range(0,21)]
    wedgeangle = math.pi*2/21
    
    
    out = svg.svg(width=1000, height=1000+100*c.saliencelegend, viewbox='0 0 1000 1%d00' % (1*c.saliencelegend==True))
    
    if(benefit):
        colors=c.colorsbenefit
    else:
        colors=c.colorscost
    if c.centerlabel is not None:
        out.add(svg.text(c.centerlabel[1-benefit], 500, 500, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
    
    #draw wedges
    for i in range(0,21):
        r = ringradii(magnitude[i]+c.includezeromagnitude)
        if(c.saliencebywidth==1):
            wedgewidth = wedgeangle/2/(3+c.includezerosalience)*(salience[i]+c.includezerosalience)
        elif(c.saliencebywidth>1):
            wedgewidth = wedgeangle/2/(saliencebywidth**3)*(c.saliencebywidth**salience[i])
        else:
            wedgewidth = wedgeangle/2
        x1 = (500 + math.cos(indicatorcenterangles[i]+wedgewidth)*c.centerradius)
        y1 = (500 + math.sin(indicatorcenterangles[i]+wedgewidth)*c.centerradius)
        x2 = (500 + math.cos(indicatorcenterangles[i]+wedgewidth)*r)
        y2 = (500 + math.sin(indicatorcenterangles[i]+wedgewidth)*r)
        x3 = (500 + math.cos(indicatorcenterangles[i]-wedgewidth)*r)
        y3 = (500 + math.sin(indicatorcenterangles[i]-wedgewidth)*r)
        x4 = (500 + math.cos(indicatorcenterangles[i]-wedgewidth)*c.centerradius)
        y4 = (500 + math.sin(indicatorcenterangles[i]-wedgewidth)*c.centerradius)
        if(c.saliencebycolor):
            s = ((salience[i]+c.includezerosalience)**c.saliencebycolor)/((3.0+c.includezerosalience)**c.saliencebycolor)
        else:
            s = 1
        red,green,blue = colors[i//7]
        d = 'M %s,%s L %s,%s A %s,%s 0 0,0 %s,%s L %s,%s A %s,%s 0 0,1 %s,%s' % (x1,y1,x2,y2,r,r,x3,y3,x4,y4,c.centerradius,c.centerradius,x1,y1)
        if(salience[i]>0 or c.includezerosalience):
            out.add(svg.path(d, fill='rgb(%s,%s,%s)' % (red,green,blue), p='fill-opacity="%s"' % s))
        
            
            
    #draw dividers and text
    for i in range(0,21):
        
        if(c.saliencebywidth and c.drawsaliencedividers):
            x1 = (500 + math.cos(indicatorcenterangles[i])*c.centerradius)
            y1 = (500 + math.sin(indicatorcenterangles[i])*c.centerradius)
            x2 = (500 + math.cos(indicatorcenterangles[i])*c.edgeradius)
            y2 = (500 + math.sin(indicatorcenterangles[i])*c.edgeradius)
            out.add(svg.line(x1, y1, x2, y2, 'black', .5))
            for j in range(1-c.includezerosalience,3):
                if(c.saliencebywidth>1):
                    wedgewidth = wedgeangle/2/(c.saliencebywidth**3)*(c.saliencebywidth**j)
                else:
                    wedgewidth = wedgeangle/2/(3+c.includezerosalience)*(j+c.includezerosalience)
                for k in [1,-1]:
                    x1 = (500 + math.cos(indicatorcenterangles[i]+wedgewidth*k)*c.centerradius)
                    y1 = (500 + math.sin(indicatorcenterangles[i]+wedgewidth*k)*c.centerradius)
                    x2 = (500 + math.cos(indicatorcenterangles[i]+wedgewidth*k)*c.edgeradius)
                    y2 = (500 + math.sin(indicatorcenterangles[i]+wedgewidth*k)*c.edgeradius)
                    out.add(svg.line(x1, y1, x2, y2, 'black', .5))
        
        #invisible link and tooltip box
        x1 = (500 + math.cos(indicatorcenterangles[i]+wedgeangle/2)*c.centerradius)
        y1 = (500 + math.sin(indicatorcenterangles[i]+wedgeangle/2)*c.centerradius)
        x2 = (500 + math.cos(indicatorcenterangles[i]+wedgeangle/2)*c.textradius+25)
        y2 = (500 + math.sin(indicatorcenterangles[i]+wedgeangle/2)*c.textradius+25)
        x3 = (500 + math.cos(indicatorcenterangles[i]-wedgeangle/2)*c.textradius+25)
        y3 = (500 + math.sin(indicatorcenterangles[i]-wedgeangle/2)*c.textradius+25)
        x4 = (500 + math.cos(indicatorcenterangles[i]-wedgeangle/2)*c.centerradius)
        y4 = (500 + math.sin(indicatorcenterangles[i]-wedgeangle/2)*c.centerradius)
        d = 'M %s,%s L %s,%s L %s,%s L %s,%s z' % (x1,y1,x2,y2,x3,y3,x4,y4)
        newpath = svg.path(d, fill='white', p='fill-opacity="0.0"')
        newpath.add(svg.title(' %s: %s\n Magnitude %s\tSalience %s' % (c.indicatornames[i], c.indicatorfullnames[i], magnitude[i], salience[i])))
        out.add(newpath)

        x = (500 + math.cos(indicatorcenterangles[i])*c.textradius)
        y = (500 + math.sin(indicatorcenterangles[i])*c.textradius)
        out.add(svg.text(c.indicatornames[i], x, y, fontsize=c.font, p='style="text-anchor: middle; dominant-baseline: middle"'))
        
        # draw dividers
        x1 = 500 + math.cos(indicatorseparatorangles[i])*c.centerradius
        y1 = 500 + math.sin(indicatorseparatorangles[i])*c.centerradius
        if(i % 7 == 0):
            x2 = 500 + math.cos(indicatorseparatorangles[i])*(c.textradius+25)
            y2 = 500 + math.sin(indicatorseparatorangles[i])*(c.textradius+25)
            out.add(svg.line(x1, y1, x2, y2, 'black', 10))
        elif (c.xgrid or (c.saliencebywidth and c.drawsaliencedividers)):
                x2 = 500 + math.cos(indicatorseparatorangles[i])*(c.textradius)
                y2 = 500 + math.sin(indicatorseparatorangles[i])*(c.textradius)
                out.add(svg.line(x1, y1, x2, y2, 'black', 2))
    
    #draw rings
    for i in range(0,c.maxvalue+c.includezeromagnitude+1):
        if(i==c.includezeromagnitude):
            w=5
            out.add(svg.circle('500','500',ringradii(i),'black',w,'none'))
        elif (c.ygrid or i==0):
            w=1
            out.add(svg.circle('500','500',ringradii(i),'black',w,'none'))

    return out
Ejemplo n.º 12
0
def makesaliencelegend():
    out = svg.svg(width=2000, height=100, viewbox='0 0 2000 100')
    if c.swapsaliencemagnitude:
        te = 'Magnitude:'
    else:
        te = 'Salience:'

    out.add(svg.text(te, 70, 50, fontsize=c.font))
    for i in range(0, 2):
        if i == 0:
            red, green, blue = c.colorsbenefit[0]
        elif c.colorsbenefit[0] == c.colorscost[0]:
            return out
        else:
            red, green, blue = c.colorscost[0]

        for j in range(0, 3 + c.includezerosalience):
            out.add(
                svg.text(j + (1 - c.includezerosalience),
                         (i * 950 + 290 + j *
                          (200 - 60 * c.includezerosalience)),
                         50,
                         fontsize=c.font))
            if (c.saliencebycolor):
                s = ((j + 1)**c.saliencebycolor) / (
                    (3.0 + c.includezerosalience)**c.saliencebycolor)
            else:
                s = 1
            if (c.saliencebywidth):
                out.add(
                    svg.rect((i * 950 + 320 + j *
                              (200 - 60 * c.includezerosalience)),
                             11,
                             80,
                             50,
                             stroke='black',
                             fill='none'))
                if (c.saliencebywidth > 1):
                    w = 80.0 / (c.saliencebywidth**3) * (c.saliencebywidth**(
                        j + 1 - c.includezerosalience))
                else:
                    w = 80.0 / (3 + c.includezerosalience) * (j + 1)
                out.add(
                    svg.rect((i * 950 + 360 + j *
                              (200 - 60 * c.includezerosalience) - (w / 2)),
                             11,
                             w,
                             50,
                             stroke='none',
                             fill='rgb(%s,%s,%s)' % (red, green, blue),
                             p='fill-opacity="%s"' % s))
            else:
                out.add(
                    svg.rect((i * 950 + 320 + j *
                              (200 - 60 * c.includezerosalience)),
                             11,
                             80,
                             50,
                             stroke='none',
                             fill='rgb(%s,%s,%s)' % (red, green, blue),
                             p='fill-opacity="%s"' % s))
    return out
Ejemplo n.º 13
0
def makebarsvert(magnitudebenefit, saliencebenefit, magnitudecost,
                 saliencecost):

    if c.swapsaliencemagnitude:
        tm = saliencebenefit[:]
        saliencebenefit = magnitudebenefit[:]
        magnitudebenefit = tm
        tm = saliencecost[:]
        saliencecost = magnitudecost[:]
        magnitudecost = tm

    #general variables
    t = 0
    if c.centerlabel is not None:
        t = 50
    out = svg.svg(width=1000, height=2250 + t, viewbox='0 0 1000 2150')
    barwidth = 2050 / (21 + c.spacebars * 2)

    chart = svg.g('transform="translate(0 %s)"' % t)
    out.add(chart)

    for cb in range(0, 2):
        if c.centerlabel is not None:
            out.add(
                svg.text(
                    c.centerlabel[1 - cb],
                    250 + (cb) * 500,
                    25,
                    fontsize=c.font,
                    p='style="text-anchor: middle; dominant-baseline: middle"')
            )

        if (cb == 1):
            colors = c.colorsbenefit
            magnitude = magnitudebenefit
            salience = saliencebenefit
        else:
            magnitude = magnitudecost
            salience = saliencecost
            colors = c.colorscost

        #draw bars
        for i in range(0, 21):
            h = barheight(magnitude[i] + c.includezeromagnitude)
            if (c.saliencebywidth == 1):
                w = barwidth / (3 + c.includezerosalience) * (
                    salience[i] + c.includezerosalience)
            elif (c.saliencebywidth > 1):
                w = barwidth / (c.saliencebywidth**3) * (c.saliencebywidth**
                                                         salience[i])
            else:
                w = barwidth
            if (c.saliencebycolor):
                s = ((salience[i] + c.includezerosalience)**
                     c.saliencebycolor) / (
                         (3.0 + c.includezerosalience)**c.saliencebycolor)
            else:
                s = 1
            red, green, blue = colors[i // 7]
            if (salience[i] > 0 or c.includezerosalience):
                barlinecolor = (int(red * c.barlineshade),
                                int(green * c.barlineshade),
                                int(blue * c.barlineshade))
                chart.add(
                    svg.rect(
                        500 + (cb - 1) * h,
                        (i + (i // 7) * c.spacebars) * barwidth +
                        (barwidth - w) / 2,
                        h,
                        w,
                        fill='rgb(%s,%s,%s)' % (red, green, blue),
                        stroke='rgb(%s,%s,%s)' %
                        (barlinecolor[0], barlinecolor[1], barlinecolor[2]),
                        strokewidth=c.barline,
                        p='fill-opacity="%s"' % s))

            #invisible link and tooltip box
            newrect = svg.rect(500 + (cb - 1) * c.textradius,
                               (i + (i // 7) * c.spacebars) * barwidth,
                               c.textradius,
                               barwidth,
                               fill='white',
                               p='fill-opacity="0.0"')
            newrect.add(
                svg.title(' %s: %s\n Magnitude %s\tSalience %s' %
                          (c.indicatornames[i], c.indicatorfullnames[i],
                           magnitude[i], salience[i])))
            chart.add(newrect)

        #draw ygrid
        for i in range(0, c.maxvalue + c.includezeromagnitude + 1):
            if (i == c.includezeromagnitude):
                w = 5
            else:
                w = 1
            if (c.ygrid or i == 0):
                x2 = 0
            else:
                x2 = 2050 - c.ticksize
            chart.add(
                svg.line(500 + barheight(i) * (cb - .5) * 2, 2050 + c.ticksize,
                         500 + barheight(i) * (cb - .5) * 2, x2, 'black', w))

    #draw xgrid dividers
    chart.add(
        svg.line(500 - c.edgeradius, 2050, 500 + c.edgeradius, 2050, 'black',
                 5))
    for i in range(0, 21 + c.spacebars * 2):
        if (c.xgrid or (c.saliencebywidth and c.drawsaliencedividers)):
            chart.add(
                svg.line(500 - c.edgeradius, barwidth * i, 500 + c.edgeradius,
                         barwidth * i, 'black', 1))
        elif (ticksize):
            chart.add(
                svg.line(500 - c.ticksize, barwidth * i, 500 + c.ticksize,
                         barwidth * i, 'black', 1))

    #draw salience dividers and column headings
    for i in range(0, 21):
        if (c.saliencebywidth and c.drawsaliencedividers):
            for j in range(1 - c.includezerosalience, 3):
                if (c.saliencebywidth > 1):
                    w = barwidth / 2 / (c.saliencebywidth**
                                        3) * (c.saliencebywidth**j)
                else:
                    w = barwidth / 2 / (3 + c.includezerosalience) * (
                        j + c.includezerosalience)
                for k in [1, -1]:
                    chart.add(
                        svg.line(500 - c.edgeradius,
                                 barwidth * (i + (i // 7) + .5) + k * w,
                                 500 + c.edgeradius,
                                 barwidth * (i + (i // 7) + .5) + k * w,
                                 'black', .5))

        x = (500 - c.textradius)
        y = ((i + (i // 7) * c.spacebars + .5) * barwidth)
        chart.add(
            svg.text(
                c.indicatornames[i],
                x,
                y,
                fontsize=c.font,
                p='style="text-anchor: middle; dominant-baseline: middle"'))

    #draw magnitude legend
    if c.magnitudelegend:
        if c.swapsaliencemagnitude:
            te = 'Salience'
        else:
            te = 'Magnitude'
        mag = svg.g(p='transform="translate(0 2050)"')
        mag.add(
            svg.text(
                te,
                500,
                100,
                fontsize=c.font,
                p='style="text-anchor: middle; dominant-baseline: middle"'))

        lastnumber = 1
        for i in range(0, c.maxvalue + c.includezeromagnitude + 1):
            if (i - c.includezeromagnitude == 0):
                mag.add(
                    svg.text(
                        i - c.includezeromagnitude,
                        502 - barheight(i),
                        40,
                        fontsize=c.font,
                        p='style="text-anchor: middle; dominant-baseline: middle"'
                    ))
                if (barheight(i) * 2 > c.font):
                    mag.add(
                        svg.text(
                            i - c.includezeromagnitude,
                            502 + barheight(i),
                            40,
                            fontsize=c.font,
                            p='style="text-anchor: middle; dominant-baseline: middle"'
                        ))
            elif (i - c.includezeromagnitude > 0):
                # alternate top and bottom if axis lables too close
                mag.add(
                    svg.text(
                        i - c.includezeromagnitude,
                        502 + barheight(i) * lastnumber,
                        40,
                        fontsize=c.font,
                        p='style="text-anchor: middle; dominant-baseline: middle"'
                    ))
                if (barheight(i) - barheight(i - 1) > c.font):
                    mag.add(
                        svg.text(
                            i - c.includezeromagnitude,
                            502 - barheight(i) * lastnumber,
                            40,
                            fontsize=c.font,
                            p='style="text-anchor: middle; dominant-baseline: middle"'
                        ))
                else:
                    lastnumber = lastnumber * -1
        chart.add(mag)

    return out
Ejemplo n.º 14
0
def makemagnitudelegend():
    angles = [-math.pi / 2, math.pi / 2]
    wedgeangle = math.pi * 2 / 21

    out = svg.svg(width=250, height=1000, viewbox='0 0 250 1000')

    x = (500 + math.cos(angles[0]) * c.textradius)
    y = (500 + math.sin(angles[0]) * c.textradius)
    if c.swapsaliencemagnitude:
        te = 'Salience:'
    else:
        te = 'Magnitude:'
    out.add(
        svg.text(te,
                 125,
                 25,
                 fontsize=c.font,
                 p='style="text-anchor: middle; dominant-baseline: middle"'))

    for angle in angles:

        x1 = (125 + math.cos(angle + wedgeangle / 2) * c.centerradius)
        y1 = (500 + math.sin(angle + wedgeangle / 2) * c.centerradius)
        x2 = (125 + math.cos(angle + wedgeangle / 2) * c.textradius)
        y2 = (500 + math.sin(angle + wedgeangle / 2) * c.textradius)
        x3 = (125 + math.cos(angle - wedgeangle / 2) * c.textradius)
        y3 = (500 + math.sin(angle - wedgeangle / 2) * c.textradius)
        x4 = (125 + math.cos(angle - wedgeangle / 2) * c.centerradius)
        y4 = (500 + math.sin(angle - wedgeangle / 2) * c.centerradius)

        out.add(svg.line(x1, y1, x2, y2, 'black', 2))
        out.add(svg.line(x3, y3, x4, y4, 'black', 2))

        if (c.drawsaliencedividers):
            x1 = (125 + math.cos(angle) * c.centerradius)
            y1 = (500 + math.sin(angle) * c.centerradius)
            x2 = (125 + math.cos(angle) * c.edgeradius)
            y2 = (500 + math.sin(angle) * c.edgeradius)
            out.add(svg.line(x1, y1, x2, y2, 'black', .5))
            for j in range(1 - c.includezerosalience, 3):
                if (c.saliencebywidth > 1):
                    wedgewidth = wedgeangle / 2 / (c.saliencebywidth**
                                                   3) * (c.saliencebywidth**j)
                else:
                    wedgewidth = wedgeangle / 2 / (
                        3 + c.includezerosalience) * (j +
                                                      c.includezerosalience)
                x1 = (125 + math.cos(angle - wedgewidth) * c.centerradius)
                y1 = (500 + math.sin(angle - wedgewidth) * c.centerradius)
                x2 = (125 + math.cos(angle - wedgewidth) * c.edgeradius)
                y2 = (500 + math.sin(angle - wedgewidth) * c.edgeradius)
                out.add(svg.line(x1, y1, x2, y2, 'black', .5))
                x1 = (125 + math.cos(angle + wedgewidth) * c.centerradius)
                y1 = (500 + math.sin(angle + wedgewidth) * c.centerradius)
                x2 = (125 + math.cos(angle + wedgewidth) * c.edgeradius)
                y2 = (500 + math.sin(angle + wedgewidth) * c.edgeradius)
                out.add(svg.line(x1, y1, x2, y2, 'black', .5))

        for i in range(0, c.maxvalue + c.includezeromagnitude + 1):
            if (i == c.includezeromagnitude):
                w = 5
            else:
                w = 1
            r = ringradii(i)
            x1 = (125 + math.cos(angle + wedgeangle / 1.5) * r)
            y1 = (500 + math.sin(angle + wedgeangle / 1.5) * r)
            x2 = (125 + math.cos(angle - wedgeangle / 1.5) * r)
            y2 = (500 + math.sin(angle - wedgeangle / 1.5) * r)
            d = 'M %s,%s A %s,%s 0 0,0 %s,%s' % (x1, y1, r, r, x2, y2)
            out.add(svg.path(d, stroke='black', strokewidth=w))

            y = y1
            if (i % 2 == 0):
                x = x2 + 10 * angle
            else:
                x = x1 - 10 * angle
            if (i - c.includezeromagnitude >= 0):
                out.add(
                    svg.text(
                        i - c.includezeromagnitude,
                        x,
                        y,
                        fontsize=c.font,
                        p='style="text-anchor: middle; dominant-baseline: middle"'
                    ))

    return out
Ejemplo n.º 15
0
def makecircle(magnitude, salience, benefit=1):
    if c.swapsaliencemagnitude:
        tm = salience[:]
        salience = magnitude[:]
        magnitude = tm

    #general variables
    indicatorseparatorangles = [
        -math.pi * 2 / 21 * i + math.pi / 21 for i in range(0, 22)
    ]
    indicatorcenterangles = [-math.pi * 2 / 21 * i for i in range(0, 21)]
    wedgeangle = math.pi * 2 / 21

    out = svg.svg(width=1000,
                  height=1000 + 100 * c.saliencelegend,
                  viewbox='0 0 1000 1%d00' % (1 * c.saliencelegend == True))

    if (benefit):
        colors = c.colorsbenefit
    else:
        colors = c.colorscost
    if c.centerlabel is not None:
        out.add(
            svg.text(
                c.centerlabel[1 - benefit],
                500,
                500,
                fontsize=c.font,
                p='style="text-anchor: middle; dominant-baseline: middle"'))

    #draw wedges
    for i in range(0, 21):
        r = ringradii(magnitude[i] + c.includezeromagnitude)
        if (c.saliencebywidth == 1):
            wedgewidth = wedgeangle / 2 / (3 + c.includezerosalience) * (
                salience[i] + c.includezerosalience)
        elif (c.saliencebywidth > 1):
            wedgewidth = wedgeangle / 2 / (saliencebywidth**3) * (
                c.saliencebywidth**salience[i])
        else:
            wedgewidth = wedgeangle / 2
        x1 = (500 +
              math.cos(indicatorcenterangles[i] + wedgewidth) * c.centerradius)
        y1 = (500 +
              math.sin(indicatorcenterangles[i] + wedgewidth) * c.centerradius)
        x2 = (500 + math.cos(indicatorcenterangles[i] + wedgewidth) * r)
        y2 = (500 + math.sin(indicatorcenterangles[i] + wedgewidth) * r)
        x3 = (500 + math.cos(indicatorcenterangles[i] - wedgewidth) * r)
        y3 = (500 + math.sin(indicatorcenterangles[i] - wedgewidth) * r)
        x4 = (500 +
              math.cos(indicatorcenterangles[i] - wedgewidth) * c.centerradius)
        y4 = (500 +
              math.sin(indicatorcenterangles[i] - wedgewidth) * c.centerradius)
        if (c.saliencebycolor):
            s = ((salience[i] + c.includezerosalience)**c.saliencebycolor) / (
                (3.0 + c.includezerosalience)**c.saliencebycolor)
        else:
            s = 1
        red, green, blue = colors[i // 7]
        d = 'M %s,%s L %s,%s A %s,%s 0 0,0 %s,%s L %s,%s A %s,%s 0 0,1 %s,%s' % (
            x1, y1, x2, y2, r, r, x3, y3, x4, y4, c.centerradius,
            c.centerradius, x1, y1)
        if (salience[i] > 0 or c.includezerosalience):
            out.add(
                svg.path(d,
                         fill='rgb(%s,%s,%s)' % (red, green, blue),
                         p='fill-opacity="%s"' % s))

    #draw dividers and text
    for i in range(0, 21):

        if (c.saliencebywidth and c.drawsaliencedividers):
            x1 = (500 + math.cos(indicatorcenterangles[i]) * c.centerradius)
            y1 = (500 + math.sin(indicatorcenterangles[i]) * c.centerradius)
            x2 = (500 + math.cos(indicatorcenterangles[i]) * c.edgeradius)
            y2 = (500 + math.sin(indicatorcenterangles[i]) * c.edgeradius)
            out.add(svg.line(x1, y1, x2, y2, 'black', .5))
            for j in range(1 - c.includezerosalience, 3):
                if (c.saliencebywidth > 1):
                    wedgewidth = wedgeangle / 2 / (c.saliencebywidth**
                                                   3) * (c.saliencebywidth**j)
                else:
                    wedgewidth = wedgeangle / 2 / (
                        3 + c.includezerosalience) * (j +
                                                      c.includezerosalience)
                for k in [1, -1]:
                    x1 = (500 +
                          math.cos(indicatorcenterangles[i] + wedgewidth * k) *
                          c.centerradius)
                    y1 = (500 +
                          math.sin(indicatorcenterangles[i] + wedgewidth * k) *
                          c.centerradius)
                    x2 = (500 +
                          math.cos(indicatorcenterangles[i] + wedgewidth * k) *
                          c.edgeradius)
                    y2 = (500 +
                          math.sin(indicatorcenterangles[i] + wedgewidth * k) *
                          c.edgeradius)
                    out.add(svg.line(x1, y1, x2, y2, 'black', .5))

        #invisible link and tooltip box
        x1 = (500 + math.cos(indicatorcenterangles[i] + wedgeangle / 2) *
              c.centerradius)
        y1 = (500 + math.sin(indicatorcenterangles[i] + wedgeangle / 2) *
              c.centerradius)
        x2 = (500 + math.cos(indicatorcenterangles[i] + wedgeangle / 2) *
              c.textradius + 25)
        y2 = (500 + math.sin(indicatorcenterangles[i] + wedgeangle / 2) *
              c.textradius + 25)
        x3 = (500 + math.cos(indicatorcenterangles[i] - wedgeangle / 2) *
              c.textradius + 25)
        y3 = (500 + math.sin(indicatorcenterangles[i] - wedgeangle / 2) *
              c.textradius + 25)
        x4 = (500 + math.cos(indicatorcenterangles[i] - wedgeangle / 2) *
              c.centerradius)
        y4 = (500 + math.sin(indicatorcenterangles[i] - wedgeangle / 2) *
              c.centerradius)
        d = 'M %s,%s L %s,%s L %s,%s L %s,%s z' % (x1, y1, x2, y2, x3, y3, x4,
                                                   y4)
        newpath = svg.path(d, fill='white', p='fill-opacity="0.0"')
        newpath.add(
            svg.title(' %s: %s\n Magnitude %s\tSalience %s' %
                      (c.indicatornames[i], c.indicatorfullnames[i],
                       magnitude[i], salience[i])))
        out.add(newpath)

        x = (500 + math.cos(indicatorcenterangles[i]) * c.textradius)
        y = (500 + math.sin(indicatorcenterangles[i]) * c.textradius)
        out.add(
            svg.text(
                c.indicatornames[i],
                x,
                y,
                fontsize=c.font,
                p='style="text-anchor: middle; dominant-baseline: middle"'))

        # draw dividers
        x1 = 500 + math.cos(indicatorseparatorangles[i]) * c.centerradius
        y1 = 500 + math.sin(indicatorseparatorangles[i]) * c.centerradius
        if (i % 7 == 0):
            x2 = 500 + math.cos(
                indicatorseparatorangles[i]) * (c.textradius + 25)
            y2 = 500 + math.sin(
                indicatorseparatorangles[i]) * (c.textradius + 25)
            out.add(svg.line(x1, y1, x2, y2, 'black', 10))
        elif (c.xgrid or (c.saliencebywidth and c.drawsaliencedividers)):
            x2 = 500 + math.cos(indicatorseparatorangles[i]) * (c.textradius)
            y2 = 500 + math.sin(indicatorseparatorangles[i]) * (c.textradius)
            out.add(svg.line(x1, y1, x2, y2, 'black', 2))

    #draw rings
    for i in range(0, c.maxvalue + c.includezeromagnitude + 1):
        if (i == c.includezeromagnitude):
            w = 5
            out.add(svg.circle('500', '500', ringradii(i), 'black', w, 'none'))
        elif (c.ygrid or i == 0):
            w = 1
            out.add(svg.circle('500', '500', ringradii(i), 'black', w, 'none'))

    return out
Ejemplo n.º 16
0
def plot(ratios, 
    range_x     = (0, 2),
    major       = 1.0, 
    minor       = 5,
    title       = None,
    subtitle    = None, 
    colors      = {}):    
    
    display     = 800, 680
    margin_x    = 60, 60
    margin_y    =  20,  80 + 10 * (subtitle is not None) + 20 * (title is not None)
    
    area        = display[0] - sum(margin_x), sum(margin_y) - display[1]
    offset      = margin_x[0], display[1] - margin_y[0]
    
    # draw grid lines
    start, end  = range_x
    # epsilon to deal with rounding errors
    cells       = int((end - start) / major * minor + 1e-5)
    
    grid_minor  = []
    grid_major  = []
    ticks       = []
    labels      = []
    for i in range(cells + 1):
        x      = i * major / (minor * (end - start))
        v      = i * major /  minor
        m      = i % minor == 0
        
        screen = tuple(tuple(map(round, transform(x, area, offset))) for x in ((x, 0), (x, 1)))
        length = 12 if m else 6
        (grid_major if m else grid_minor).append(  
            svg.path(  (transform(screen[0], (1, 1), (0.5,  0)), 
                        transform(screen[1], (1, 1), (0.5, -1))), 
            classes = ('grid', 'grid-major' if m else 'grid-minor')))
        ticks.append( 
            svg.path(  (transform(screen[1], (1, 1), (0.5, -8)), 
                        transform(screen[1], (1, 1), (0.5, -8 - length))), 
            classes = ('tick',)))
        
        if m:
            labels.append(svg.text(str(round(v, 3)), 
                position    = transform(screen[1], (1, 1), (0, -16 - length)), 
                classes     = ('label-numeric', 'label-x') + (('unity',) if v == 1 else ())))
    # title and subtitle
    if type(title) is str:
        screen = tuple(map(round, transform((0.5, 1), area, offset)))
        labels.append(svg.text(title, 
            position    = transform(screen, (1, 1), (0, -70)), 
            classes     = ('title',)))
    if type(subtitle) is str:
        screen = tuple(map(round, transform((0.5, 1), area, offset)))
        labels.append(svg.text(subtitle, 
            position    = transform(screen, (1, 1), (0, -50)), 
            classes     = ('subtitle',)))
    
    # plot data 
    rows    = tuple((name, ratio, (
            margin_x[0] + area[0] * (ratio - range_x[0]) / (range_x[1] - range_x[0]),
            margin_y[1] + (i + 0.5) * 20))
        for i, (name, ratio) in enumerate(sorted(ratios.items(), key = lambda k: k[1])))
    # pixel coordinate of the y axis
    zero    = margin_x[0] + area[0] * (1.0 - range_x[0]) / (range_x[1] - range_x[0])
    
    legend      = tuple(svg.text(name, 
        (zero + 16 * (1 if ratio <= 1 else -1), screen[1]), 
        classes = ('label-legend', 'better' if ratio <= 1 else 'worse'))
        for name, ratio, screen in rows)
    percents    = tuple(svg.text('{:+.2f} %'.format((ratio - 1) * 100), 
        (screen[0] - 16 * (1 if ratio <= 1 else -1), screen[1]), 
        classes = ('label-percent', 'better' if ratio <= 1 else 'worse'))
        for name, ratio, screen in rows)
    
    stems       = tuple(svg.path((
            (zero,                                      screen[1]), 
            (screen[0] + 4 * (1 if ratio <= 1 else -1), screen[1])), 
        classes = ('stem', 'better' if ratio <= 1 else 'worse'))
        for name, ratio, screen in rows 
        if abs(screen[0] - zero) > 4)
    dots        = tuple(svg.circle(screen, radius = 4, 
        classes = ('dot', 'better' if ratio <= 1 else 'worse'))
        for name, ratio, screen in rows)
    
    style = '''
    rect.background 
    {
        fill:   white;
    }
    
    path.grid 
    {
        stroke-width: 1px;
        fill:   none;
    }
    path.grid-major 
    {
        stroke: #eeeeeeff;
    }
    path.grid-minor 
    {
        stroke: #f5f5f5ff;
    }
    
    path.tick 
    {
        stroke-width: 1px;
        stroke: #333333ff;
        fill:   none;
    }
    
    path.stem 
    {
        stroke-width: 1px;
        stroke-dasharray: 3 3;
    }
    circle.dot 
    {
        stroke-width: 2px;
        stroke: #666;
        fill:   none;
    }
    
    text
    {
        fill: #333333ff;
        font-family: 'SF Mono';
    }
    text.label-numeric 
    {
        font-size: 12px;
    }
    text.label-numeric.unity 
    {
        font-weight: 700;
    }
    text.label-x 
    {
        text-anchor: middle; 
        dominant-baseline: text-top;
    }
    
    text.label-legend, text.label-percent
    {
        font-size: 12px;
        dominant-baseline: middle;
    }
    text.label-percent 
    {
        font-weight: 700;
    }
    text.label-legend.better, text.label-percent.worse 
    {
        text-anchor: begin; 
    }
    text.label-legend.worse, text.label-percent.better 
    {
        text-anchor: end; 
    }
    
    text.title, text.subtitle 
    {
        text-anchor: middle; 
    }
    text.title 
    {
        font-size: 20px;
    }
    text.subtitle 
    {
        font-size: 12px;
    }
    ''' + '''
    circle.better, path.stem.better
    {{
        stroke: {color_fill_better}
    }}
    circle.worse, path.stem.worse
    {{
        stroke: {color_fill_worse}
    }}
    text.label-percent.better 
    {{
        fill: {color_better}
    }}
    text.label-percent.worse 
    {{
        fill: {color_worse}
    }}
    '''.format( ** colors )
    
    return svg.svg(display, style, 
        tuple(grid_minor + grid_major + ticks + labels) + legend + percents + stems + dots)