Esempio n. 1
0
def main(args):
    roomsize_message_count = Counter()
    def accum(dct):
        roomsize_message_count[int(dct['num_recipients'])] += 1
    ReadCSVFile(args.file, accum)
    
    if args.max_roomsize:
        sizes = [args.max_roomsize]
    else:
        sizes = sorted(roomsize_message_count.keys())

    points = []
    for size in sizes:
        points.append((size, 
                         (args.price_per_xmpp * 
                          calculate_messages(roomsize_message_count, 
                                            size, args.ignore_large_rooms)
                          )
                         ) )

    if args.csv:
        for p in points:
            print '%s,%s' % p
    else:
        x = [q[0] for q in points]
        y = [q[1] for q in points]
        from pygooglechart import XYLineChart, Axis
        chart = XYLineChart(400, 400)
        chart.add_data(x)
        chart.add_data(y)
#        chart.set_axis_labels(Axis.BOTTOM, 'max users/channel')
#        chart.set_axis_labels(Axis.LEFT, 'approx cost / week')
        print chart.get_url()+'&chxt=x,y'
        
    return 0
Esempio n. 2
0
def make_chart(request):
    chart = XYLineChart(640, 400)
    chart.set_colours(['FF0000', '00FF00', '0000FF'])

    # add a few attributes to build the legend incrementally
    chart.devices = []
    chart._ranges = []

    return chart
Esempio n. 3
0
def graph_evolution(gens, best_per_gen):

    chart = XYLineChart(500, 500, x_range=(0, max(gens)), y_range=(0, max(best_per_gen)))

    chart.add_data(gens)
    chart.add_data(best_per_gen)

    chart.set_colours(['0000FF'])

    # x axis labels are generation numbers
    chart.set_axis_labels(Axis.BOTTOM, gens)

    webbrowser.open(chart.get_url())
Esempio n. 4
0
def chart(ui, repo, *pats, **opts):
    '''Create graphs of revision data

    This command will graph count of changed lines or revisions grouped by date.

    Statistics are based on the number of changed lines, or
    alternatively the number of matching revisions if the
    --changesets option is specified.

    Examples::

      # create chart of changed lines for every day
      hg chart

      # create chart of changesets for every day
      hg chart -f '%H' -c '''

    width = opts.get('width')
    height = opts.get('height')
    if width * height > 300000:
        raise util.Abort(_('area must be less than 300,000'))

    rate = countrate(ui, repo, *pats, **opts).items()
    if not rate:
        raise util.Abort(_('no matching revisions found'))

    if len(rate) == 1:
        raise util.Abort(_('only one data point found'))

    pairs = [(k,v) for k,v in rate]
    pairs.sort(lambda x, y: x[0] - y[0])

    if len(pairs) > width:
        combine = int(math.ceil(float(len(pairs)) / width))
        newpairs = []
        while pairs:
            newpairs.append((pairs[0][0], reduce(lambda x,y: x + y[1], pairs[0:combine], 0)))
            del pairs[0:combine]
        pairs = newpairs

    keys = [x[0] for x in pairs]
    vals = [x[1] for x in pairs]
    ymax = max(vals)
    chart = XYLineChart(width, height, x_range=(keys[0],
                        keys[-1]), y_range=(0, ymax))
    if not opts.get('nolabels'):
        chart.set_axis_range(Axis.LEFT, 0, ymax)
        chart.set_axis_labels(Axis.BOTTOM,
            map(lambda x: datetime.datetime(*time.gmtime(x)[:6]).strftime('%x'),
                range(keys[0], keys[-1]+1,
                    (keys[-1] - keys[0])/max(1,int(width/100)))))
    chart.add_data(keys)
    chart.add_data(vals)
    print chart.get_url()
    def graph(self):
        """ graph the building as a polygon using google charts
        """
        chart = XYLineChart(200, 200, x_range=(0, 200), y_range=(0, 200))

        xdata = []
        ydata = []

        for n in self.verticies:
            x,y = n
            xdata.append(x)
            ydata.append(y)
        chart.add_data(xdata)
        chart.add_data(ydata)
        webbrowser.open(chart.get_url())
Esempio n. 6
0
    def graph(self):     

        to = copy.deepcopy(self.tour_order)

        # add 1st city at the end for graphing purposes
        to.append(to[0])

        chart = XYLineChart(MAP_SIZE, MAP_SIZE, 
                            x_range=(0, MAP_SIZE), y_range=(0, MAP_SIZE))
        xcoords = [c.getx() for c in to]
        ycoords = [c.gety() for c in to]
        chart.add_data(xcoords)
        chart.add_data(ycoords)

        webbrowser.open(chart.get_url())
Esempio n. 7
0
def main(args):
    roomsize_message_count = Counter()

    def accum(dct):
        roomsize_message_count[int(dct['num_recipients'])] += 1

    ReadCSVFile(args.file, accum)

    if args.max_roomsize:
        sizes = [args.max_roomsize]
    else:
        sizes = sorted(roomsize_message_count.keys())

    points = []
    for size in sizes:
        points.append((size, (args.price_per_xmpp * calculate_messages(
            roomsize_message_count, size, args.ignore_large_rooms))))

    if args.csv:
        for p in points:
            print '%s,%s' % p
    else:
        x = [q[0] for q in points]
        y = [q[1] for q in points]
        from pygooglechart import XYLineChart, Axis
        chart = XYLineChart(400, 400)
        chart.add_data(x)
        chart.add_data(y)
        #        chart.set_axis_labels(Axis.BOTTOM, 'max users/channel')
        #        chart.set_axis_labels(Axis.LEFT, 'approx cost / week')
        print chart.get_url() + '&chxt=x,y'

    return 0
Esempio n. 8
0
def xy_rect():
    chart = XYLineChart(settings.width,
                        settings.height,
                        x_range=(0, 100),
                        y_range=(0, 100))
    chart.add_data([10, 90, 90, 10, 10])
    chart.add_data([10, 10, 90, 90, 10])
    chart.download('line-xy-rect.png')
Esempio n. 9
0
def xy_random():
    chart = XYLineChart(settings.width,
                        settings.height,
                        x_range=(0, 100),
                        y_range=(0, 100))
    chart.add_data(helper.random_data())
    chart.add_data(helper.random_data())
    chart.download('line-xy-random.png')
Esempio n. 10
0
def novidomejni_grafik():
    """По датум последните 30 дена колку нови домејни имало."""

    c1 = conn.cursor()
    c1.execute("select datum, novidomejni from novidomejni order by datum desc limit 30")

    novi = [x for x in c1]
    novi.sort()

    datumi = [x[0] for x in novi]
    ipsilonoska = [int(x[1]) for x in novi] # kolku novi
    iksoska = [x for x in range(0,len(datumi))]

    xmax = len(iksoska)
    ymax = max([int(a[1]) for a in novi])

    chart = XYLineChart(800,300,x_range=(0,xmax-1),y_range=(0,ymax))

    chart.add_data(iksoska)
    chart.add_data(ipsilonoska)

    for x in range(0,len(datumi)):
        if x%2:
            datumi[x]=''

    ipsilon = [ x for x in range(0,ymax+1)]
    for y in range(0,ymax+1):
        if y%2:
            ipsilon[y]=''
    ipsilon[0]=''
    ipsilon[-1]=ymax

    chart.set_axis_labels(Axis.BOTTOM,datumi)
    chart.set_axis_labels(Axis.LEFT, ipsilon)
    chart.set_title("Број на нови .mk домени по денови|")

    return chart.get_url()
def grafico(fileName,datax,datay):
    """Graphical generate"""
    
    droid.dialogCreateAlert("Gerando Grafico","Aguarde a geracao do gráfico")
    droid.dialogShow()
    
    
    
    if(len(datax) != 0):
        xmax, xmin = MaxMindado(datax)
        ymax, ymin = MaxMindado(datay)
        
        if(xmax != xmin):
            deltax = (xmax -xmin)/10.0
        else:
            droid.makeToast("Erro: falta definir eixo x")
            return
        if(ymax != ymin):
            deltay = (ymax - ymin)/10.0
        else:
            droid.makeToast("Erro: Falta definir dados de y")
            return
            
        left_axis = [datax[0] + deltax*i for i in range(11)]
        bottom_axis = [datay[0] + deltay*i for i in range(11)]
    chart = XYLineChart(500, 400,
                       x_range=(xmin,xmax),
                       y_range=(ymin,ymax))
    chart.add_data(datax)
    chart.add_data(datay)
        
    chart.set_axis_labels(Axis.LEFT,[ymin,ymax])
    chart.set_axis_labels(Axis.BOTTOM,[xmin,xmax])
    chart.download('/mnt/sdcard/graphicospeech/'+fileName)  
    droid.fullSetProperty("image1","src",\
                           "file:///mnt/sdcard/graphicospeech/"+fileName)
    
    droid.dialogDismiss()
def altitude_profile_gchart(db, route):
    # First calculate the altitude profile
    profile = altitude_profile(db, route)
    
    # Create gchart
    # http://code.google.com/apis/chart/#line_charts
    # http://pygooglechart.slowchop.com/

    # For the horizontal scale, we need to know the horizontal distance 
    # between the coordinates. First point will have coordinate 0, last 
    # point the sum of all distances.
    
    # y coordinates are the altitudes.
    
    x_coordinates = [0]
    y_coordinates = []  

    for i in range(len(profile)-1):
      x_coordinates.append(x_coordinates[i])

      x_coordinates[i+1] += distance.distance(
        (profile[i]['lat'],profile[i]['lon'] ),
        (profile[i+1]['lat'],profile[i+1]['lon'] )
      ).kilometers
 
      y_coordinates.append(profile[i]['alt'])

    y_coordinates.append(profile[-1]['alt'])

    # Create gchart
    # http://code.google.com/apis/chart/#line_charts
    # http://pygooglechart.slowchop.com/
    chart = XYLineChart(325, 200, 
                        x_range=(0,max(x_coordinates)), y_range=(min(y_coordinates),max(y_coordinates)))
    chart.add_data(x_coordinates)
    chart.add_data(y_coordinates)
    
    chart.set_axis_labels(Axis.BOTTOM, ['0', str(max(x_coordinates))[0:4] + " km"])
    chart.set_axis_labels(Axis.LEFT, [str(int(min(y_coordinates))) + " m", str(int(max(y_coordinates))) + " m"])

    # Return gchart url:
    return chart.get_url()
Esempio n. 13
0
def xy_circle():
    chart = XYLineChart(settings.width, settings.height)
    steps = 40
    xradius = 25
    yradius = 45
    xmid = 50
    ymid = 50
    xlist = []
    ylist = []
    for angle in xrange(0, steps + 1):
        angle = float(angle) / steps * math.pi * 2
        xlist.append(math.cos(angle) * xradius + xmid)
        ylist.append(math.sin(angle) * yradius + ymid)
    chart.add_data(xlist)
    chart.add_data(ylist)
    chart.download('line-xy-circle.png')
Esempio n. 14
0
def genChart(width, height, data, ind, outfile, title):
    # this is designed to take a list, the value of the wshed, and save the output graph
    mn = min(data)
    mx = max(data)
    chart = XYLineChart(width, height, title=title, x_range=(0, len(data)), y_range=(0, mx))
    chart.set_colours(["3072F3", "FF0000"])
    chart.set_line_style(0, 3)
    chart.set_grid(20, 25, 1, 5)
    # set up axis and labels
    left_axis = chart.set_axis_labels(Axis.LEFT, ["            Lowest", "Total Toxicity    ", "            Highest"])
    chart.set_axis_style(left_axis, "202020", font_size=11, alignment=0)
    # add x and y data for distribution line
    chart.add_data(range(len(data)))
    chart.add_data(data)

    # add marker to position of ind
    chart.add_marker(0, ind, "d", "FF0000", 10)

    chart.download(outfile)
    return outfile
 def __init__(self):
     self.chart = XYLineChart(750, 400)
class Graph():
    
    colours = []
    legend = []
    max_wx = 0
    max_wy = 0
    min_wy = 4000000000
    
    label_suffix = " MB"
    scale = 1024*1024

    def __init__(self):
        self.chart = XYLineChart(750, 400)
        
    
    def set_config(self, config):
        self.label_suffix = config.get("general", "label_suffix")
        self.scale = int(config.get("general", "scale"))

    def add_serie(self, WX, WY, colour, descr):
        self.chart.add_data(WX)
        self.chart.add_data(WY)
        self.colours.append(colour)
        self.legend.append(descr)
        
        self.max_wx = max(self.max_wx, max(WX))
        self.max_wy = max(self.max_wy, max(WY))
        self.min_wy = min(self.min_wy, min(WY))
        
    def set_title(self, title):
        self.chart.set_title(title)
        
    def make_chart(self, name):
        densX = self.max_wx / 15
        
        wy_max_lab = int(self.max_wy / self.scale + 1)
        wy_min_lab = int(max(self.min_wy / self.scale - 1, 0))
        densY = max((wy_max_lab - wy_min_lab) / 10, 1) 
        self.chart.set_axis_labels(Axis.BOTTOM, range(0, self.max_wx + 1, densX))
        self.chart.set_axis_labels(Axis.LEFT, self.__make_Ylabels(wy_min_lab, wy_max_lab, int(densY)))
        self.chart.y_range = (wy_min_lab * self.scale, wy_max_lab * self.scale)
        
        self.chart.set_legend(self.legend)
        self.chart.set_colours(self.colours)
        self.chart.set_grid(15, 10, 1, 5)
        
        self.chart.download("%s.png" % (name))
        
    def __make_Ylabels(self, wy_min_lab, wy_max_lab, densY):
        result = []
        for i in range(wy_min_lab, wy_max_lab, densY):
            result.append("%d%s" % (i, self.label_suffix))
        return result
d = start
pos = 0
step = timedelta(days=1)
while d != end:
    if d in deadlines:
        deadlines[d] = pos
    d += step
    pos += 1
    if d not in data:
        data[d] = 0
rows = sorted(data.items())

title = str(sum(data.values())) + ' partecipanti al PyCon Tre - ' + start.strftime('%d %b %Y') + ' / ' + end.strftime('%d %b %Y')
chart = XYLineChart(
    width = 1000, height = 300,
    title = title, y_range = [0, 420]
)
x_values = range(len(rows))

chart.add_data(x_values)
row = []
total = 0
for d, count in rows:
    total += count
    row.append(total)
chart.add_data(row)

chart.add_data(x_values)
chart.add_data([ x[1] for x in rows ])

chart.add_data(x_values)
Esempio n. 18
0
d = start
pos = 0
step = timedelta(days=1)
while d != end:
    if d in deadlines:
        deadlines[d] = pos
    d += step
    pos += 1
    if d not in data:
        data[d] = 0
rows = sorted(data.items())

title = str(sum(
    data.values())) + ' partecipanti al PyCon Tre - ' + start.strftime(
        '%d %b %Y') + ' / ' + end.strftime('%d %b %Y')
chart = XYLineChart(width=1000, height=300, title=title, y_range=[0, 420])
x_values = range(len(rows))

chart.add_data(x_values)
row = []
total = 0
for d, count in rows:
    total += count
    row.append(total)
chart.add_data(row)

chart.add_data(x_values)
chart.add_data([x[1] for x in rows])

chart.add_data(x_values)
chart.add_data([0] * len(x_values))
Esempio n. 19
0
def xy_random():
    chart = XYLineChart(settings.width, settings.height,
                        x_range=(0, 100), y_range=(0, 100))
    chart.add_data(helper.random_data())
    chart.add_data(helper.random_data())
    chart.download('line-xy-random.png')
Esempio n. 20
0
def main():

    parseLive()

    stats = {}
    time_stats = {}

    fp = open("genetics.log", "r")
    lines = fp.readlines()
    header = [h.strip() for h in lines[0].split(",")]
    for line in lines[1:]:
        data = line.split(",")
        type = data[0].strip()
        generation = int(data[1])
        time = int(float(data[2]) / 10) * 10

        if type not in stats:
            stats[type] = {}
            time_stats[type] = {}
        if generation not in stats[type]:
            stats[type][generation] = {}
        if time not in time_stats[type]:
            time_stats[type][time] = {}

        d = stats[type][generation]
        t = time_stats[type][time]

        for phene, value in zip(header[3:], data[3:]):
            if phene not in d:
                d[phene] = []
            d[phene].append(float(value))
            if phene not in t:
                t[phene] = []
            t[phene].append(float(value))

    for s, name in [(stats, "generation"), (time_stats, "time")]:

        for feature in Phenotype.VALID:

            chart = XYLineChart(400, 300)

            max_wx = 0
            for creature in ['rabbit', 'wolf']:
                WX = []
                WYavg = []
                WYmin = []
                WYmax = []
                for g, phenes in sorted(s[creature].items()):
                    WX.append(g)
                    WYavg.append(sum(phenes[feature]) / len(phenes[feature]))
                    WYmin.append(min(phenes[feature]))
                    WYmax.append(max(phenes[feature]))

                if len(WX) < 2:
                    WX.append(2)

                chart.add_data(WX)
                chart.add_data(WYmin)
                chart.add_data(WX)
                chart.add_data(WYmax)
                chart.add_data(WX)
                chart.add_data(WYavg)



                max_wx = max(max_wx, max(WX))

            chart.set_title("Phenotype: %s / %s" % (feature, name))
            chart.set_colours(['ffe9bf', 'daffbf', 'ff0000', 'ebbfff', 'bffff5', '0000ff'])
            chart.set_legend(['rabbits-min', 'rabbits-max', 'rabbits-avg', 'wolves-min', 'wolves-max', 'wolves-avg'])
            chart.set_grid(0, 10, 3, 3)

            if name == "generation":
                chart.set_axis_labels(Axis.BOTTOM, range(0, max_wx + 1, 5))
            else:
                chart.set_axis_labels(Axis.BOTTOM, range(0, max_wx + 1, 100))
            chart.download("%s-%s.png" % (name, feature))
Esempio n. 21
0
def animalNum(stats):

    chart = XYLineChart(400, 300)

    max_wx = 0
    for creature in ['rabbit', 'wolf']:
        WX = []
        WY = []
        count = 0
        for t in sorted(stats[creature].keys()):
            WX.append(t)
            for event in stats[creature][t]['event']:
                if event == LiveLog.BIRTH:
                    count += 1
                else:
                    count -= 1
          #  print count, creature, str(stats[creature][t]['event'])
            WY.append(count)

        chart.add_data(WX)
        chart.add_data(WY)
        max_wx = max(max_wx, max(WX))

    chart.set_title("Population size")
    chart.set_colours(['ff0000', '0000ff'])
    chart.set_legend(['rabbits', 'wolves'])
    chart.set_grid(0, 10, 3, 3)

    chart.set_axis_labels(Axis.BOTTOM, range(0, max_wx + 1, 100))
    chart.download('number.png')
Esempio n. 22
0
def _make_chart(width=600, height=200, **chart_kwargs):
    chart = XYLineChart(width, height, **chart_kwargs)
    chart.set_colours(CHART_COLORS)
    return chart
Esempio n. 23
0
def xy_random():
    chart = XYLineChart(width, height, x_range=(0, 100), y_range=(0, 100))
    chart.add_data(random_data())
    chart.add_data(random_data())
    chart.download('line-xy-random.png')
Esempio n. 24
0
def make_graph(x_axis, data, color_vertically=True):
	x_axis = x_axis[:]
	data = data[:]

	max_y_value = 24500000
	max_y = 24500000
	min_time = min(x_axis)
	max_time = max(x_axis)

	chart = XYLineChart(700, 400, x_range=[min_time, max_time], y_range=[0, max_y_value])

	chart.set_axis_labels(Axis.LEFT, ['', max_y_value])

	start_time = datetime.fromtimestamp(min(x_axis)).strftime("%H:%M")
	end_time = datetime.fromtimestamp(max(x_axis)).strftime("%H:%M")
	chart.set_axis_labels(Axis.BOTTOM, [start_time, end_time])

	# First value is the highest Y value. Two of them are needed to be
	# plottable.
	chart.add_data([min_time, max_time])
	chart.add_data([max_y] * 2)

	#print max_y, min_time, max_time
	prev_y = [0] * 2
	for bar in data[::-1]:
		Y = bar
		if not Y:
			Y = prev_y
		#print "X", idx, X
		#print "Y", idx, Y
		chart.add_data(x_axis)
		chart.add_data(Y)
		prev_y = Y

	chart.add_data([min_time, max_time])
	chart.add_data([0] * 2)

	# Black lines
	chart.set_colours(['000000'] * 5)

	color_chart_vertically(chart, data)

	print chart.get_url()
	return chart
Esempio n. 25
0
def make_graph(x_axis, data, color_vertically=True):
    x_axis = x_axis[:]
    data = data[:]

    max_y_value = 24500000
    max_y = 24500000
    min_time = min(x_axis)
    max_time = max(x_axis)

    chart = XYLineChart(700,
                        400,
                        x_range=[min_time, max_time],
                        y_range=[0, max_y_value])

    chart.set_axis_labels(Axis.LEFT, ['', max_y_value])

    start_time = datetime.fromtimestamp(min(x_axis)).strftime("%H:%M")
    end_time = datetime.fromtimestamp(max(x_axis)).strftime("%H:%M")
    chart.set_axis_labels(Axis.BOTTOM, [start_time, end_time])

    # First value is the highest Y value. Two of them are needed to be
    # plottable.
    chart.add_data([min_time, max_time])
    chart.add_data([max_y] * 2)

    #print max_y, min_time, max_time
    prev_y = [0] * 2
    for bar in data[::-1]:
        Y = bar
        if not Y:
            Y = prev_y
        #print "X", idx, X
        #print "Y", idx, Y
        chart.add_data(x_axis)
        chart.add_data(Y)
        prev_y = Y

    chart.add_data([min_time, max_time])
    chart.add_data([0] * 2)

    # Black lines
    chart.set_colours(['000000'] * 5)

    color_chart_vertically(chart, data)

    print chart.get_url()
    return chart
Esempio n. 26
0
 def __init__(self,data,imagefileurl,name,label,title,nbpts=None,ptindexlist=None,timerange=False,timestart=None,type='ggl',labelx='',labely=None,unitx='',unity=''):
     Log('MyXYChart: begin %s\n' % label)
     self.charttype='line'
     self.imagefileurl = imagefileurl
     self.name = name
     self.label = label
     self.title = title
     self.type = type
     # Simple chart or XY chart ?
     if len(data)==2 and len(data[0])>1:
         datax = data[0]
         datay = data[1]
     else:
         #print('DEBUG: simple chart')
         datay = data
     # Compute min and max Y values
     (min_y,max_y,scaling_y) = ExtendRange(min(datay),max(datay))
     if max_y-min_y==0:
         max_y = min_y + 1.0
         scaling_y = 0.2
     
     if type in ('dyg','json'):
         self.marginsize = 0
         self.pt2px = None
         self.data = list(data)
         self.timerange = timerange
         self.labelx = labelx
         self.unitx = unitx
         self.unity = unity
         if labely==None:
             self.labely = label
         else:
             self.labely = labely
         if timerange:
             self.data[0] = map(lambda secf: 1000*time.mktime((timestart + datetime.timedelta(seconds=int(secf))).timetuple()),data[0])
             #self.data[0] = map(int,data[0])
         return
     
     #print('min_y=%d max_y=%d scaling_y=%d' % (min_y,max_y,scaling_y))
     #max_y = int(ceil(max(datay))) # up rounded max value
     #if min(datay)<0.0:
     #    min_y = int(floor(min(datay)))
     #else:
     #    min_y = 0
     #print('min_y=%d,max_y=%d %f' % (min_y,max_y,max(datay)))
     #self.marginsize = max(len(str(max_y)),len(str(min_y)))*6+6  # Font size of y label is 6 pixels
     #self.marginsize = 30
     self.marginsize = max(max(len(str(max_y)),len(str(min_y)))*7+10,30)  # Font size of y label is 6 pixels
     self.height = 200
     # Build chart
     if len(data)==2 and len(data[0])>1:
         self.width = 800
         (min_x,max_x,scaling_x) = ExtendRange(datax[0],datax[len(datax)-1])
         #print('min_x=%d max_x=%d' % (min_x,max_x))
         min_x = int(floor(datax[0]))
         max_x = int(ceil(datax[len(datax)-1]))
         #print('min_x=%d max_x=%d' % (min_x,max_x))
         chart = XYLineChart(self.width, self.height, x_range=[min_x,max_x], y_range=[min_y,max_y])
         chart.add_data(datax)
         chart.add_data(datay)
         if min_y<0 and max_y>0:
             chart.add_data([0,max_x])
             chart.add_data([0,0])
             chart.set_colours(['339900','FF0000'])
             chart.grid = '%s,%s,%s,%s,%s,%s' % (float(scaling_x*100)/float(max_x-min_x),float(scaling_y*100)/float(max_y-min_y),2,2,float(min_x*100)/float(max_x-min_x),0.0)
         else:
             chart.set_colours(['339900'])
             try:
                 chart.grid = '%s,%s,%s,%s,%s,%s' % (float(scaling_x*100)/float(max_x-min_x),float(scaling_y*100)/float(max_y-min_y),2,2,float(min_x*100)/float(max_x-min_x),float(min_y*100)/float(max_y-min_y))
             except ZeroDivisionError:
                 print 'DEBUG: %s %s %s %s' % (max_x,min_x,max_y,min_y)
         #print('grid=%s' % chart.grid)
         #chart.set_grid ...
         if timerange:
             axis_index = chart.set_axis_labels(Axis.BOTTOM, map(lambda sec: SecondToTimeString(timestart,sec),MyRange(min_x,max_x,scaling_x)))
             chart.set_axis_positions(axis_index, map(lambda x: '%.4f' % (float(x*100)/float(max_x-min_x)),MyRange(min_x,max_x,scaling_x)))  #.4f to no have too long urls
             #for x in MyRange(scaling_x,max_x,scaling_x):
             #    chart.add_marker(0,GetIndexOfClosest(datax,x),'V','AAAAAA',1,-1)
         else:
             axis_index = chart.set_axis_labels(Axis.BOTTOM, MyRange(min_x,max_x,scaling_x))
             chart.set_axis_positions(axis_index, map(lambda x: '%.4f' % (float(x*100)/float(max_x-min_x)),MyRange(min_x,max_x,scaling_x)))  #.4f to no have too long urls
             #for x in MyRange(scaling_x,max_x,scaling_x):
             #    chart.add_marker(0,GetIndexOfClosest(datax,x),'V','AAAAAA',1,-1)
         chart.set_axis_labels(Axis.LEFT, MyRange(min_y,max_y,scaling_y))
         marginright = 30
         graphsize = self.width-self.marginsize-marginright
         #print([GetIndexOfCloserFromOrderedList(i,ptindexlist) for i in range(0,nbpts)])
         if ptindexlist==None:
             #if nbpts==None:
             #    nbpts=len(datax)
             if not(nbpts==len(datax)):
                 raise Exception('nbpts=%s len(datax)=%s'%(nbpts,len(datax)))
             self.pt2px = [int(round(datax[i]*graphsize/(max(datax)-min(datax)))) for i in range(0,nbpts)]
         else:
             dataxrange = max(datax)-min(datax)
             maxj = len(ptindexlist)-1
             self.pt2px = []
             j = 0
             for i in range(0,nbpts):
                 if j<maxj and ptindexlist[j+1]<=i:
                     j += 1
                 self.pt2px.append(int(round(datax[j]*graphsize/dataxrange)))
             #self.pt2px = [int(round(datax[GetIndexOfClosestFromOrderedList(i,ptindexlist)]*graphsize/(max(datax)-min(datax)))) for i in range(0,nbpts)]
         # the following works only if points are equally
         #self.pt2px = [int(round(datax[min(int(round(i*len(datax)/nbpts)),len(datax)-1)]*graphsize/(max(datax)-min(datax)))) for i in range(0,nbpts)]
     else:
         self.pt2px = None
         self.width = len(datay) + self.marginsize
         chart = SimpleLineChart(self.width, self.height, y_range=[min_y,max_y])
         chart.add_data(data)
         chart.set_colours(['0000FF'])
         #print('here %d %d'%(min_y,max_y))
         #sys.exit()
         chart.set_axis_labels(Axis.LEFT, MyRange(min_y,max_y,scaling_y))
         marginright = 0
     chart.markers.append(('B','FFEE0080','0','1.0','0'))
     #chart.add_fill_simple('FFCC00')
     # Set the vertical stripes
     #chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)
     # Set label
     #chart.set_title(label)
     # Build googlecharts url
     #print '&chma='+str(self.marginsize-2)+','+str(marginright)+',0,0'
     self.imagefileurl = chart.get_url() + '&chma='+str(self.marginsize-2)+','+str(marginright)+',0,0'
     if len(self.imagefileurl)>2069:
         raise ValueError('Too much values (%d) instead of 2069' % (len(self.imagefileurl)))
     Log('MyXYChart: end\n')
Esempio n. 27
0
def novidomejni_grafik():
    """По датум последните 30 дена колку нови домејни имало."""

    c1 = conn.cursor()
    c1.execute(
        "select datum, novidomejni from novidomejni order by datum desc limit 30"
    )

    novi = [x for x in c1]
    novi.sort()

    datumi = [x[0] for x in novi]
    ipsilonoska = [int(x[1]) for x in novi]  # kolku novi
    iksoska = [x for x in range(0, len(datumi))]

    xmax = len(iksoska)
    ymax = max([int(a[1]) for a in novi])

    chart = XYLineChart(800, 300, x_range=(0, xmax - 1), y_range=(0, ymax))

    chart.add_data(iksoska)
    chart.add_data(ipsilonoska)

    for x in range(0, len(datumi)):
        if x % 2:
            datumi[x] = ''

    ipsilon = [x for x in range(0, ymax + 1)]
    for y in range(0, ymax + 1):
        if y % 2:
            ipsilon[y] = ''
    ipsilon[0] = ''
    ipsilon[-1] = ymax

    chart.set_axis_labels(Axis.BOTTOM, datumi)
    chart.set_axis_labels(Axis.LEFT, ipsilon)
    chart.set_title("Број на нови .mk домени по денови|")

    return chart.get_url()
Esempio n. 28
0
def xy_rect():
    chart = XYLineChart(settings.width, settings.height,
                        x_range=(0, 100), y_range=(0, 100))
    chart.add_data([10, 90, 90, 10, 10])
    chart.add_data([10, 10, 90, 90, 10])
    chart.download('line-xy-rect.png')
Esempio n. 29
0
def presence_chart(days):
  """Returns a graph of user presence, in his language of choice."""

  start = datetime.date.today() - datetime.timedelta(days=days)
  start = datetime.date(start.year, start.month, 1)

  genreh = Rehearsal.objects.filter(type='G').filter(date__gte=start).order_by('date')
  begreh = Rehearsal.objects.filter(type='B').filter(date__gte=start).order_by('date')
  concert = Concert.objects.filter(start__gte=start).order_by('start')

  # Calculates the vertical range
  max_y = 0
  genreh_presence = [] 
  active = []
  begreh_presence = []
  concert_presence = []
  for k in genreh: 
    active.append(((k.date-start).days, k.members.count()))
    if k.members.count() > max_y: max_y = k.members.count()
    genreh_presence.append(((k.date-start).days, k.presence().count()))
  for k in begreh: 
    begreh_presence.append(((k.date-start).days, k.presence().count()))
  for k in concert: 
    concert_presence.append(((k.start.date()-start).days, k.participated().count()))
    if k.participated().count() > max_y: max_y = k.participated().count()
  max_y = 5+5*(max_y/5)

  # Chart size of 200x125 pixels and specifying the range for the Y axis
  width = 500
  height = 200
  chart = XYLineChart(width, height, y_range=[0, max_y])
  chart.add_data([k[0] for k in genreh_presence])
  chart.add_data([k[1] for k in genreh_presence])
  chart.add_data([k[0] for k in begreh_presence])
  chart.add_data([k[1] for k in begreh_presence])
  chart.add_data([k[0] for k in concert_presence])
  chart.add_data([k[1] for k in concert_presence])
  chart.add_data([k[0] for k in active])
  chart.add_data([k[1] for k in active])

  # Set the line colours
  chart.set_colours(['0000FF', 'FF0000', '00FF00','000000'])
  chart.set_legend([_(u'General rehearsals'),_(u'Beginner rehearsals'),_(u'Concerts'),_(u'Active members')])
  chart.set_title(_(u'Member presence'))

  # Contents of each axis
  x_labels = range(0, max_y + 1, 5)
  x_labels[0] = ''
  chart.set_axis_labels(Axis.LEFT, x_labels)

  # Calculates the months
  months = [start.month + k for k in range(int(math.ceil(days/30)))]
  while max(months) > 12:
    for k in range(len(months)): 
      if months[k] > 12: months[k] -= 12 
  labels = [k.strftime('%b') for k in [datetime.date(1970, j, 1) for j in months]] + [''] 
  chart.set_axis_labels(Axis.BOTTOM, labels)

  # Set the horizontal dotted lines
  chart.set_grid(0, 20, 1, 5)

  chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 1.0/(len(labels)-1), 'FFFFFF', 1.0/(len(labels)-1))

  return {'url': chart.get_url(), 'width': width, 'height': height}