def process (name, date):
    newdate = date[8:10] + "_" + date[5:7] + "_" + date[0:4]
    url = r"http://www.lloydsbankinggroup.com/media/excel/2010/%s_historic_data.xls" % newdate
    print url
    url = r"http://www.lloydsbankinggroup.com/media/excel/2010/04_06_10_historic_data.xls"
    book = xlrd.open_workbook(file_contents=scrape(url))
    sheet = book.sheet_by_name (name)
    months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']

    data = []
    i = 1
    while i < 500:
        try:
            month = sheet.cell_value (i, 0)
            year  = sheet.cell_value (i, 1)
            level = sheet.cell_value (i, 2)
        except:
            break
        when= "%04d-%02d-01" % (int(year), months.index (month) + 1)
        i = i + 1
        data.append (level)        
        sqlite.save(unique_keys=["Date"], data={"Date":when, "Index":level})

    chart = SimpleLineChart(500, 255, y_range=[0, 700])
    chart.add_data (data)
    metadata.save("chart", chart.get_url())
예제 #2
0
def makeChartOfDay(data):

    max_user = 150
    chart = SimpleLineChart(400, 325, y_range=[0, max_user])
    dataChart = []
    for ore in range(24):
        ore = str(ore)
        if len(ore) == 1:
            ore = '0'+ore
        try:
            dataChart.append(userList[data]['stats']['online'][ore])
        except:
            dataChart.append(0)
    
    chart.add_data(dataChart)

    chart.set_colours(['0000FF'])

    left_axis = range(0, max_user + 1, 25)
    
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)
    
#    chart.set_axis_labels(Axis.BOTTOM, \
#    ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])

    chart.set_axis_labels(Axis.BOTTOM, \
    range(0, 24))

    return chart.get_url()
예제 #3
0
    def __init__(self):

        # Set the vertical range from 0 to 100
        factor = 8 - 1 
        max_y = 20 * factor
        max_x = 250
        # Chart size of 200x125 pixels and specifying the range for the Y axis
        self.chart = SimpleLineChart(width=50*factor, height=25*factor, 
                                     title='ping ftp.sunet.se',
#                                     legend=True,
                                     x_range=[0, max_x],                                      
                                     y_range=[0, max_y])


        # Set the line colour to blue
        self.chart.set_colours(colours=['0000FF'])

        # Set the vertical stripes:arguments area, angle etc.
        #self.chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)

        # Set the horizontal dotted lines
        #self.chart.set_grid(x_step=0, y_step=5*factor, line_segment=factor, blank_segment=factor)

        # The Y axis labels contains 0 to 100 skipping every 25, but remove the
        # first number because it's obvious and gets in the way of the first X
        # label.
        left_axis = range(0, max_y + 1, 25)
        left_axis[0] = ''
        self.chart.set_axis_labels(axis_type=Axis.LEFT, values=left_axis)

        # X axis labels
        self.chart.set_axis_labels(axis_type=Axis.BOTTOM, \
#        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])
        values= [ ' ', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])
예제 #4
0
def get_chart_url(series):
    chart = SimpleLineChart(400, 200)

    chart.set_legend([name for (name, _) in series])
    chart.set_colours_within_series(colors[0:len(series)])

    for (_, data) in series:
        chart.add_data(data)

    return chart.get_url()
예제 #5
0
파일: labels.py 프로젝트: thqbop/nuvola
def many_labels():
    chart = SimpleLineChart(settings.width, settings.height)

    for a in range(3):
        for axis_type in (Axis.LEFT, Axis.RIGHT, Axis.BOTTOM):
            index = chart.set_axis_range(axis_type, 0, random.random() * 100)
            chart.set_axis_style(index, colour=helper.random_colour(), \
                font_size=random.random() * 10 + 5)

    chart.add_data(helper.random_data())
    chart.download('label-many.png')
예제 #6
0
    def mk_chart(self):
        from pygooglechart import SimpleLineChart
        chart =  SimpleLineChart(self.width, self.height, colours=('91CF60', 'FC8D59'))

        all_labels = [d[0] for d in self.cumulative]

        chart.add_data([d[1] for d in self.cumulative])
        chart.add_data([d[1] for d in self.newdata])
        chart.set_axis_labels('y', range(0, self.cmax, (self.cmax / 4)))
        chart.set_axis_labels('x', [all_labels[x] for x in
                                    range(0, len(all_labels), (len(all_labels) / 4))])
        return chart
예제 #7
0
    def __init__(self, data, iter=0, width=300, height=300):
        self.chart = SimpleLineChart(width, height, y_range=(0, 10))
        legend = []
        colors = ["cc0000", "00cc00", "0000cc", "990000", "009900", "000099", "0099ff", "FF9900", "9900ff", "ff0099"]
        title = "die rolls per objective"
        if iter > 0:
            title = title + " (%s samples)" % iter
        for i in data.keys():
            self.chart.add_data(data[i])
            legend.append(str(i))

        logging.debug(legend)
        logging.debug(colors)
        self.chart.set_colours(colors)
        self.chart.set_legend(legend)

        grid_x_amount = 100 / (len(data[i]) - 1)
        self.chart.set_grid(grid_x_amount, 10, 5, 5)

        left_axis = range(0, 11, 1)
        left_axis[0] = ""
        self.chart.set_axis_labels(Axis.LEFT, left_axis)

        bottom_len = len(data[i]) + 2
        bottom_axis = range(2, bottom_len, 1)
        self.chart.set_axis_labels(Axis.BOTTOM, bottom_axis)

        self.chart.set_title(title)
예제 #8
0
    def mk_chart(self):
        from pygooglechart import SimpleLineChart
        chart = SimpleLineChart(self.width,
                                self.height,
                                colours=('91CF60', 'FC8D59'))

        all_labels = [d[0] for d in self.cumulative]

        chart.add_data([d[1] for d in self.cumulative])
        chart.add_data([d[1] for d in self.newdata])
        chart.set_axis_labels('y', range(0, self.cmax, (self.cmax / 4)))
        chart.set_axis_labels('x', [
            all_labels[x]
            for x in range(0, len(all_labels), (len(all_labels) / 4))
        ])
        return chart
예제 #9
0
def taxonLineChart(taxon, site, max_y=None, label_record=None):
    
    min_y = 0
    
    records = taxon.mean_densities.filter(site=site).order_by('year')
    years = [ record.year for record in records ]
    means = [ record.mean for record in records ]
    
    # Set the vertical range from 0 to 100
    max_y = max_y or max(means)
    span = max_y - min_y
    if span == 0:
        max_y = 1
        

    step = pow(10, round(math.log(max_y) / math.log(10)) - 1)
    ticks = frange(min_y, max_y + (step * 1), step)

    chart = SimpleLineChart(300, 100, y_range=[0, max_y])

    # Add the chart data
    chart.add_data(means)

    # Set the line colour to blue
    chart.set_colours(['76A4FB'])
    
    # limit number of ticks to around 4
    n = len(ticks) / 3

    # The Y axis labels contains 0 to 100 skipping every 25, but remove the
    # first number because it's obvious and gets in the way of the first X
    # label.
    ticks = ticks[::n]
    ticks[0] = ''
    chart.set_axis_labels(Axis.LEFT, ticks)

    # X axis labels
    chart.set_axis_labels(Axis.BOTTOM, years[::4])
    
    url = chart.get_url()
    url.replace('lc', 'ls')
    url += '&chm=B,C3D9FF,0,0,0'
    if label_record:
        url += ('|@a,3366CC,0,%f:%f,4' % (float(years.index(label_record.year)) / float(len(years)), (label_record.mean+(max_y * 0.05))/max_y))
    print url
    return url
예제 #10
0
def group_membership_activity(request, group_slug):
    group = get_object_or_404(BaseGroup, slug=group_slug)

    listcount = []
    listdate = []
    currentcount = group.member_users.all().count()
    thedate = date.today()
    skip = False
    while thedate.year != date.today().year - 1 or thedate.month != date.today(
    ).month:
        if thedate.month == 1:
            startdate = date(year=thedate.year - 1, month=12, day=1)
        else:
            startdate = date(year=thedate.year, month=thedate.month - 1, day=1)
        joins = GroupMemberRecord.objects.filter(
            group=group,
            membership_start=True,
            datetime__range=(startdate, thedate)).count()
        unsubs = GroupMemberRecord.objects.filter(
            group=group,
            membership_end=True,
            datetime__range=(startdate, thedate)).count()
        listcount.append(currentcount - joins + unsubs)
        if not skip:
            listdate.append(thedate.strftime("%B %y"))
        else:
            listdate.append("")
        skip = not skip
        thedate = startdate

    listcount.reverse()
    listdate.reverse()

    activity = SimpleLineChart(600,
                               450,
                               y_range=(min(listcount), max(listcount)))
    activity.add_data(listcount)

    yaxis = range(
        min(listcount),
        max(listcount) + 1,
        max(max(listcount) / 10,
            1))  # that last number should be 25 or 50.  but for testing...
    if len(yaxis) < 2:  # only for testing...
        yaxis.append(1)
    yaxis[0] = ''
    activity.set_axis_labels(Axis.LEFT, yaxis)
    activity.set_axis_labels(Axis.BOTTOM, listdate)

    return activity.get_url()
예제 #11
0
def simpleChart(bottom_labels, data):
    # round min and max to nearest integers
    datamin = int(min(data) - 0.5)
    datamax = int(max(data) + 0.5)
    chart = SimpleLineChart(200, 125, y_range=[datamin, datamax])
    chart.add_data(data)

    left_axis = [datamin, 0, datamax]
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_axis_labels(Axis.BOTTOM, bottom_labels)
    return chart
예제 #12
0
def many_labels():
    chart = SimpleLineChart(settings.width, settings.height)

    for a in xrange(3):
        for axis_type in (Axis.LEFT, Axis.RIGHT, Axis.BOTTOM):
            index = chart.set_axis_range(axis_type, 0, random.random() * 100)
            chart.set_axis_style(index, colour=helper.random_colour(), \
                font_size=random.random() * 10 + 5)

    chart.add_data(helper.random_data())
    chart.download('label-many.png')
예제 #13
0
def graphURL(data):
    log("debut graphURL")
    log(str(data))
    # Set the vertical range from 0 to 100
    max_y = 100 * max(data) + 20
    # Chart size of 300x150 pixels and specifying the range for the Y axis
    log(str(max_y))
    try:
        chart = SimpleLineChart(300, 150, y_range=[0, max_y])
    except Exception, e:
        log(str(e))
예제 #14
0
파일: graph.py 프로젝트: carlobifulco/Yaic
 def __init__(self,data):
   x_size=900
   colours=['0000FF']
   y_size=200
   spacer=10
   y_range=[min(data)-spacer, max(data)+spacer]
   left_axis=range(y_range[0],y_range[1],5)
   self.chart=SimpleLineChart(x_size,y_size,y_range=y_range)
   self.chart.set_axis_labels(Axis.LEFT,left_axis)
   self.chart.set_colours(colours)
   self.chart.add_data(data)
예제 #15
0
def gchart(data, node, check, metric, start=datetime.now()-timedelta(days=1), end=datetime.now()):
  d = []
  ts = []
  for p in  data['metrics'][0]['data']:
    d.append(float(p['avg']))
    ts.append(p['ts'])

  # Chart size of 200x125 pixels and specifying the range for the Y axis
  max_y = int(max(d))
  chart = SimpleLineChart(450, 250, y_range=[0,max_y])
  chart.add_data(d)
  left_axis = range(0, max_y + 1, max_y/5)
  left_axis[0] = ''
  chart.set_axis_labels(Axis.LEFT, left_axis)
  min_dt = datetime.fromtimestamp(min(ts))
  max_dt = datetime.fromtimestamp(max(ts))
  chart.set_axis_labels(Axis.BOTTOM, [ str(min_dt), str(max_dt) ])
  title = '%s.%s.%s' % (node['name'], check['type'], metric)
  chart.set_title(title)
  return chart.get_url()
예제 #16
0
    def get_pace_chart_url(self, width, height):
        if len(self.positions()) == 0:
            return ''

        pace = []
        int_dist = []
        s = 0
        last_p = None
        for p in self.positions():
            if last_p != None:
                ds = distance.distance((p.latitude, p.longitude), \
                    (last_p.latitude, last_p.longitude)).kilometers
                s = s + int(ds * 1000)
                dt = (p.time - last_p.time).seconds
                if ds > 0:
                    pace.append(dt / ds)
                    int_dist.append(s)

            last_p = p

        int_pace = [int(p) for p in ema(pace, 20)]

        min_pace = int(min(int_pace) * 0.95)
        max_pace = int(max(int_pace) / 0.95)
        mid_pace = (max_pace + min_pace) / 2

        min_pace_str = '%02d:%02d' % (min_pace / 60, min_pace % 60)
        mid_pace_str = '%02d:%02d' % (mid_pace / 60, mid_pace % 60)
        max_pace_str = '%02d:%02d' % (max_pace / 60, max_pace % 60)

        chart = SimpleLineChart(width, height, y_range = (min_pace, max_pace))
        chart.add_data(int_pace)
        chart.set_axis_labels(Axis.LEFT, [min_pace_str, mid_pace_str, max_pace_str])

        return chart.get_url()
def simpleChart(bottom_labels, data):
    # round min and max to nearest integers
    datamin = int(min(data) - 0.5)
    datamax = int(max(data) + 0.5)
    chart = SimpleLineChart(200, 125, y_range=[datamin, datamax])
    chart.add_data(data)
    
    left_axis = [datamin,0,datamax]
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_axis_labels(Axis.BOTTOM, bottom_labels) 
    return chart
예제 #18
0
파일: views.py 프로젝트: reverie/seddit.com
def month_graph(data, start, end):
    """Helper for making graphy graph for a month's worth of data on something."""
    from pygooglechart import SimpleLineChart, Axis
    WIDTH, HEIGHT = 700, 200
    
    y_range = (0, max(max(data), 1)) # todo: have extra room when I figure out how to do labels (set_axis_positions?)
    x_range = (0, 30)
    chart = SimpleLineChart(WIDTH, HEIGHT, y_range=y_range, x_range=x_range)
    chart.add_data(data)
    chart.set_axis_labels(Axis.LEFT, y_range)
    #chart.left.labels = chart.left.label_positions = [0, max(data)]
    chart.set_axis_labels(Axis.BOTTOM, [d.strftime('%D') for d in
                                date_range(start, end, datetime.timedelta(days=10))])
    #chart.bottom.label_positions = [0, 10, 20, 30]
    return chart.get_url()
예제 #19
0
def getchart(history):
    data = []
    created = []
    for h in history:
        data.append(float(h.average))
        created.append(int(h.created.day))

    max_y = int(math.ceil(max(data))) + 1
    min_y = int(math.floor(min(data))) - 1
    chart = SimpleLineChart(550, 225, y_range=[min_y, max_y])
    chart.add_data(data)
    chart.set_colours(["0000FF"])
    # chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)
    chart.set_grid(0, 25, 5, 5)
    left_axis = range(min_y, max_y + 1, 2)
    left_axis[0] = ""
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_axis_labels(Axis.BOTTOM, created)
    return chart
예제 #20
0
파일: views.py 프로젝트: alexnjoyce/myewb2
def group_membership_activity(request, group_slug):
    group = get_object_or_404(BaseGroup, slug=group_slug)
    
    listcount = []
    listdate = []
    currentcount = group.member_users.all().count()
    thedate = date.today()
    skip = False
    while thedate.year != date.today().year - 1 or thedate.month != date.today().month:
        if thedate.month == 1:
            startdate = date(year=thedate.year - 1,
                             month=12, day=1)
        else:
            startdate = date(year=thedate.year,
                             month=thedate.month - 1,
                             day=1)
        joins = GroupMemberRecord.objects.filter(group=group,
                                                 membership_start=True,
                                                 datetime__range=(startdate, thedate)).count()
        unsubs = GroupMemberRecord.objects.filter(group=group,
                                                  membership_end=True,
                                                  datetime__range=(startdate, thedate)).count()
        listcount.append(currentcount - joins + unsubs)
        if not skip:
            listdate.append(thedate.strftime("%B %y"))
        else:
            listdate.append("")
        skip = not skip
        thedate = startdate
        
    listcount.reverse()
    listdate.reverse()

    activity = SimpleLineChart(600, 450, y_range=(min(listcount), max(listcount)))
    activity.add_data(listcount)

    yaxis = range(min(listcount), max(listcount) + 1, max(max(listcount)/10, 1))    # that last number should be 25 or 50.  but for testing...
    if len(yaxis) < 2:  # only for testing...
        yaxis.append(1)
    yaxis[0] = ''
    activity.set_axis_labels(Axis.LEFT, yaxis)
    activity.set_axis_labels(Axis.BOTTOM, listdate)
        
    return activity.get_url()
예제 #21
0
파일: models.py 프로젝트: perliedman/gypsum
    def get_elevation_chart_url(self, width, height):
        if len(self.positions) == 0:
            return ''

        int_elevations = [int(elevation) for elevation in ema([p.altitude for p in self.positions], 30)]

        max_elev = int(max(int_elevations) / 0.95)
        min_elev = int(min(int_elevations) * 0.95)

        chart = SimpleLineChart(width, height, y_range = (min_elev, max_elev))
        chart.add_data(int_elevations)
        chart.set_axis_range(Axis.LEFT, min_elev, max_elev)

        return chart.get_url()
예제 #22
0
파일: models.py 프로젝트: perliedman/gypsum
    def get_pace_chart_url(self, width, height):
        def calc_pace_and_dist_from_previous(acc, p):
            last_p = acc[0]
            s = acc[1]
            pace = acc[2]
            int_dist = acc[3]

            ds = distance.distance((p.latitude, p.longitude), \
                (last_p.latitude, last_p.longitude)).kilometers
            s = s + int(ds * 1000)
            dt = (p.time - last_p.time).seconds
            if ds > 0:
                pace.append(dt / ds)
                int_dist.append(s)

            acc[0] = p
            acc[1] = s

            return acc

        if len(self.positions) == 0:
            return ''

        pace = []
        int_dist = []
        s = 0
        last_p = None

        r = reduce(calc_pace_and_dist_from_previous,
            self.positions[1:len(self.positions)],
            [self.positions[0], 0, [], []])
        pace = r[2]
        int_dist = r[3]
        int_pace = [int(p) for p in ema(pace, 30)]

        min_pace = int(min(int_pace) * 0.95)
        max_pace = int(max(int_pace) / 0.95)
        mid_pace = (max_pace + min_pace) / 2

        min_pace_str = '%02d:%02d' % (min_pace / 60, min_pace % 60)
        mid_pace_str = '%02d:%02d' % (mid_pace / 60, mid_pace % 60)
        max_pace_str = '%02d:%02d' % (max_pace / 60, max_pace % 60)

        chart = SimpleLineChart(width, height, y_range = (min_pace, max_pace))
        chart.add_data(int_pace)
        chart.set_axis_labels(Axis.LEFT, [min_pace_str, mid_pace_str, max_pace_str])

        return chart.get_url()
def makechart(aaseq, regions):
    hdph = dict()
    hdph['d'] = -3.5
    hdph['e'] = -3.5
    hdph['k'] = -3.9
    hdph['r'] = -4.5
    hdph['h'] = -3.2
    hdph['y'] = -1.3
    hdph['w'] = -0.9
    hdph['f'] = 2.8
    hdph['c'] = 2.5
    hdph['m'] = 1.9
    hdph['s'] = -0.8
    hdph['t'] = -0.7
    hdph['n'] = -3.5
    hdph['q'] = -3.5
    hdph['g'] = -0.4
    hdph['a'] = 1.8
    hdph['v'] = 4.2
    hdph['l'] = 3.8
    hdph['i'] = 4.5
    hdph['p'] = -1.6
    hdphseq = []
    for i in range(len(aaseq)):
        hdphseq.append(hdph[aaseq[i]])
    
    min_y = -5
    max_y = 5
    chart = SimpleLineChart(2, 2, y_range=[min_y, max_y])
    
    #chart.add_data([max_y]*2)
    chart.add_data(hdphseq)   
    #chart.add_data([min_y]*2)
    chart.set_axis_labels(Axis.BOTTOM, aaseq)
    
    chart.download('test.png')
    
    #print hdphseq
    return hdphseq
예제 #24
0
def get_chart_url():
    cache_key = 'phonedb-chart-url-%s' % settings.LANGUAGE_CODE
    url = cache.get(cache_key)
    if url is not None:
        return url
    enddate = datetime.datetime.now()
    # This works badly, we will rather render only chart for month after
    # it has finished
    #+ datetime.timedelta(days=30)
    endyear = enddate.year
    endmonthlast = enddate.month
    endmonth = 12

    dates = []
    unsupported = []
    supported = []
    totals = []
    alls = []
    years = []

    for year in range(2006, endyear + 1):
        if year == endyear:
            endmonth = endmonthlast
        for month in range(1, endmonth + 1):
            if month == 1:
                years.append('%d' % year)
            else:
                years.append('')

            time_range = (datetime.date(1900, 1,
                                        1), datetime.date(year, month, 1))

            supported_val = Phone.objects.exclude(state='deleted').filter(
                connection__isnull=False).filter(
                    created__range=time_range).count()
            unsupported_val = Phone.objects.exclude(state='deleted').filter(
                connection__isnull=True).filter(
                    created__range=time_range).count()
            all_val = Phone.objects.filter(
                created__lt=datetime.date(year, month, 1)).count()

            supported.append(supported_val)
            unsupported.append(unsupported_val)
            totals.append(unsupported_val + supported_val)
            alls.append(all_val)
            dates.append('%d-%02d' % (year, month))


#print dates
#print unsupported
#print supported
#print totals
#print alls

    max_y = int(((max(alls) / 100) + 1) * 100)

    chart = SimpleLineChart(800, 300, y_range=[0, max_y])

    #    chart.fill_solid(chart.BACKGROUND, 'ffd480')
    #    chart.fill_solid(chart.CHART, 'ffd480')
    # Chart data
    chart.add_data(supported)
    chart.add_data(totals)
    chart.add_data(alls)
    # Lowest value
    chart.add_data([0] * 2)

    # Set the line colour to blue
    chart.set_colours(['00FF00', 'FF0000', '0000FF', '00000000'])

    #chart.add_fill_range('76A4FB', 2, 3)
    # Set the vertical stripes
    month_stripes = 3.0
    chart.fill_linear_stripes(Chart.CHART, 0, 'ffffff',
                              month_stripes / len(alls), 'cccccc',
                              month_stripes / len(alls))

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

    chart.set_legend([
        _('Supported phones').encode('utf-8'),
        _('Approved records').encode('utf-8'),
        _('Total records').encode('utf-8')
    ])

    left_axis = ['%d' % x for x in range(0, max_y + 1, int(max_y / 10))]
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)

    chart.set_axis_labels(Axis.BOTTOM, years)

    url = chart.get_url().replace('http:', 'https:')
    cache.set(cache_key, url, 3600)
    return url
예제 #25
0
def show(request, fund_id):
    fund = get_object_or_404(Fund, pk=fund_id)
    prices = fund.fundprice_set.order_by('-date')
    data = []
    for price in prices:
        data.append(price.price)
    data.reverse()
    chart = SimpleLineChart(500, 200, y_range=[min(data), max(data)])
    chart.add_data(data)
    chart.set_colours(['0000FF'])
    chart.fill_solid('bg', 'DDDDFF')
    chart.set_axis_labels(Axis.LEFT, [min(data), max(data)])
    start_date = prices[len(prices) - 1].date.isoformat()
    end_date = prices[0].date.isoformat()
    chart.set_axis_labels(Axis.BOTTOM, [start_date, end_date])
    url = chart.get_url()
    return render_to_response('funds/show.html',
            {'fund': fund, 'prices': prices, 'graph_url': url})
예제 #26
0
def main_dashboard(request):

    today, created = DailyStats.objects.get_or_create(day=date.today())
    if today.users == 0:
        today.users = 1

    # ---- Daily usage ----
    enddate = date.today()
    #startdate = enddate - timedelta(weeks=60)
    startdate = enddate - timedelta(weeks=4)
    averageusage = DailyStats.objects.filter(
        day__range=(startdate, enddate)).order_by('day')
    days = []
    signins = []
    posts = []
    replies = []
    whiteboards = []
    signups = []
    listsignups = []
    listupgrades = []
    deletions = []
    numUsers = []
    numRegularMembers = []
    regupgrades = []
    renewals = []
    regdowngrades = []
    for s in averageusage:
        days.append(s.day.strftime("%B %y"))
        signins.append(s.signins)
        posts.append(s.posts)
        replies.append(s.replies)
        whiteboards.append(s.whiteboardEdits)
        signups.append(s.signups)
        listsignups.append(s.mailinglistsignups)
        listupgrades.append(s.mailinglistupgrades)
        deletions.append(s.deletions)
        numUsers.append(s.users)
        numRegularMembers.append(s.regularmembers)
        regupgrades.append(s.regupgrades)
        renewals.append(s.renewals)
        regdowngrades.append(s.regdowngrades)

    xaxis = []
    #for i in range(0, len(days), 1):    # this will make limited test data look better
    for i in range(0, len(days), len(days) / 8):
        xaxis.append(days[i])

    # ---- Daily usage ----
    dailyUsageChart = SimpleLineChart(600, 450, y_range=(0, max(signins)))
    #chart.add_data(avgsignins)
    dailyUsageChart.add_data(posts)
    dailyUsageChart.add_data(replies)
    dailyUsageChart.add_data(signins)
    dailyUsageChart.add_data(whiteboards)

    dailyUsageChart.set_colours(['ff0000', 'ffff00', '00ff00', '0000ff'])
    dailyUsageChart.set_legend(['posts', 'replies', 'signins', 'whiteboards'])
    dailyUsageChart.set_legend_position('b')

    #yaxis = range(0, max_signins + 1, 2)    # this will make limited test data look better
    yaxis = range(0, max(signins), max(signins) / 10)
    yaxis[0] = ''
    dailyUsageChart.set_axis_labels(Axis.LEFT, yaxis)
    dailyUsageChart.set_axis_labels(Axis.BOTTOM, xaxis)

    dailyUsage = dailyUsageChart.get_url()

    # ---- Account changes ----
    accountChangesChart = SimpleLineChart(600, 450, y_range=(0, 25))
    accountChangesChart.add_data(signups)
    accountChangesChart.add_data(listsignups)
    accountChangesChart.add_data(listupgrades)
    accountChangesChart.add_data(deletions)

    accountChangesChart.set_colours(['ff0000', 'ffff00', '00ff00', '0000ff'])
    accountChangesChart.set_legend(
        ['account signups', 'email signups', 'email upgrades', 'deletions'])
    accountChangesChart.set_legend_position('b')

    #yaxis = range(0, 25, 2)    # this will make limited test data look better
    yaxis = range(0, min(max(listsignups), 10), max(max(listsignups) / 10, 1))
    yaxis[0] = ''
    accountChangesChart.set_axis_labels(Axis.LEFT, yaxis)
    accountChangesChart.set_axis_labels(Axis.BOTTOM, xaxis)

    accountChanges = accountChangesChart.get_url()

    # ---- Membership ----
    membershipChart = SimpleLineChart(600, 450, y_range=(42000, 52000))
    membershipChart.add_data(numUsers)
    membershipChart.add_data(numRegularMembers)

    membershipChart.set_colours(['ff0000', '0000ff'])
    membershipChart.set_legend(['total users', 'regular members'])
    membershipChart.set_legend_position('b')

    yaxis = range(42000, 52000, 1000)
    yaxis[0] = ''
    yaxis2 = range(0, 1500, 50)
    yaxis2[0] = ''
    membershipChart.set_axis_labels(Axis.LEFT, yaxis)
    membershipChart.set_axis_labels(Axis.RIGHT, yaxis2)
    membershipChart.set_axis_labels(Axis.BOTTOM, xaxis)

    membershipChart = membershipChart.get_url()

    # ---- Account changes ----
    membershipChangesChart = SimpleLineChart(600, 450, y_range=(0, 10))
    membershipChangesChart.add_data(regupgrades)
    membershipChangesChart.add_data(renewals)
    membershipChangesChart.add_data(regdowngrades)

    membershipChangesChart.set_colours(['ff0000', 'ffff00', '00ff00'])
    membershipChangesChart.set_legend(
        ['regular upgrades', 'renewals', 'regular downgrades'])
    membershipChangesChart.set_legend_position('b')

    #yaxis = range(0, 25, 2)    # the same.
    yaxis = range(
        0, max(max(regupgrades), max(regdowngrades), max(renewals)),
        max(max(max(regupgrades), max(regdowngrades), max(renewals)) / 10, 1))
    yaxis[0] = ''
    membershipChangesChart.set_axis_labels(Axis.LEFT, yaxis)
    membershipChangesChart.set_axis_labels(Axis.BOTTOM, xaxis)

    membershipChanges = membershipChangesChart.get_url()

    # ---- Status breakdown ----
    statusBreakdownChart = PieChart3D(600, 240)
    mlistmembers = today.users - today.regularmembers - today.associatemembers
    statusBreakdownChart.add_data([
        mlistmembers +
        1,  # FIXME: the +1 is needed so pygoogle doesn't crash (it doesn't handle zeroes well)
        today.associatemembers + 1,
        today.regularmembers + 1
    ])

    statusBreakdownChart.set_colours(['ff0000', 'ffff00', '00ff00'])
    statusBreakdownChart.set_pie_labels(
        ["mailing list members", "associate members", "regular members"])
    statusBreakdown = statusBreakdownChart.get_url()

    # ---- Membership breakdown ----
    chapters = Network.objects.filter(chapter_info__isnull=False,
                                      is_active=True)
    chapternames = []
    chaptermembers = []
    for chapter in chapters:
        chapternames.append(chapter.slug)
        chaptermembers.append(chapter.members.all().count())

    membershipBreakdownChart = StackedHorizontalBarChart(
        500, 500, x_range=(0, max(chaptermembers)))
    membershipBreakdownChart.add_data(chaptermembers)
    yaxis = range(0, max(chaptermembers), 10)
    yaxis[0] = ''
    membershipBreakdownChart.set_axis_labels(Axis.BOTTOM, yaxis)
    membershipBreakdownChart.set_axis_labels(Axis.LEFT, chapternames)
    membershipBreakdownChart.set_bar_width(330 / len(chapternames))
    membershipBreakdown = membershipBreakdownChart.get_url()

    # ---- Province breakdown ----
    profiletype = ContentType.objects.get_for_model(MemberProfile)
    addresses = Address.objects.filter(content_type=profiletype)
    totalprov = Address.objects.filter(
        content_type=profiletype).count() + 1  # FIXME

    provinces = []
    provincecount = []
    provincelist = list(pycountry.subdivisions.get(country_code='CA'))
    for p in provincelist:
        pcode = p.code.split('-')[1]
        provincecount2 = Address.objects.filter(content_type=profiletype,
                                                province=pcode).count()
        if provincecount2 == 0:
            provincecount2 = 1
        provincecount.append(provincecount2)
        provinces.append(pcode + " (%d%%)" %
                         (provincecount2 * 100 / totalprov))
    #provinces = sorted(provinces)

    provinceBreakdownChart = PieChart3D(600, 240)
    provinceBreakdownChart.add_data(provincecount)

    #provinceBreakdownChart.set_colours(['ff0000', 'ffff00', '00ff00'])
    provinceBreakdownChart.set_pie_labels(provinces)
    provinceBreakdown = provinceBreakdownChart.get_url()

    # ---- Gender breakdown ----
    males = MemberProfile.objects.filter(gender='M').count() + 1
    females = MemberProfile.objects.filter(gender='F').count() + 1
    genderunknown = MemberProfile.objects.filter(
        gender__isnull=True).count() + 1  #FIXME
    gendertotal = males + females + genderunknown
    genderBreakdownChart = PieChart3D(600, 240)
    genderBreakdownChart.add_data([males, females, genderunknown])

    genderBreakdownChart.set_colours(['ff0000', 'ffff00', '00ff00'])
    genderBreakdownChart.set_pie_labels([
        'Male (%d%%)' % (males * 100 / gendertotal),
        'Female (%d%%)' % (females * 100 / gendertotal),
        'Unspecified (%d%%)' % (genderunknown * 100 / gendertotal)
    ])
    genderBreakdown = genderBreakdownChart.get_url()

    # ---- Student breakdown ----
    students = User.objects.filter(
        studentrecord__graduation_date__isnull=True).count() + 1
    nonstudents = User.objects.filter(
        workrecord__end_date__isnull=True).count() + 1
    # yeah, i know, not 100% accurate since a student can have a part-time job
    studentBreakdownChart = PieChart3D(600, 240)
    studentBreakdownChart.add_data([students, nonstudents])

    studentBreakdownChart.set_colours(['ff0000', '00ff00'])
    studentBreakdownChart.set_pie_labels(['Students', 'Non-students'])
    studentBreakdown = studentBreakdownChart.get_url()

    # ---- Language breakdown ----
    preferen = MemberProfile.objects.filter(language='E').count() + 1
    preferfr = MemberProfile.objects.filter(language='F').count() + 1
    prefernone = MemberProfile.objects.filter(
        language__isnull=True).count() + 1
    languageBreakdownChart = PieChart3D(600, 240)
    languageBreakdownChart.add_data([preferen, preferfr, prefernone])

    languageBreakdownChart.set_colours(['ff0000', 'ffff00', '00ff00'])
    languageBreakdownChart.set_pie_labels(
        ['english', 'french', 'not specified'])
    languageBreakdown = languageBreakdownChart.get_url()

    # ---- Post breakdown ----
    postspublic = GroupTopic.objects.filter(
        parent_group__visibility='E',
        parent_group__parent__isnull=True).count() + 1
    postsprivate = GroupTopic.objects.filter(
        parent_group__parent__isnull=True).exclude(
            parent_group__visibility='E').count() + 1
    postspublicchapter = GroupTopic.objects.filter(
        parent_group__visibility='E',
        parent_group__parent__isnull=False).count() + 1
    postsprivatechapter = GroupTopic.objects.filter(
        parent_group__parent__isnull=False).exclude(
            parent_group__visibility='E').count() + 1
    postcount = postspublic + postsprivate + postspublicchapter + postsprivatechapter
    postBreakdownChart = PieChart3D(600, 240)
    postBreakdownChart.add_data(
        [postspublic, postspublicchapter, postsprivatechapter, postsprivate])

    #postBreakdownChart.set_colours(['ff0000', 'ffff00', '00ff00'])
    postBreakdownChart.set_pie_labels(
        ['public', 'public chapter', 'private chapter', 'private'])
    postBreakdown = postBreakdownChart.get_url()

    # ---- Login distribution ----
    logincount = []
    malelogins = []
    femalelogins = []
    for i in range(0, 30):
        logincount.append(
            MemberProfile.objects.filter(login_count__gte=i).count())
        malelogins.append(
            MemberProfile.objects.filter(login_count__gte=i,
                                         gender='M').count())
        femalelogins.append(
            MemberProfile.objects.filter(login_count__gte=i,
                                         gender='F').count())

    loginDistribution = SimpleLineChart(600, 450, y_range=(0, 9000))
    loginDistribution.add_data(logincount)
    loginDistribution.add_data(malelogins)
    loginDistribution.add_data(femalelogins)

    loginDistribution.set_colours(['ff0000', '0000ff', '00ff00'])
    loginDistribution.set_legend(['logins', 'male', 'female'])
    loginDistribution.set_legend_position('b')

    yaxis = range(
        0, 9000,
        500)  # that last number should be 25 or 50.  but for testing...
    yaxis[0] = ''
    loginDistribution.set_axis_labels(Axis.LEFT, yaxis)
    loginDistribution.set_axis_labels(Axis.BOTTOM, range(0, 30))

    loginDistribution = loginDistribution.get_url()

    # ---- Login recency ----
    loginrecent = []
    loginrecentdate = []
    thedate = date(date.today().year - 1, date.today().month, 1)
    skip = False
    while thedate.year != date.today().year or thedate.month != date.today(
    ).month:
        if thedate.month == 12:
            enddate = date(year=thedate.year + 1, month=1, day=1)
        else:
            enddate = date(year=thedate.year, month=thedate.month + 1, day=1)
        loginrecent.append(
            MemberProfile.objects.filter(
                previous_login__range=(thedate, enddate)).count())
        if not skip:
            loginrecentdate.append(thedate.strftime("%B %y"))
        else:
            loginrecentdate.append("")
        skip = not skip
        thedate = enddate

    loginRecency = SimpleLineChart(600, 450, y_range=(0, max(loginrecent) + 1))
    loginRecency.add_data(loginrecent)

    yaxis = range(0, max(loginrecent), max(
        max(loginrecent) / 10,
        1))  # that last number should be 25 or 50.  but for testing...
    if len(yaxis) == 0:
        yaxis.append(10)
        yaxis.append(10)
    yaxis[0] = ''
    loginRecency.set_axis_labels(Axis.LEFT, yaxis)
    loginRecency.set_axis_labels(Axis.BOTTOM, loginrecentdate)

    loginRecency = loginRecency.get_url()

    # ---- Age distribution ----
    ages = []
    for age in range(15, 75):
        year = date.today().year - age
        ages.append(
            MemberProfile.objects.filter(date_of_birth__year=year).count())

    ageDistribution = SimpleLineChart(600, 450, y_range=(0, max(ages) + 1))
    ageDistribution.add_data(ages)

    yaxis = range(0, max(ages) + 1, 50)
    yaxis[0] = ''
    ageDistribution.set_axis_labels(Axis.LEFT, yaxis)
    ageDistribution.set_axis_labels(Axis.BOTTOM, range(15, 75, 5))

    ageDistribution = ageDistribution.get_url()

    # ---- Finally! ----
    return render_to_response(
        "stats/dashboard.html", {
            "signins": today.signins,
            "posts": today.posts,
            "replies": today.replies,
            "signups": today.signups,
            "listsignups": today.mailinglistsignups,
            "listupgrades": today.mailinglistupgrades,
            "deletions": today.deletions,
            "regupgrades": today.regupgrades,
            "regdowngrades": today.regdowngrades,
            "renewals": today.renewals,
            "totalusers": today.users,
            "dailyUsage": dailyUsage,
            "accountChanges": accountChanges,
            "membershipChart": membershipChart,
            "membershipChanges": membershipChanges,
            "statusBreakdown": statusBreakdown,
            "mlistmembers": mlistmembers,
            "mlistmemberspercent": mlistmembers * 100 / today.users,
            "associatemembers": today.associatemembers,
            "associatememberspercent":
            today.associatemembers * 100 / today.users,
            "regularmembers": today.regularmembers,
            "regularmemberspercent": today.regularmembers * 100 / today.users,
            "membershipBreakdown": membershipBreakdown,
            "provinceBreakdown": provinceBreakdown,
            "provincecount": totalprov,
            "genderBreakdown": genderBreakdown,
            "studentBreakdown": studentBreakdown,
            "languageBreakdown": languageBreakdown,
            "postBreakdown": postBreakdown,
            "loginDistribution": loginDistribution,
            "loginRecency": loginRecency,
            "ageDistribution": ageDistribution
        },
        context_instance=RequestContext(request))
예제 #27
0
파일: line.py 프로젝트: willdye/genetify
def simple_random():
    chart = SimpleLineChart(settings.width, settings.height)
    chart.add_data(helper.random_data())
    # chart.download('line-simple-random.png')
    print chart.get_url()
예제 #28
0
    def _line(self, results):
        key = 'count'
        if self.request.GET.get('percentages') == 'true':
            key = 'percentage'
        counts = [x.get(key) for x in results]
        maxcount = max(counts)

        granularity = self.request.GET.get('granularity')
        times = [x.get(granularity) for x in results]

        width = int(self.request.GET.get('width', 575))
        height = int(self.request.GET.get('height', 300))
        chart = SimpleLineChart(width, height, y_range=(0, max(counts)))
        chart.add_data(counts)
        chart.set_line_style(0, thickness=2)  # Set line thickness
        chart.set_colours([
            'E0B300',
        ])
        chart.fill_solid('bg', '00000000')  # Make the background transparent
        chart.set_grid(0, 50, 2, 5)  # Set gridlines

        if self.request.GET.get('granularity') == 'month':
            months = [x['month'] for x in results]
            januaries = [x for x in months if x.endswith('01')]
            january_indexes = [months.index(x) for x in januaries]
            january_percentages = [
                int((x / float(len(months))) * 100) for x in january_indexes
            ]
            index = chart.set_axis_labels(Axis.BOTTOM,
                                          [x[:4] for x in januaries[::2]])
            chart.set_axis_positions(index,
                                     [x for x in january_percentages[::2]])

        if key == 'percentage':
            label = '%.4f' % maxcount
            label += '%'
        else:
            label = int(maxcount)
        index = chart.set_axis_labels(Axis.LEFT, [
            label,
        ])
        chart.set_axis_positions(index, [
            100,
        ])

        if self.request.GET.get('legend', 'true') != 'false':
            chart.set_legend([
                self.request.GET.get('phrase'),
            ])

        return chart.get_url()
예제 #29
0
파일: line.py 프로젝트: Ashwini7/La-resumex
def simple_random():
    chart = SimpleLineChart(settings.width, settings.height, y_range=(0, 100))
    chart.add_data(helper.random_data())
    chart.download('line-simple-random.png')
예제 #30
0
def group(request, group_id):
    group = GroupedMessage.objects.get(pk=group_id)

    message_list = group.message_set.all()

    obj = message_list[0]
    if "__sentry__" in obj.data:
        module, args, frames = obj.data["__sentry__"]["exc"]
        obj.class_name = str(obj.class_name)
        # We fake the exception class due to many issues with imports/builtins/etc
        exc_type = type(obj.class_name, (Exception,), {})
        exc_value = exc_type(obj.message)

        exc_value.args = args

        fake_request = FakeRequest()
        fake_request.META = obj.data.get("META", {})
        fake_request.GET = obj.data.get("GET", {})
        fake_request.POST = obj.data.get("POST", {})
        fake_request.FILES = obj.data.get("FILES", {})
        fake_request.COOKIES = obj.data.get("COOKIES", {})
        fake_request.url = obj.url
        if obj.url:
            fake_request.path_info = "/" + obj.url.split("/", 3)[-1]
        else:
            fake_request.path_info = ""

        reporter = ImprovedExceptionReporter(
            fake_request, exc_type, exc_value, frames, obj.data["__sentry__"].get("template")
        )
        traceback = mark_safe(reporter.get_traceback_html())
    else:
        traceback = mark_safe("<pre>%s</pre>" % (group.traceback,))

    unique_urls = (
        message_list.filter(url__isnull=False)
        .values_list("url", "logger", "view", "checksum")
        .annotate(times_seen=Count("url"))
        .values("url", "times_seen")
        .order_by("-times_seen")
    )

    unique_servers = (
        message_list.filter(server_name__isnull=False)
        .values_list("server_name", "logger", "view", "checksum")
        .annotate(times_seen=Count("server_name"))
        .values("server_name", "times_seen")
        .order_by("-times_seen")
    )

    today = datetime.datetime.now()

    chart_qs = (
        message_list.filter(datetime__gte=today - datetime.timedelta(hours=24))
        .extra(select={"hour": "extract(hour from datetime)"})
        .values("hour")
        .annotate(num=Count("id"))
        .values_list("hour", "num")
    )

    rows = dict(chart_qs)
    if rows:
        max_y = max(rows.values())
    else:
        max_y = 1

    if SimpleLineChart:
        chart = SimpleLineChart(384, 80, y_range=[0, max_y])
        chart.add_data([max_y] * 30)
        chart.add_data([rows.get((today - datetime.timedelta(hours=d)).hour, 0) for d in range(0, 24)][::-1])
        chart.add_data([0] * 30)
        chart.fill_solid(chart.BACKGROUND, "eeeeee")
        chart.add_fill_range("eeeeee", 0, 1)
        chart.add_fill_range("e0ebff", 1, 2)
        chart.set_colours(["eeeeee", "999999", "eeeeee"])
        chart.set_line_style(1, 1)
        chart_url = chart.get_url()

    return render_to_response("sentry/group.html", locals())
예제 #31
0
파일: line.py 프로젝트: Ashwini7/La-resumex
def stripes():
    
    # Set the vertical range from 0 to 100
    max_y = 100

    # Chart size of 200x125 pixels and specifying the range for the Y axis
    chart = SimpleLineChart(200, 125, y_range=[0, max_y])

    # Add the chart data
    data = [
        32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
        37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62, 60, 55,
        55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32
    ]
    chart.add_data(data)
    
    # Set the line colour to blue
    chart.set_colours(['0000FF'])

    # Set the vertical stripes
    chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)

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

    # The Y axis labels contains 0 to 100 skipping every 25, but remove the
    # first number because it's obvious and gets in the way of the first X
    # label.
    left_axis = range(0, max_y + 1, 25)
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)

    # X axis labels
    chart.set_axis_labels(Axis.BOTTOM, \
        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])

    chart.download('line-stripes.png')
예제 #32
0
def fill():

    # Set the vertical range from 0 to 50
    max_y = 50
    chart = SimpleLineChart(200, 125, y_range=[0, max_y])

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

    # 3 sets of real data
    chart.add_data([0, 28, None,None])
    chart.add_data([None, 28, 18,None])
    chart.add_data([None, None, 18,30])

    # Last value is the lowest in the Y axis.
    #chart.add_data([0] * 2)

    # Black lines
    chart.set_colours(["ffc900","d60000","8fb800","d60000","8fb800"])

    # Filled colours
    # from the top to the first real data
    #chart.add_fill_range('76A4FB', 0, 1)

    # Between the 3 data values
    #chart.add_fill_range('224499', 1, 2)
    #chart.add_fill_range('FF0000', 2, 3)

    # from the last real data to the
    #chart.add_fill_range('80C65A', 3, 4)

    # Some axis data
    chart.set_axis_labels(Axis.LEFT, ['', max_y / 2, max_y])
    chart.set_axis_labels(Axis.BOTTOM, ['Sep', 'Oct', 'Nov', 'Dec'])

    chart.download('line-fill.png')
예제 #33
0
def gchart(data,
           node,
           check,
           metric,
           start=datetime.now() - timedelta(days=1),
           end=datetime.now()):
    d = []
    ts = []
    for p in data['metrics'][0]['data']:
        d.append(float(p['avg']))
        ts.append(p['ts'])

    # Chart size of 200x125 pixels and specifying the range for the Y axis
    max_y = int(max(d))
    chart = SimpleLineChart(450, 250, y_range=[0, max_y])
    chart.add_data(d)
    left_axis = range(0, max_y + 1, max_y / 5)
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)
    min_dt = datetime.fromtimestamp(min(ts))
    max_dt = datetime.fromtimestamp(max(ts))
    chart.set_axis_labels(Axis.BOTTOM, [str(min_dt), str(max_dt)])
    title = '%s.%s.%s' % (node['name'], check['type'], metric)
    chart.set_title(title)
    return chart.get_url()
예제 #34
0
def simple_random():
    chart = SimpleLineChart(settings.width, settings.height, y_range=(0, 100))
    chart.add_data(helper.random_data())
    chart.download('line-simple-random.png')
예제 #35
0
def stripes():
    
    # Set the vertical range from 0 to 100
    max_y = 100

    # Chart size of 200x125 pixels and specifying the range for the Y axis
    chart = SimpleLineChart(200, 125, y_range=[0, max_y])

    # Add the chart data
    data = [
        32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
        37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62, 60, 55,
        55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32
    ]
    chart.add_data(data)
    
    # Set the line colour to blue
    chart.set_colours(['0000FF'])

    # Set the vertical stripes
    #chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)

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

    # The Y axis labels contains 0 to 100 skipping every 25, but remove the
    # first number because it's obvious and gets in the way of the first X
    # label.
    left_axis = list(range(0, max_y + 1, 25))
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)

    # X axis labels
    chart.set_axis_labels(Axis.BOTTOM, \
        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])

    chart.download('line-stripes.png')
예제 #36
0
    def _partyline(self, party_results):
        if self.request.GET.get('percentages') == 'true':
            key = 'percentage'
        else:
            key = 'count'

        maxcount = 0
        allcounts = []
        granularity = self.request.GET.get('granularity')
        months = []

        for party, results in party_results.iteritems():
            counts = [x.get(key) for x in results['results']]
            allcounts.append(counts)
            if max(counts) > maxcount:
                maxcount = max(counts)

            if granularity == 'month':
                months = [x['month'] for x in results['results']]
                januaries = [x for x in months if x.endswith('01')]
                january_indexes = [months.index(x) for x in januaries]
                january_percentages = [
                    int((x / float(len(months))) * 100)
                    for x in january_indexes
                ]

            #times = [x.get(granularity) for x in results['results']]

        width = int(self.request.GET.get('width', 575))
        height = int(self.request.GET.get('height', 318))
        chart = SimpleLineChart(width, height, y_range=(0, max(counts)))

        chart.fill_solid('bg', '00000000')  # Make the background transparent
        chart.set_grid(0, 50, 2, 5)  # Set gridlines

        if granularity == 'month':
            index = chart.set_axis_labels(Axis.BOTTOM,
                                          [x[:4] for x in januaries[::2]])
            chart.set_axis_positions(index,
                                     [x for x in january_percentages[::2]])

        if key == 'percentage':
            label = '%.4f' % maxcount
        else:
            label = int(maxcount)
        index = chart.set_axis_labels(Axis.LEFT, [
            label,
        ])
        chart.set_axis_positions(index, [
            100,
        ])

        for n, counts in enumerate(allcounts):
            chart.add_data(counts)
            chart.set_line_style(n, thickness=2)  # Set line thickness

        colors = {
            'R': 'bb3110',
            'D': '295e72',
        }
        chart_colors = []
        chart_legend = []
        for k in party_results.keys():
            chart_colors.append(colors.get(k, '000000'))
            chart_legend.append(k)
            chart.legend_position = 'b'

        chart.set_colours(chart_colors)

        if self.request.GET.get('legend', 'true') != 'false':
            chart.set_legend(chart_legend)
        return chart.get_url()
예제 #37
0
    def get(self):
        counters = tasks.Counter.all().fetch(10)

        rows = [{'name': c.key().name(), 'count': c.count} for c in counters]

        chart = SimpleLineChart(1000, 300)
        for counter in counters:
            query = counter.snapshots
            query.order('-date')
            snapshots = query.fetch(30)
            counts = [s.count for s in snapshots]
            dates = [s.date.strftime("%d/%m") for s in snapshots]
            for i in xrange(len(counts) - 1):
                counts[i] -= counts[i + 1]
            counts.reverse()
            dates.reverse()
            chart.add_data(counts[1:])

        chart.set_axis_labels(pygooglechart.Axis.BOTTOM, dates[1:])
        chart.set_axis_labels(pygooglechart.Axis.LEFT,
                              range(0,
                                    chart.data_y_range()[1], 5))

        hsv_colours = [(float(x) / 255, 1, 1)
                       for x in range(0, 255, 255 / len(counters))]
        rgb_colours = [colorsys.hsv_to_rgb(*x) for x in hsv_colours]
        hex_colours = [
            '%02x%02x%02x' %
            (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255))
            for x in rgb_colours
        ]

        chart.set_colours(hex_colours)
        chart.set_legend([c.key().name() for c in counters])

        path = os.path.join(os.path.dirname(__file__), self.TEMPLATE)
        self.response.out.write(
            template.render(path, {
                'url': chart.get_url(),
                'counters': rows
            }))
예제 #38
0
def draw_plot(data, generation):
    # Set the vertical range from 0 to 100
    max_y = data[0]

    # Chart size of 200x125 pixels and specifying the range for the Y axis
    chart = SimpleLineChart(600, 325, y_range=[0, max_y])

    # Add the chart data
    """
	data = [
	    32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
	    37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62, 60, 55,
	    55, 52, 47, 44, 44, 40, 40, 37, 0,0,0,0,0,0,0
	]
	"""
    chart.add_data(data)

    # Set the line colour to blue
    chart.set_colours(['0000FF'])

    # Set the vertical stripes
    chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)

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

    # The Y axis labels contains 0 to 100 skipping every 25, but remove the
    # first number because it's obvious and gets in the way of the first X
    # label.
    left_axis = range(0, max_y + 1, 25)
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)

    # X axis labels
    chart.set_axis_labels(Axis.BOTTOM,
                          [str(x) for x in xrange(1, generation + 1)][::14])
    chart.download('plot.png')
예제 #39
0
def getRollingAverageGraph(cursor, colName, rollingWindowDays, title=""):
    sqlCMD = "SELECT pDate, %s from %s" % (colName, N.JOBS_SUMMARY_TABLENAME)
    cursor.execute(sqlCMD)
    results = cursor.fetchall()
    beginWindowIndex = 0
    endWindowIndex = 0
    xData = []
    yData = []
    while endWindowIndex < len(results):
        while endWindowIndex < len(results) and (
                results[endWindowIndex][0] -
                results[beginWindowIndex][0]).days <= rollingWindowDays:
            endWindowIndex += 1
        yData.append(
            sum(results[i][1]
                for i in xrange(beginWindowIndex, endWindowIndex, 1)) /
            float(endWindowIndex - beginWindowIndex))
        xData.append(results[endWindowIndex - 1][0])
        beginWindowIndex = endWindowIndex
    chart = SimpleLineChart(680, 400, y_range=(min(yData) - 1, max(yData) + 1))
    chart.add_data(yData)

    yLabels = range(0, int(max(yData) + 1), 5)
    yLabels[0] = ''
    xLabels = [
        str(xData[-i]) for i in xrange(1,
                                       len(xData) - 1, int(0.2 * len(xData)))
    ]
    xLabels.reverse()
    chart.set_axis_labels(Axis.LEFT, yLabels)
    chart.set_axis_labels(Axis.BOTTOM, xLabels)
    chart.set_title("Rolling %i-Day Average %s" % (rollingWindowDays, title))
    imgbin = chart.download()
    toReturn = cStringIO.StringIO(imgbin)
    toReturn.seek(0)
    return chart.get_url(), toReturn
예제 #40
0
    def _plot_line(self, options, args, fh):
        """Plot a line chart"""
        from pygooglechart import Chart, SimpleLineChart, Axis

        delimiter = options.delimiter
        field = options.field - 1

        pts = []
        for l in imap(lambda x: x.strip(), fh):
            splitted_line = l.split(delimiter)
            k = float(splitted_line.pop(field))
            pts.append((k, ' '.join(splitted_line)))

        if options.get('limit', None):
            # Only wanna use top N samples by key, sort and truncate
            pts = sorted(pts, key=itemgetter(0), reverse=True)[:options.limit]

        if not pts:
            raise ValueError("No data to plot")

        max_y = int(max((v for v, label in pts)))
        chart = SimpleLineChart(options.width,
                                options.height,
                                y_range=[0, max_y])

        # Styling
        chart.set_colours(['0000FF'])
        chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)
        chart.set_grid(0, 25, 5, 5)

        data, labels = zip(*pts)
        chart.add_data(data)

        # Axis labels
        chart.set_axis_labels(Axis.BOTTOM, labels)
        left_axis = range(0, max_y + 1, 25)
        left_axis[0] = ''
        chart.set_axis_labels(Axis.LEFT, left_axis)

        return chart
예제 #41
0
def index(request):
    logger_names = SortedDict((l, l) for l in GroupedMessage.objects.values_list("logger", flat=True).distinct())
    server_names = SortedDict((l, l) for l in Message.objects.values_list("server_name", flat=True).distinct())
    level_names = SortedDict((str(k), v) for k, v in LOG_LEVELS)

    logger = request.GET.get("logger")
    server_name = request.GET.get("server_name") or ""
    level = request.GET.get("level") or ""

    try:
        page = int(request.GET.get("p", 1))
    except (TypeError, ValueError):
        page = 1

    realtime = page == 1

    if logger not in logger_names:
        logger = ""

    if server_name not in server_names:
        server_name = ""

    if level not in level_names:
        level = ""

    # this only works in postgres
    message_list = (
        GroupedMessage.objects.filter(status=0)
        .extra(
            select={"score": "times_seen / (pow((floor(extract(epoch from now() - last_seen) / 3600) + 2), 1.25) + 1)"}
        )
        .order_by("-score", "-last_seen")
    )

    today = datetime.datetime.now()

    chart_qs = (
        Message.objects.filter(datetime__gte=today - datetime.timedelta(hours=24))
        .extra(select={"hour": "extract(hour from datetime)"})
        .values("hour")
        .annotate(num=Count("id"))
        .values_list("hour", "num")
    )

    if logger:
        message_list = message_list.filter(logger=logger)
        chart_qs = chart_qs.filter(logger=logger)

    if level:
        message_list = message_list.filter(level=level)
        chart_qs = chart_qs.filter(level=level)

    if server_name:
        message_list = message_list.filter(message_set__server_name=server_name).distinct()
        chart_qs = chart_qs.filter(server_name=server_name)

    rows = dict(chart_qs)
    if rows:
        max_y = max(rows.values())
    else:
        max_y = 1

    if SimpleLineChart:
        chart = SimpleLineChart(384, 80, y_range=[0, max_y])
        chart.add_data([max_y] * 30)
        chart.add_data([rows.get((today - datetime.timedelta(hours=d)).hour, 0) for d in range(0, 24)][::-1])
        chart.add_data([0] * 30)
        chart.fill_solid(chart.BACKGROUND, "eeeeee")
        chart.add_fill_range("eeeeee", 0, 1)
        chart.add_fill_range("e0ebff", 1, 2)
        chart.set_colours(["eeeeee", "999999", "eeeeee"])
        chart.set_line_style(1, 1)
        chart_url = chart.get_url()

    return render_to_response("sentry/index.html", locals())
예제 #42
0
start_marker = [start_x - 4, start_y - 4, start_x + 4, start_y + 4]
topo_draw.ellipse(start_marker, fill="black", outline="white")
# Starting circle
end_lon, end_lat = (lons[-1], lats[-1])
end_x, end_y = world2pixel(end_lon, end_lat, w, h, bbox)
end_point = [end_x - 10, end_y - 10, end_x + 10, end_y + 10]
topo_draw.ellipse(end_point, fill="red", outline="black")
end_marker = [end_x - 4, end_y - 4, end_x + 4, end_y + 4]
topo_draw.ellipse(end_marker, fill="black", outline="white")

# Save the topo map
topo.save("%s_topo.jpg" % osm_img)

# Build the elevation chart using the Google Charts API
log.info("Creating elevation profile chart")
chart = SimpleLineChart(600, 300, y_range=[min(elvs), max(elvs)])

# API quirk -  you need 3 lines of data to color
# in the plot so we add a line at the minimum value
# twice.
chart.add_data([min(elvs)] * 2)
chart.add_data(elvs)
chart.add_data([min(elvs)] * 2)

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

# fill in the elevation area with a hex color
chart.add_fill_range('80C65A', 1, 2)

# Set up labels for the minimum elevation, halfway value, and max value
예제 #43
0
파일: line.py 프로젝트: Ashwini7/La-resumex
def fill():

    # Set the vertical range from 0 to 50
    max_y = 50
    chart = SimpleLineChart(200, 125, y_range=[0, max_y])

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

    # 3 sets of real data
    chart.add_data([28, 30, 31, 33, 35, 36, 42, 48, 43, 37, 32, 24, 28])
    chart.add_data([16, 18, 18, 21, 23, 23, 29, 36, 31, 25, 20, 12, 17])
    chart.add_data([7, 9, 9, 12, 14, 14, 20, 27, 21, 15, 10, 3, 7])

    # Last value is the lowest in the Y axis.
    chart.add_data([0] * 2)

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

    # Filled colours
    # from the top to the first real data
    chart.add_fill_range('76A4FB', 0, 1)

    # Between the 3 data values
    chart.add_fill_range('224499', 1, 2)
    chart.add_fill_range('FF0000', 2, 3)

    # from the last real data to the
    chart.add_fill_range('80C65A', 3, 4)

    # Some axis data
    chart.set_axis_labels(Axis.LEFT, ['', max_y / 2, max_y])
    chart.set_axis_labels(Axis.BOTTOM, ['Sep', 'Oct', 'Nov', 'Dec'])

    chart.download('line-fill.png')
예제 #44
0
    def read(self, request, *args, **kwargs):
        self.request = request
        if kwargs.get('chart_type') == 'timeline':
            handler = PhraseOverTimeHandler()
            if request.GET.get('split_by_party') == 'true':
                resultsets = {}
                for party in [
                        'R',
                        'D',
                ]:
                    kwargs['party'] = party
                    resultsets[party] = handler.read(request, *args, **kwargs)
                return {
                    'results': {
                        'url': self._partyline(resultsets),
                    },
                }

            elif request.GET.get('compare') == 'true':
                phrases = request.GET.get(
                    'phrases', '').split(',')[:5]  # Max of 5 phrases
                parties = request.GET.get('parties', '').split(',')
                states = request.GET.get('states', '').split(',')
                #chambers = request.GET.get('chambers', '').split(',')

                colors = [
                    '8E2844',
                    'A85B08',
                    'AF9703',
                ]

                metadata = []
                legend_items = []
                months = None

                key = 'count'
                if self.request.GET.get('percentages') == 'true':
                    key = 'percentage'

                granularity = self.request.GET.get('granularity')

                width = int(request.GET.get('width', 575))
                height = int(request.GET.get('height', 300))
                chart = SimpleLineChart(width, height)
                chart.set_grid(0, 50, 2, 5)  # Set gridlines
                chart.fill_solid('bg',
                                 '00000000')  # Make the background transparent
                chart.set_colours(colors)
                maxcount = 0

                # Use phrases as a baseline; that is, assume that
                # there's a corresponding value for the other filters.
                # If a filter doesn't have as many values as the number
                # of phrases, the corresponding phrase will not be
                # filtered.
                # (However, if a value is set for 'party' or 'state'
                # in the querystring, that will override any values
                # set in 'phrases' or 'parties.')
                for n, phrase in enumerate(phrases):
                    chart.set_line_style(n, thickness=2)  # Set line thickness

                    if not phrase.strip():
                        continue
                    kwargs['phrase'] = phrase
                    legend = phrase
                    try:
                        kwargs['party'] = parties[n]
                    except IndexError:
                        pass

                    try:
                        kwargs['state'] = states[n]
                    except IndexError:
                        pass

                    if kwargs.get('party') and kwargs.get('state'):
                        legend += ' (%(party)s, %(state)s)' % kwargs
                    elif kwargs.get('party'):
                        legend += ' (%(party)s)' % kwargs
                    elif kwargs.get('state'):
                        legend += ' (%(state)s)' % kwargs

                    legend_items.append(legend)

                    data = handler.read(request, *args, **kwargs)
                    results = data['results']
                    counts = [x.get(key) for x in results]
                    if max(counts) > maxcount:
                        maxcount = max(counts)

                    chart.add_data(counts)
                    metadata.append(kwargs)

                # Duplicated code; should move into separate function.
                if self.request.GET.get('granularity') == 'month':
                    if not months:
                        months = [x['month'] for x in results]
                        januaries = [x for x in months if x.endswith('01')]
                        january_indexes = [months.index(x) for x in januaries]
                        january_percentages = [
                            int((x / float(len(months))) * 100)
                            for x in january_indexes
                        ]
                        index = chart.set_axis_labels(
                            Axis.BOTTOM, [x[:4] for x in januaries[::2]])
                        chart.set_axis_positions(
                            index, [x for x in january_percentages[::2]])

                chart.y_range = (0, maxcount)

                if key == 'percentage':
                    label = '%.4f' % maxcount
                    label += '%'
                else:
                    label = int(maxcount)

                index = chart.set_axis_labels(Axis.LEFT, [
                    label,
                ])
                chart.set_axis_positions(index, [
                    100,
                ])

                # Always include a legend when comparing.
                chart.set_legend(legend_items)

                return {
                    'results': {
                        'metadata': metadata,
                        'url': chart.get_url()
                    }
                }
                #return resultsets

            else:
                data = handler.read(request, *args, **kwargs)
                return {
                    'results': {
                        'url': self._line(data['results']),
                    },
                }

        elif kwargs.get('chart_type') == 'pie':
            handler = PhraseByCategoryHandler()
            kwargs['entity_type'] = request.GET.get('entity_type')
            data = handler.read(request, *args, **kwargs)
            if request.GET.get('output') == 'data':
                return {'data': self._pie(data['results'])}
            return {
                'results': {
                    'url': self._pie(data['results']),
                },
            }

        return {
            'error': 'Invalid chart type.',
        }
예제 #45
0
파일: chart.py 프로젝트: simonwittber/fibra
from pygooglechart import Axis

import timeit
import gc

results = dict()
RANGE = range(0, 100000, 10000)[1:]
for lib in "stacklessb", "fibrab", "kamaeliab":
    results[lib] = eval(open("%s.results"%lib).read())

# Set the vertical range from 0 to 100
max_y = max(max(i) for i in results.values())  * 1.1
print max_y

# Chart size of 200x125 pixels and specifying the range for the Y axis
chart = SimpleLineChart(400, 300, y_range=[0, max_y])

chart.set_colours(['0000FF', "00FF00", "FF0000", "FFFF00"])
print sorted(results.keys())
for k in sorted(results.keys()):
    data = results[k]
    chart.add_data(data)

# Set the vertical stripes
chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)

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

# The Y axis labels contains 0 to 100 skipping every 25, but remove the
# first number because it's obvious and gets in the way of the first X
예제 #46
0
    def GetHtml(self):
        if self.IsEmpty(): return ""

        # Determine top 10 addresses
        top_addresses = \
            [(count, address) for (address, count) in self.__all_addresses.items()]
        top_addresses.sort(reverse=True)
        top_addresses = [address for (count, address) in top_addresses]

        if len(top_addresses) > 10:
            top_addresses = top_addresses[0:10]

        top_addresses.reverse()

        # Collect lines for each address
        bucket_lines = {}

        for bucket in self.__buckets:
            sum = 0
            for address in top_addresses:
                sum += bucket.get(address, 0)

            sum = float(sum)
            fraction_sum = 0

            for address in top_addresses:
                if sum == 0:
                    fraction = 0
                else:
                    fraction = bucket.get(address, 0) / sum

                fraction_sum += fraction

                # Make sure everything adds up to 1.0
                if address == top_addresses[-1]:
                    fraction_sum = 1.0

                if address not in bucket_lines:
                    bucket_lines[address] = []

                bucket_lines[address].append(
                    round(fraction_sum * ExtendedData.max_value()))

        # Smooth lines
        for address, points in bucket_lines.items():
            smoothed = []
            window = []
            window_sum = 0
            for i in xrange(0, len(points)):
                if i < self.__min_bucket or i > self.__max_bucket:
                    smoothed.append(0)
                else:
                    point = points[i]
                    if len(window) == Distribution._BUCKET_SIZE:
                        window_sum -= window.pop(0)
                    window.append(point)
                    window_sum += point
                    smoothed.append(round(window_sum / len(window)))
            bucket_lines[address] = smoothed

        # Generate chart
        chart = SimpleLineChart(450, 250)
        data_index = 0
        colors = []
        legend = []

        top_addresses.reverse()

        for address in top_addresses:
            data = bucket_lines[address]
            chart.add_data(data)

            color = _FILL_COLORS[data_index % len(_FILL_COLORS)]

            chart.add_fill_range(color, data_index, data_index + 1)
            data_index += 1

            colors.append(color)
            legend.append((color, self.__address_names[address], address))

        # Another set of points to make sure we will to the bottom
        chart.add_data([0, 0])

        chart.set_colours(colors)
        chart.set_axis_labels(Axis.BOTTOM, MONTH_NAMES)

        t = Template(
            file="templates/distribution.tmpl",
            searchList={
                "id": self.id,
                "chart": chart,
                # We don't use the legend feature of the chart API since that would
                # make the URL longer than its limits
                "legend": legend,
                "class": self.__css_class,
            })
        return unicode(t)
예제 #47
0
def simple_random():
    chart = SimpleLineChart(300, 100, y_range=(0, 100))
    max_y = 100
    list_data = [10, 90, 80, 10, 10, 20, 30, 20, 15, 45, 56, 42, 92]
    chart.add_data(list_data)
    chart.add_data(reversed(list_data))
    chart.set_axis_labels(Axis.LEFT, ['', max_y / 2, max_y])
    chart.set_axis_labels(Axis.BOTTOM, ['Sep', 'Oct', 'Nov', 'Dec'])
    chart.download('line-simple-random.png')
예제 #48
0
def _line_strip_graph(data,
                      legends,
                      axis_labels,
                      size,
                      steps,
                      type=SimpleLineChart,
                      multiline=False):
    if multiline:
        max_values = []
        min_values = []
        for row in data:
            max_values.append(max(row))
            min_values.append(min(row))
        max_y = max(max_values)
        min_y = min(min_values)
    else:
        max_y = max(data)
        min_y = min(data)

    #validando si hay datos para hacer grafico
    if max_y == 0:
        return None

    chart = SimpleLineChart(size[0], size[1], y_range=[0, max_y * 1.05])

    if multiline:
        for row in data:
            chart.add_data(row)
    else:
        chart.add_data(data)

    step = ((max_y * 1.05) - (min_y * 0.95)) / steps

    #validando en caso de el paso sea menor que uno y de cero en la conversion
    if step < 1:
        step = 1

    tope = int(round(max_value * 1.05))
    if tope < max_value:
        tope += 2
    else:
        tope += 1

    try:
        left_axis = range(int(round(min_y * 0.95)), tope, int(step))
    except ValueError:
        #error por que los range no soportan decimales
        left_axis = range(0, 2)
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_colours(
        ['FFBC13', '22A410', 'E6EC23', '2B2133', 'BD0915', '3D43BD'])

    chart.set_axis_labels(Axis.BOTTOM, axis_labels)
    chart.set_legend(legends)
    chart.set_legend_position('b')

    return chart
예제 #49
0
if csvCount[-1:] == ",":
    csvCount = csvCount[:-1]

if csvDates[-1:] == ",":
    csvDates = csvDates[:-1]

print "CSV dates = " + str(csvDates)
print "CSV count = " + str(csvCount)
print str(startYear) + '-' + str(startMonth).zfill(2) + '-01'
print str(endYear) + '-' + str(endMonth).zfill(2) + '-01'

#Generate graph
max_y = 300

chart = SimpleLineChart(500, 500, y_range=[0, max_y])

chart.add_data(count)

# Set the line colour to blue
chart.set_colours(['0000FF'])

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

# The Y axis labels contains 0 to the max skipping every 25, but remove the
# first number because it's obvious and gets in the way of the first X
# label.
left_axis = list(range(0, max_y + 1, 25))
left_axis[0] = ''
chart.set_axis_labels(Axis.LEFT, left_axis)
예제 #50
0
def main():
     size_limit = 3000 * 100;
     x_size = 1000
     y_size = 300
     y_max = 100
     
     parser = OptionParser()
     parser.add_option("-f", "--file", dest="filename",
                       help="input data file")
     parser.add_option("-o", "--output", dest="chartname",
                       help="output chart file")
     parser.add_option("-s", "--size", dest="size",
                       help="'xsize,ysize' length of the chart x*y<=%d" % size_limit)
     parser.add_option("-y", "--y-max", dest="y_max",
                       help="y max limit")
     (options, args) = parser.parse_args(sys.argv[1:])          
     if (options.filename == None or options.chartname == None):
          parser.print_help()
          sys.exit(1)
     # init x,y size
     if (options.size):
          size = options.size
          xy_pair = size.split(",")
          if len(xy_pair) == 2:
               x_size = string.atoi(xy_pair[0])
               y_size = string.atoi(xy_pair[1])
          else :
               parser.print_help()
               sys.exit(1)
     if (x_size * y_size > size_limit):
          print("ERROR: x*y > %s" % size_limit)
          sys.exit(1)

     # init y range
     if (options.y_max):
          y_max = string.atoi(options.y_max)
               
     # input file section
     ifile = open(options.filename)
     while True:
          l = ifile.readline()
          if len(l) == 0:
               break
          # print("get line: %s" % l[:-1])
     data = [
          32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
          37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62, 60, 55,
          55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32
          ]
     data2 = [
          55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32, 62, 60, 55,
          32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,        
          37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62
          ]
     data_list = [data, data2]
     # output file section
     chart = SimpleLineChart(x_size, y_size, y_range=[0, y_max])
     # set data
     for d in data_list:
          chart.add_data(d)
        # init color
     RR=16; GG=16; BB=16
     color_list = []
     for i in range(len(data_list)):
          RR+=10;GG+=15;BB+=65
          color_list.append("%s%s%s" %
                            (str(hex(RR%255))[2:],
                             str(hex(GG%255))[2:],
                             str(hex(BB%255))[2:]) )
     # print(color_list)
     chart.set_colours(color_list)
     chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)
     chart.set_grid(0, 25, 5, 5)
     # left_axis = range(0, y_max+1, 25)
     # left_axis[0] = ""
     chart.set_axis_labels(Axis.LEFT, ["","25%","50%","75%","100%"])
     chart.set_axis_labels(Axis.BOTTOM, ["0:00", "3:00", "6:00", "9:00", "12:00", "15:00", "18:00", "21:00", "24:00"])
    
     chart.download(options.chartname)
# Starting circle

end_lon, end_lat = (lons[-1], lats[-1])
end_x, end_y = world2pixel(end_lon, end_lat, w, h, bbox)
end_point = [end_x-10, end_y-10, end_x+10, end_y+10]
topo_draw.ellipse(end_point, fill="red", outline="black")
end_marker = [end_x-4, end_y-4, end_x+4, end_y+4]
topo_draw.ellipse(end_marker, fill="black", outline="white")

# Save the topo map
topo.save("{}_topo.jpg".format(osm_img))

# Build the elevation chart using the Google Charts API
log.info("Creating elevation profile chart")
chart = SimpleLineChart(600, 300, y_range=[min(elvs), max(elvs)])

# API quirk -  you need 3 lines of data to color
# in the plot so we add a line at the minimum value
# twice.
chart.add_data([min(elvs)]*2)
chart.add_data(elvs)
chart.add_data([min(elvs)]*2)

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

# fill in the elevation area with a hex color
chart.add_fill_range('80C65A', 1, 2)

# Set up labels for the minimum elevation, halfway value, and max value
예제 #52
0
def group_post_activity(request, group_slug):
    group = get_object_or_404(BaseGroup, slug=group_slug)

    postcount = []
    replycount = []
    allcount = []
    listdate = []
    thedate = date(date.today().year - 1, date.today().month, 1)
    skip = False
    while thedate.year != date.today().year or thedate.month != date.today(
    ).month:
        if thedate.month == 12:
            enddate = date(year=thedate.year + 1, month=1, day=1)
        else:
            enddate = date(year=thedate.year, month=thedate.month + 1, day=1)
        posts = GroupTopic.objects.filter(parent_group=group,
                                          created__range=(thedate,
                                                          enddate)).count()
        #replies = ThreadedComment.objects.filter(content_object__parent_group=group,
        #                                         date_submitted__range=(thedate, enddate)).count()
        replies = 0
        postcount.append(posts)
        replycount.append(replies)
        allcount.append(posts + replies)
        if not skip:
            listdate.append(thedate.strftime("%B %y"))
        else:
            listdate.append("")
        skip = not skip
        thedate = enddate

    postactivity = SimpleLineChart(
        600,
        450,
        y_range=(min(min(postcount), min(replycount)),
                 max(max(postcount), max(replycount)) + 1))
    postactivity.add_data(postcount)
    postactivity.add_data(replycount)
    postactivity.add_data(allcount)

    yaxis = range(min(min(postcount), min(replycount)),
                  max(max(postcount), max(replycount)) + 1, 1)
    if len(yaxis) < 2:
        yaxis.append(1)
    yaxis[0] = ''
    postactivity.set_axis_labels(Axis.LEFT, yaxis)
    postactivity.set_axis_labels(Axis.BOTTOM, listdate)

    postactivity.set_colours(['ff0000', '0000ff', '00ff00'])
    postactivity.set_legend(['posts', 'replies', 'total'])
    postactivity.set_legend_position('b')

    return postactivity.get_url()
예제 #53
0
def cat_proximity():
    """Cat proximity graph from http://xkcd.com/231/"""
    chart = SimpleLineChart(int(settings.width * 1.5), settings.height)
    chart.set_legend(['INTELLIGENCE', 'INSANITY OF STATEMENTS'])

    # intelligence
    data_index = chart.add_data([100. / y for y in xrange(1, 15)])

    # insanity of statements
    chart.add_data([100. - 100 / y for y in xrange(1, 15)])

    # line colours
    chart.set_colours(['208020', '202080'])

    # "Near" and "Far" labels, they are placed automatically at either ends.
    near_far_axis_index = chart.set_axis_labels(Axis.BOTTOM, ['FAR', 'NEAR'])

    # "Human Proximity to cat" label. Aligned to the center.
    index = chart.set_axis_labels(Axis.BOTTOM, ['HUMAN PROXIMITY TO CAT'])
    chart.set_axis_style(index, '202020', font_size=10, alignment=0)
    chart.set_axis_positions(index, [50])

    chart.download('label-cat-proximity.png')
예제 #54
0
    def create_graph(self, particle_data, time_data):
        # Set the vertical range from 0 to 2
        max_y = 2

        # Chart size of 500x500 pixels and specifying the range for the Y axis
        chart = SimpleLineChart(500, 500, y_range=[0, max_y])

        # Add the chart data
        data = particle_data

        chart.add_data(data)

        # Set the line color blue
        chart.set_colours(['0000FF'])

        # Set the vertical stripes
        chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)

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

        # The Y axis labels
        left_axis = ['0.25', '0.5', '0.75', '1']
        left_axis[0] = ''
        chart.set_axis_labels(Axis.LEFT, left_axis)
        left_axis2 = "Proton Flux"[::-1]
        chart.set_axis_labels(Axis.LEFT, left_axis2)

        # X axis labels
        chart.set_axis_labels(Axis.BOTTOM, time_data[0:3][::-1])
        chart.set_axis_labels(Axis.BOTTOM, "Time")

        chart.download('chart.png')
        return True
def RenderGoogleChart(data, filename):    
    """
    create a GoogleChart from decoded data under filename (.png)
    """
    print "Rendering GoogleChart [%s]" % filename
    # Retrieve chart data
    elements=[]
    max_y = 0
    min_y = 9999
    for i in range(len(data["time"])):
        if data["cps"][i] > max_y: max_y = data["cps"][i]
        if data["cps"][i] < min_y: min_y = data["cps"][i]
        elements.append(data["cps"][i])

    # Chart size of 600x375 pixels and specifying the range for the Y axis
    chart = SimpleLineChart(600, 375, y_range=[min_y-0.1, max_y+0.1])
    
    # Add the chart data
    chart.add_data(elements)
    
    # Set the line colour to blue
    chart.set_colours(['0000FF'])

    # Set the vertical stripes
    chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)

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

    # Define the Y axis labels
    left_axis = [x * 0.1 for x in range(0, int(max_y/0.1))]
    left_axis[0] = 'CPS'
    chart.set_axis_labels(Axis.LEFT, left_axis)

    chart.download(filename)
예제 #56
0
def generate_mon_chart(mon_counts_1, mon_counts_2):
    """Generates a line graph plotting articles per month.

    Returns the url to a Google Chart showing the article counts in 
    mon_counts_1 vs. those in mon_counts_2.
    """
    # Get the first three letters of the calendar month names
    x_axis = [name[:3] for name in calendar.month_name][1:]
    min_y = min(mon_counts_1 + mon_counts_2)
    max_y = max(mon_counts_1 + mon_counts_2)
    step_y = ((max_y - min_y + 1) / 14) + 1
    y_axis = range(min_y, max_y, step_y)

    chart = SimpleLineChart(CHART_WIDTH, CHART_HEIGHT, y_range=[min_y, max_y])
    chart.add_data(mon_counts_1)
    chart.add_data(mon_counts_2)
    chart.set_colours([LINE_COLOR_1, LINE_COLOR_2])
    chart.set_axis_labels(Axis.BOTTOM, x_axis)
    chart.set_axis_labels(Axis.LEFT, y_axis)
    chart.set_line_style(0, thickness=LINE_THICKNESS)
    chart.set_line_style(1, thickness=LINE_THICKNESS)

    return chart.get_url()
예제 #57
0
from pygooglechart import Chart
from pygooglechart import SimpleLineChart
from pygooglechart import Axis

# Set the vertical range from 0 to 100
max_y = 100

# Chart size of 200x125 pixels and specifying the range for the Y axis
chart = SimpleLineChart(200, 125, y_range=[0, max_y])

# Add the chart data
data = [
    32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37,
    37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62, 60, 55,
    55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32
]
chart.add_data(data)

# Set the line colour to blue
chart.set_colours(['0000FF'])

# Set the vertical stripes
chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2)

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

# The Y axis labels contains 0 to 100 skipping every 25, but remove the
# first number because it's obvious and gets in the way of the first X
# label.
left_axis = range(0, max_y + 1, 25)
예제 #58
0
파일: grafos.py 프로젝트: fitoria/mcas
def _line_strip_graph(data, legends, axis_labels, size, steps, 
                           type=SimpleLineChart, multiline=False, **kwargs):
    if multiline:
        max_values = []
        min_values = [] 
        for row in data:
            max_values.append(max(row))
            min_values.append(min(row))
        max_y = max(max_values)
        min_y = min(min_values)
    else:
        max_y = max(data)
        min_y = min(data)
    
    #validando si hay datos para hacer grafico
    if max_y==0:
        return None

    chart = SimpleLineChart(size[0], size[1], y_range=[0, max_y*1.05])

    if multiline:
        for row in data:
            chart.add_data(row)
    else:
        chart.add_data(data)
    
    step = ((max_y*1.05)-(min_y*0.95))/steps

    #validando en caso de el paso sea menor que uno y de cero en la conversion
    if step<1:
        step = 1
    
    max_value = max_y
    tope = int(round(max_value*1.05))
    if tope < max_value:
        tope+=2
    else:
        tope+=1

    try:
        left_axis = range(int(round(min_y*0.95)), tope, int(step))
    except ValueError:
        #error por que los range no soportan decimales
        left_axis = range(0, 2)
    left_axis[0]=''

    chart.set_axis_range(Axis.LEFT, min_y, tope)
    if 'units' in kwargs:
        chart.set_axis_labels(Axis.LEFT, kwargs['units'])

    if 'time' in kwargs:
        chart.set_axis_labels(Axis.BOTTOM, kwargs['time'])

    chart.set_grid(0, 25, 4, 4,)
    chart.chls=4|4
    #chart.fill_linear_stripes(Chart.CHART, 0, 'FFFFEF', 0.2, 'FFFFFF', 0.2)
    chart.set_colours(COLORS)

    if axis_labels:
        chart.set_axis_labels(Axis.BOTTOM, axis_labels)
    chart.set_legend(legends)
    chart.set_legend_position('b')

    if 'thickness' in kwargs:
        if multiline:
            for i in range(len(data)):
                chart.set_line_style(index = i, thickness=kwargs['thickness'])
        else:
            chart.set_line_style(index=0, thickness=kwargs['thickness'])

    return chart