コード例 #1
0
    def get(self):
        list = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep']
        list2 = []
        for title in list:
            list2.append(int(getdata(title, 'funds').custom['amount'].text))
        max_y = 10000
        chart = SimpleLineChart(200, 125, y_range=[0, max_y])

        chart.add_data([2000, 3000, 5000, 1200, 5000, 4000, 1000, 3000, 5900])

        # 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, list)

        url2 = chart.get_url()
        self.response.out.write(
            template.render('template/donate.html', {
                'url2': url2,
            }))
コード例 #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 velocity_chart(self):

        graph_width = 600
        graph_height = 300

        x_max = self.total_iterations
        y_max = max(max(self.estimate_stories_data()),
                    max(self.estimate_tasks_data()), max(self.work_data()))

        chart = SimpleLineChart(graph_width,
                                graph_height,
                                x_range=(1, x_max + 1),
                                y_range=(0, y_max + 1))

        chart.add_data(self.estimate_stories_data())
        chart.add_data(self.estimate_tasks_data())
        chart.add_data(self.work_data())

        chart.set_grid(0, 100.0 / y_max + 1, 5, 5)
        chart.set_colours(['FF0000', '00FF00', '0000FF'])
        chart.set_legend(
            [_('rough story estimates'),
             _('task estimates'),
             _('worked')])
        chart.set_legend_position('b')
        chart.set_axis_labels(Axis.LEFT, ['', '', _('days')])
        chart.set_axis_labels(Axis.BOTTOM, list(range(1, x_max + 1)))
        chart.set_axis_range(Axis.LEFT, 0, y_max + 1)

        return chart.get_url(data_class=ExtendedData)
コード例 #4
0
ファイル: views.py プロジェクト: texastribune/django-sentry
def group(request, group_id):
    group = get_object_or_404(GroupedMessage, pk=group_id)

    message_list = group.message_set.all()
    
    obj = message_list.order_by('-id')[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
    
        reporter = ImprovedExceptionReporter(obj.request, exc_type, exc_value, frames, obj.data['__sentry__'].get('template'))
        traceback = mark_safe(reporter.get_traceback_html())
    elif group.traceback:
        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')

    def iter_data(obj):
        for k, v in obj.data.iteritems():
            if k.startswith('_') or k in ['url']:
                continue
            yield k, v
    
    json_data = iter_data(obj)
    
    # TODO: this should be a template tag
    engine = get_db_engine()
    if SimpleLineChart and not engine.startswith('sqlite'):
        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

        chart = SimpleLineChart(300, 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/details.html', locals())
コード例 #5
0
ファイル: views.py プロジェクト: adamgreig/isatracker
def show(request, isa_id):
    isa = get_object_or_404(ISA, pk=isa_id)
    isafunds = isa.isafund_set.all()
    start_date = isa.created
    end_date = date.today()
    current_date = start_date
    data = []
    while current_date <= end_date:
        value = 0
        for isafund in isafunds:
            try:
                fundprice = isafund.fund.fundprice_set.get(date=current_date)
                value += fundprice.price * isafund.quantity
            except FundPrice.DoesNotExist:
                pass
        data.append(value)
        current_date += timedelta(1)
    chart = SimpleLineChart(500, 200, y_range=[min(data), max(data)])
    chart.add_data(data)
    chart.add_data([data[0], data[0]])
    chart.set_colours(['0000FF', 'AAAAAA'])
    chart.fill_solid('bg', 'DDDDFF')
    chart.set_axis_labels(Axis.LEFT, [int(min(data)), int(max(data))])
    chart.set_axis_labels(Axis.BOTTOM, [start_date, end_date])
    url = chart.get_url()
    return render_to_response('isas/show.html', {'isa': isa, 'chart_url': url})
コード例 #6
0
ファイル: views.py プロジェクト: mclabs/rapidsms
def enterprises_graph(num_days=14):
	chart_name="enterprises.png"
	# its a beautiful day
	today = datetime.today().date()

	# step for x axis
	step = timedelta(days=1)

	# empties to fill up with data
	counts = []
	dates = []

	# only get last two weeks of entries 
	day_range = timedelta(days=num_days)
	entries = Enterprise.objects.filter(
			created_at__gt=(today	- day_range))
	
	# count entries per day
	for day in range(num_days):
		count = 0
		d = today - (step * day)
		for e in entries:
			if e.created_at.day == d.day:
				count += 1
		dates.append(d.day)
		counts.append(count)
    
    	line = SimpleLineChart(440, 100, y_range=(0, 100))
	line.add_data(counts)
	line.set_axis_labels(Axis.BOTTOM, dates)
	line.set_axis_labels(Axis.BOTTOM, ['','Date', ''])
	line.set_axis_labels(Axis.LEFT, ['', 5, 10])
	line.set_colours(['0091C7'])
	line.download('apps/shabaa/static/graphs/' + chart_name)
	return chart_name
コード例 #7
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 }))
コード例 #8
0
 def get(self):
     list = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep']
     list2 = []
     for title in list:
         list2.append( int(getdata(title,'funds').custom['amount'].text))
     max_y = 10000
     chart = SimpleLineChart(200, 125, y_range=[0, max_y])
     
     chart.add_data([2000,3000,5000,1200,5000,4000,1000,3000,5900])
     
     # 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, list)
     
     url2 = chart.get_url()
     self.response.out.write(template.render('template/donate.html',{
                                             
                                                              'url2' :url2,                }))
コード例 #9
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
コード例 #10
0
ファイル: dicechart.py プロジェクト: winks/dicebreaker
class DiceChart:
    chart = None

    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)

    def download(self, name="dicechart.png"):
        self.chart.download(name)
コード例 #11
0
ファイル: views.py プロジェクト: notthatbreezy/Capitol-Words
    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()
コード例 #12
0
def simpleChart3(bottom_labels, data1, data2):
    datamin, datamax = min(min(data1, data2)), max(max(data1, data2))
    datamin = int(datamin - 0.5)
    datamax = int(datamax + 0.5)
    chart = SimpleLineChart(200, 125, y_range=[datamin, datamax])
    chart.add_data(data1)
    chart.add_data(data2)

    left_axis = [datamin, 0, datamax]

    left_axis[0] = ''  # no label at 0
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_axis_labels(Axis.BOTTOM, bottom_labels)
    chart.set_axis_labels(Axis.BOTTOM,
                          ['X Axis'])  # second label below first one
    chart.set_axis_positions(
        2, [50.0])  # position, left is 0., right is 100., 50. is center

    # Set the line colour
    chart.set_colours(['0000FF', 'FF0000'])

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

    # Set vertical stripes
    stripes = ['CCCCCC', 0.2, 'FFFFFF', 0.2]
    chart.fill_linear_stripes(Chart.CHART, 0, *stripes)
    return chart
コード例 #13
0
def simpleChart2(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 = ['min', 0, 'max']
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_axis_labels(Axis.BOTTOM, bottom_labels)
    chart.set_axis_labels(Axis.BOTTOM,
                          ['X Axis'])  # second label below first one
    chart.set_axis_positions(
        2, [50.0])  # position, left is 0., right is 100., 50. is center

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

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

    # Set vertical stripes
    stripes = ['CCCCCC', 0.2, 'FFFFFF', 0.2]
    chart.fill_linear_stripes(Chart.CHART, 0, *stripes)
    return chart
コード例 #14
0
ファイル: graphop.py プロジェクト: Jlewiswa/Twitter100k
def getLineGraph(data,line1color,line2color):
    # Set the vertical range based on data values
    tweets = [d[0] for d in data]
    retweets = [d[1] for d in data]
    ratio = [str(int(d[1]/d[0]*100))+'%' for d in data]
    hours = [d[2] for d in data]
    mx = max(tweets)
    mn = min(retweets)
    buffer = (mx - mn)/100 # average retweets have consitently been less
    min_y = mn - buffer
    max_y = mx + buffer

    # Chart size of 750x400 pixels and specifying the range for the Y axis
    chart = SimpleLineChart(750, 400, y_range=[min_y, max_y])
    chart.set_legend(['Tweets','Retweets'])
    chart.set_legend_position('t')
    # Add the chart data
    chart.add_data(tweets)
    chart.add_data(retweets)
    # Set the line colour to blue
    chart.set_colours([line1color,line2color])

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

    #set left axis to values range
    left_axis = range(min_y, max_y, (max_y-min_y)/10)
    chart.set_axis_labels(Axis.BOTTOM, hours)
    chart.set_axis_labels(Axis.BOTTOM, ratio)
    chart.set_axis_labels(Axis.LEFT, left_axis)
    return chart.get_url()
コード例 #15
0
ファイル: views.py プロジェクト: adammck/plumpynut
def graph_entries(num_days=14):
	# its a beautiful day
	today = datetime.today().date()

	# step for x axis
	step = timedelta(days=1)

	# empties to fill up with data
	counts = []
	dates = []

	# only get last two weeks of entries 
	day_range = timedelta(days=num_days)
	entries = Entry.objects.filter(
			time__gt=(today	- day_range))
	
	# count entries per day
	for day in range(num_days):
		count = 0
		d = today - (step * day)
		for e in entries:
			if e.time.day == d.day:
				count += 1
		dates.append(d.day)
		counts.append(count)
    
    	line = SimpleLineChart(440, 100, y_range=(0, 100))
	line.add_data(counts)
	line.set_axis_labels(Axis.BOTTOM, dates)
	line.set_axis_labels(Axis.BOTTOM, ['','Date', ''])
	line.set_axis_labels(Axis.LEFT, ['', 50, 100])
	line.set_colours(['0091C7'])
	line.download('webui/graphs/entries.png')
	
	return 'saved entries.png' 
コード例 #16
0
    def velocity_chart(self):

        graph_width = 600
        graph_height = 300

        x_max = self.total_iterations
        y_max = max(max(self.estimate_stories_data()),
                    max(self.estimate_tasks_data()),
                    max(self.work_data()))

        chart = SimpleLineChart(graph_width, graph_height,
                                x_range=(1, x_max + 1), y_range=(0, y_max + 1))

        chart.add_data(self.estimate_stories_data())
        chart.add_data(self.estimate_tasks_data())
        chart.add_data(self.work_data())

        chart.set_grid(0, 100.0 / y_max + 1, 5, 5)
        chart.set_colours(['FF0000', '00FF00', '0000FF'])
        chart.set_legend([_('rough story estimates'),
                          _('task estimates'), _('worked')])
        chart.set_legend_position('b')
        chart.set_axis_labels(Axis.LEFT, ['', '', _('days')])
        chart.set_axis_labels(Axis.BOTTOM, range(1, x_max + 1))
        chart.set_axis_range(Axis.LEFT, 0, y_max + 1)

        return chart.get_url(data_class=ExtendedData)
コード例 #17
0
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)
コード例 #18
0
def simpleChart3(bottom_labels, data1, data2):
    datamin, datamax = min(min(data1, data2)), max(max(data1, data2))
    datamin = int(datamin - 0.5)
    datamax = int(datamax + 0.5)
    chart = SimpleLineChart(200, 125, y_range=[datamin, datamax])
    chart.add_data(data1)
    chart.add_data(data2)
    
    left_axis = [datamin,0,datamax]

    left_axis[0] = '' # no label at 0
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_axis_labels(Axis.BOTTOM, bottom_labels)
    chart.set_axis_labels(Axis.BOTTOM, ['X Axis']) # second label below first one
    chart.set_axis_positions(2, [50.0]) # position, left is 0., right is 100., 50. is center

    # Set the line colour
    chart.set_colours(['0000FF', 'FF0000'])

    # Set the horizontal dotted lines
    chart.set_grid(0, 25, 5, 5)
    
    # Set vertical stripes
    stripes = ['CCCCCC', 0.2, 'FFFFFF', 0.2]
    chart.fill_linear_stripes(Chart.CHART, 0, *stripes)
    return chart
コード例 #19
0
    def get_chart_image(self, data, **kw):
        """Return a image file path

        Arguments::

            data -- a list containing the X,Y data representation
        """
        from pygooglechart import SimpleLineChart, Axis

        # Set the vertical range from 0 to 100
        try:
            max_y = max(data['y'])
            min_y = min(data['y'])
        except:
            min_y = 0
            max_y = 100
        width = int(kw.get('width', 600))
        height = int(kw.get('height', 250))
        # Chart size of widthxheight pixels and specifying the range for the Y axis
        chart = SimpleLineChart(width, height, y_range=[0, max_y])

        # Add the chart data
        chart.add_data(data['y'])

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

        try:
            step_x = int(100/(len(data['x'])-1))
        except:
            step_x = 0
        chart.set_grid(step_x, 10, 5, 5)

        # The Y axis labels contains min_y to max_y spling it into 10 equal parts,
        #but remove the first number because it's obvious and gets in the way
        #of the first X label.
        left_axis = [utils.intcomma(x) for x in range(0, max_y + 1, (max_y)/10)]
        left_axis[0] = ''
        chart.set_axis_labels(Axis.LEFT, left_axis)

        # X axis labels
        chart.set_axis_labels(Axis.BOTTOM, data['x'])

        #Generate an hash from arguments
        kw_hash = hash(tuple(sorted(kw.items())))
        data_hash = hash(tuple(sorted([(k, tuple(v))
            for k, v in data.iteritems()])))
        args_hash = str(kw_hash) + str(data_hash)

        image_path = os.path.join(TARGET_DIR, "%s.png" % args_hash)

        if bool(kw.get('refresh', False)) or args_hash not in self.charts:
            #Get image from google chart api
            chart.download(image_path)
            if args_hash not in self.charts:
                self.charts.append(args_hash)
            self._p_changed = True

        return image_path
コード例 #20
0
ファイル: grafos.py プロジェクト: molivera7/suco_proga
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
コード例 #21
0
ファイル: bar.py プロジェクト: iqmaker/smalltools
def simple_line():
    chart = SimpleLineChart(settings.width, settings.height,
                                      x_range=(0, 35))
    chart.set_colours(['00ff00', 'ff0000','ACff0C','B0ffE0','C0ffFF'])
    chart.add_data([1,2,3,4,5])
    chart.add_data([1,4,9,16,25])
    chart.set_title('This is title')
    chart.set_axis_labels('r', 'str')
    chart.set_legend( ['a','b','c','d','e'])
    chart.download('simple-line.png')
コード例 #22
0
ファイル: getFeed.py プロジェクト: daneroo/im-ted1k
def lineGraphFeed(feed):
    name = feed.getAttribute("name")
    observations = feed.getElementsByTagName("observation")
    print "  Feed %s has %d observations" % (name,len(observations))
    data = []
    for obs in observations:
        value = int(obs.getAttribute("value"))
        #print "   val:%s (%s)" % (value, type(value))
        data.insert(0,value/10)

    #data.reverse  # remeber the feed is reversed
    print "Max Data: %s" % max(data)

    max_y = int(math.ceil(max(data)/100.0))*100
    print "Max_y : %s" % max_y
    chart = SimpleLineChart(180, 120, y_range=[0, max_y])
    chart.add_data(data)

    lftAxisMax = max_y/100;
    print "lftAxisMax %s"%lftAxisMax
    #left_axis = range(0, lftAxisMax,(lftAxisMax/4.0))
    left_axis = []
    right_axis = []
    for i in range(0,4+1):
        kw = (i*lftAxisMax/4.0)
        left_axis.append(kw)
        right_axis.append(kw*24)

    left_axis[0] = 'kW' # remove the first label
    right_axis[0] = 'kWh/d' # remove the first label
    chart.set_axis_labels(Axis.LEFT, left_axis)
    #chart.set_axis_labels(Axis.RIGHT, right_axis)

    chart.set_title(name)

    # facebook colors
    chart.set_title_style('7f93bc',16)
    #chart.set_colours(['7f93bc'])
    chart.set_colours(['3b5998']) #darker blue

    #Colors
    colors=False
    if (colors):
        # Set the line colour to ...
        chart.set_colours(['FFFFFF'])
        # 0 here is the axis index ? 0 works for now
        chart.set_title_style('FFFFFF',16)
        chart.set_axis_style(0,'FFFFFF')
        chart.set_axis_style(1,'FFFFFF')
        chart.fill_linear_gradient(Chart.BACKGROUND,90,'000000',0.9,'007700',0.1)


    print chart.get_url()
    chart.download('%s-line.png'%name)
コード例 #23
0
ファイル: charts.py プロジェクト: esbenson/pbearfrfeed
def generate_freq_chart_url_from_qset(qset, sizex, sizey):
    ''' returns url for chart from given queryset '''
    
    end_year = qset.order_by('-publication_date')[0].publication_date.year
    start_year = qset.order_by('publication_date')[0].publication_date.year
    #print "start {0}, end {1}".format(start_year, end_year)

    year_range=range(start_year,end_year + 1)
    month_range=range(1, 13)
    count_rules = []
    count_proprules = []
    count_notices = []
    count_presdocs = []
    count_unknown = []
    count_total = []
    today = datetime.date.today()    
        
    for y in year_range:
        start_date=datetime.date(y,1,1)
        end_date=datetime.date(y,12,31)
        year_qset = qset.filter(publication_date__range=(start_date, end_date))
        count_rules.append(year_qset.filter(document_type='Rule').count())
        count_proprules.append(year_qset.filter(document_type='Proposed Rule').count())
        count_notices.append(year_qset.filter(document_type='Notice').count())
        count_presdocs.append(year_qset.filter(document_type='Presidential Document').count())
        count_unknown.append(year_qset.filter(document_type='Document of Unknown Type').count())
        count_total.append(count_unknown[-1] + count_presdocs[-1] + count_rules[-1] + count_proprules[-1] + count_notices[-1])
    #for i in [count_rules, count_proprules, count_notices, count_presdocs, count_unknown, count_total]:
        #print i

    # set up chart axis parameters
    largest_y = max(count_total)
    left_axis_step = int(pow(10, int(log10(largest_y)))) 
    max_y = (int(largest_y / left_axis_step) * left_axis_step) + (left_axis_step * 2)
    left_axis = range(0, max_y + left_axis_step, left_axis_step)
    left_axis[0] = ""
    bottom_axis = year_range

    # generate chart url
    chart = SimpleLineChart(sizex, sizey, y_range=[0, max_y])
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_axis_labels(Axis.BOTTOM, bottom_axis)
    chart.set_grid(0, max(10, int(left_axis_step / 10)), 5, 5)
    chart.set_colours(['0000FF', '00FF00', 'FF0000', 'FFFF00', '00FFFF', 'aaaaaa'])
    chart.set_legend(['Rules', 'Proposed Rules', 'Notices', 'Presidential Docs', 'Unknown', 'Total'])
    chart.add_data(count_rules)
    chart.add_data(count_proprules)
    chart.add_data(count_notices)
    chart.add_data(count_presdocs)
    chart.add_data(count_unknown)
    chart.add_data(count_total)
    chart_url = chart.get_url()
       
    return chart_url
コード例 #24
0
ファイル: views.py プロジェクト: tanveerahmad1517/myewb2
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()
コード例 #25
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
コード例 #26
0
ファイル: views.py プロジェクト: alexnjoyce/myewb2
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()
コード例 #27
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()
コード例 #28
0
ファイル: search.py プロジェクト: GunioRobot/nyt-trender
	def get(self):
		query1 = self.request.get('query1');
		query2 = self.request.get('query2');
		if query2 == '':
			 query2 = query1;
		self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
		self.response.out.write(HTML_TEMPLATE % {'query1' : query1.replace('"','&quot;'), 'query2' : query2.replace('"','&quot;')})
		if query1 != None and query2 != None:
			year_07 = '%s publication_year:[2008]' %  query1
			year_08 = '%s publication_year:[2008]' %  query2
			results7 = search(year_07)
			results8 = search(year_08)
			data7 = extract(results7)
			data8 = extract(results8)
			if sum(data8) == 0:
				data8 = [1] * 12
			big = max(data7 + data8)
			small = min(data7 + data8)
			chart = SimpleLineChart(600,400,y_range=[ small, big])
			chart.add_data(data7)
			chart.add_data(data8)
			chart.set_colours(['207000','0077A0'])
			chart.set_axis_labels(Axis.LEFT,range(small,big,((big-small+1)/ 12)+1)) 
			chart.set_axis_labels(Axis.BOTTOM,[ x[:3] for x in calendar.month_name ][1:])
			chart.set_line_style(0,thickness=6)
			chart.set_line_style(1,thickness=6)
			self.response.out.write('<div id="container">') 
			self.response.out.write('<div id="graph">') 
			self.response.out.write('<h2>Trend <font color="207000">%s</font> vs. <font color="0077A0">%s</font> for 2008</h2>' % (query1,query2))
			self.response.out.write('<img src="%s">' % chart.get_url() )
			self.response.out.write('<strong>Total: <font color="207000">%s</font> %d</strong> &nbsp; ' %(query1,results7['total']))
			self.response.out.write('<strong><font color="0077A0">%s</font> %d</strong>' % (query2,results8['total']))
			self.response.out.write('<br>As mentioned in articles from <a href="http://www.nytimes.com">The New York Times</a>')
			self.response.out.write('</div')
			self.response.out.write('<div id="img"><center>')
			self.response.out.write('<h2><font color="207000">%s</font></h2>'% (query1))
			for i in results7['results']:
				if 'small_image_url' in i: 
					self.response.out.write('<a href="%s"><img src="%s"></a>' % (i['url'],i['small_image_url']))
			self.response.out.write('</center></div>')
			self.response.out.write('<div id="img"><center>')
			self.response.out.write('<h2><font color="0077A0">%s</font></h2>'% (query2))
			for i in results8['results']:
				if 'small_image_url' in i: 
					self.response.out.write('<a href="%s"><img src="%s"></a>' % (i['url'],i['small_image_url']))
			self.response.out.write('</center></div>')
			self.response.out.write('</div>')
		self.response.out.write('<div id="container">brought to you via the search api of <a href="http://developer.nytimes.com">nytimes.com</a> and <a href="http://twitter.com/derekg">derekg</a></div>')
		self.response.out.write('</center></body></html>')
コード例 #29
0
ファイル: pygchart.py プロジェクト: krihal/pygchart
def plotter(fund):
    
    (dates, values) = dataparser("data/%s" % fund)
    left_axis = [int(min(values)), int(max(values) + 1)]
    
    chart = SimpleLineChart(600, 375, y_range=[min(values), max(values) + 1])
    chart.add_data(values)
    chart.add_data([0] * 2)
    chart.set_colours(['76A4FB'] * 5)
    chart.add_fill_range('76A4FB', 0, 1)
    chart.set_grid(0, 5, 1, 25)
    chart.set_axis_labels(Axis.LEFT, left_axis)
    chart.set_axis_labels(Axis.BOTTOM, dates)

    chart.download("charts/%s.png" % fund)
コード例 #30
0
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]])
    
    regionseq = parseregion(regions)
    
    #print regionseq

    min_y = -5
    max_y = 5
    chart = SimpleLineChart(800, 300, y_range=[min_y, max_y])
    
    #chart.add_data([max_y]*2)
    chart.add_data(hdphseq)   
    chart.add_data(regionseq)
    chart.add_data([min_y]*2)
    chart.set_colours(['76A4FB', 'ADFF2F', '000000'])
    chart.add_fill_range('ADFF2F', 1, 2)
    chart.set_axis_labels(Axis.LEFT, [min_y, '', max_y])
    chart.set_axis_labels(Axis.BOTTOM, aaseq)
    
    chart.download('test.png')
    
    #print hdphseq
    return hdphseq
コード例 #31
0
ファイル: graph.py プロジェクト: carlobifulco/Yaic
class SimpleLineTempChart:
  
  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)
    #self.chart.add_data(data)
  
  def get_url(self):
    return self.chart.get_url()
コード例 #32
0
ファイル: __init__.py プロジェクト: underbluewaters/pyrifera
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
コード例 #33
0
ファイル: pchart.py プロジェクト: cyberyoung/sentry
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(600, 500, 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
    # ]
    # 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 = xrange(0, 100, 20)
    data2 = [0, 20, 20, 40, 40, 80, 80, 100, 100]
    chart.add_data(data)
    chart.add_data(data2)

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

    # 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')
コード例 #34
0
ファイル: BorisBike.py プロジェクト: jimclarkuk/CycleStats
def queryData(ID=1):
    # connect
    
    # create a cursor
    cursor = db.cursor()
    
    #cursor.execute("SELECT available, readtime FROM occupancy WHERE site='%s'" % ID)
    cursor.execute("SELECT available, readtime FROM occupancy WHERE site='%s'" % ID)
    query = cursor.fetchall()
    log(query)
    # Set the vertical range from 0 to 100
    max_y = 50

    # Chart size of 200x125 pixels and specifying the range for the Y axis
    chart = SimpleLineChart(800, 300, y_range=[0, max_y])
    
    data, y_axis = ([[x[i] for x in query] for i in [0, 1]])
    
    length = len(y_axis)
    if length > 20:
        step = abs(len(y_axis)/20)
        y_axis = y_axis[0:length:step]
            
    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, 2)
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)
    
    # X axis labels
    chart.set_axis_labels(Axis.BOTTOM, y_axis)
    
    return chart
コード例 #35
0
ファイル: pchart.py プロジェクト: cyberyoung/sentry
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(600, 500, 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
    # ]
    # 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 = xrange(0, 100, 20)
    data2 = [0, 20, 20, 40, 40, 80, 80, 100, 100]
    chart.add_data(data)
    chart.add_data(data2)
    
    # Set the line colour to blue
    chart.set_colours(['0000FF','00CC00'])

    # 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')
コード例 #36
0
ファイル: views.py プロジェクト: adamgreig/isatracker
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})
コード例 #37
0
ファイル: chart.py プロジェクト: wangjun/reading-progress
def ShowChartByGoogle(handler, data, book, ups):
    oneday = datetime.timedelta(days=1)
    date = ups[0].date
    xlabel = [str(date.day)]
    ylabel = range(0, book.pages + 1, ((book.pages / 8) / 50 + 1) * 50)
    
    for (i, up) in enumerate(ups):
        if i == 0: continue
        days = (up.date - ups[i-1].date).days
        for j in range(days):
            date += oneday
            if date.weekday() == 0: # only records sunday
                if date.day < 7:
                    xlabel.append(str(date.month))
                else:
                    xlabel.append('.')

    chart = SimpleLineChart(600, 320, y_range=[0, ylabel[-1]])

    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 = ylabel
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)
    
    # X axis labels
    chart.set_axis_labels(Axis.BOTTOM, xlabel)

    doRender(handler, 'progress.html', {
            'book': book,
            'imgurl': chart.get_url(),
            'method': 'google'})
コード例 #38
0
def linechart(name, dataset, size=(400,400)):
    max_y = maxy(dataset)
    chart = SimpleLineChart(size[0], size[1], y_range=[0, max_y])
    legend = []
    for series_name, s in dataset:
        chart.add_data([y for x, y in s])
        legend.append(series_name)
    
    chart.set_colours(['057D9F', '8106A9', 'E9FB00', 'FF8100'])
    chart.set_legend(legend)
    chart.set_grid(0, 25, 5, 5)
    
    left_axis = range(0, int(max_y + 1), 25)
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)
    
    bottom_axis = [x for x, y in dataset[0][1]]
    chart.set_axis_labels(Axis.BOTTOM, bottom_axis)
    chart.download(name)
コード例 #39
0
def generateGraph(fMesureGlobalPerCent, nbComparison, resPath):
    max_y = 100#Fmesure à 100%
    chart = SimpleLineChart(500, 500, y_range=[0, max_y])
    chart.add_data(fMesureGlobalPerCent)
    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(0, max_y + 1, 25)
    left_axis[0] = ''
    chart.set_axis_labels(Axis.LEFT, left_axis)


    y_axis = []
    for x in range(nbComparison):
        if x%5 == 0:
            y_axis.append(x)
    chart.set_axis_labels(Axis.BOTTOM, y_axis)
    chart.download(resPath)
コード例 #40
0
ファイル: models.py プロジェクト: Niets/gestorpsi
    def get_chart(self, data, date_start, date_end, colours=None):
        # Set the vertical range from max_value plus 10
        if not data:
            return None

        max_y = max([max(l) for l in data])

        if max_y < 10:
            mult = 1
        else:
            y_scale = max_y
            mult = 1
            while y_scale/10 > 1:
                mult = mult*10
                y_scale = y_scale/10
        max_y = max_y + mult

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

        for i in data:
            chart.add_data(i)

        if not colours:
            chart.set_colours(['0000FF']) # Set the line colour to blue
        else:
            chart.set_colours(colours)

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

        # Set the horizontal dotted lines
        chart.set_grid(0, 25, 5, 5)
        
        left_axis = range(0, max_y + 1, mult)
        left_axis[0] = ''
        chart.set_axis_labels(Axis.LEFT, left_axis)

        # X axis labels
        chart.set_axis_labels(Axis.BOTTOM, \
            self.get_chart_x_axis_label(date_start, date_end))
        
        return chart.get_url()
コード例 #41
0
ファイル: plot.py プロジェクト: nfredrik/pyjunk
class PlotObject(object):
    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'])

    def plot(self, data):

        self.chart.add_data(data=data)

        self.chart.download(file_name='misse.png')
コード例 #42
0
ファイル: grafos.py プロジェクト: johnfelipe/sissan
def __line_strip_graphic__(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)

    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
    try:
        left_axis = range(int(min_y * 0.95), int(max_y * 1.05), 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
コード例 #43
0
    def _plot_timeseries(self, options, args, fh):
        """Plot a timeseries graph"""
        from pygooglechart import Chart, SimpleLineChart, Axis

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

        pts = []
        for l in imap(lambda x: x.strip(), fh):
            splitted_line = l.split(delimiter)
            v = float(splitted_line[field])
            t = datetime.strptime(splitted_line[datefield], options.dateformat)
            pts.append((t, v))

        if options.get('limit', None):
            # Only wanna use top (earliest) 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 t, v 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)

        ts, vals = zip(*pts)
        chart.add_data(vals)

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

        return chart
コード例 #44
0
def users(*args):
    days = 60
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute(
        "SELECT date_joined, COUNT(*) from auth_user where date_joined > NOW() - INTERVAL %i DAY group by DATE(date_joined) order by DATE(date_joined) desc"
        % days)

    data = {}
    max_y = 0
    for dt, num in cursor.fetchall():
        if num > max_y:
            max_y = num
        data[dt.date()] = num

    data2 = []

    dt = date.today() - timedelta(days - 1)
    for i in xrange(days):
        data2.append((dt, data.get(dt, 0)))
        dt = dt + timedelta(1)

    chart = SimpleLineChart(800, 125, y_range=[0, max_y])
    chart.add_data([row[1] for row in data2])
    chart.set_colours(['0000FF'])

    ticks = (max_y % 25) + 1

    left_axis = range(0, max_y, 25)
    left_axis[0] = ''
    chart.set_axis_labels(Axis.RIGHT, left_axis)

    bottom_axis = [
        dt[0].strftime("%b") if dt[0].day == 1 else '' for dt in data2
    ]
    chart.set_axis_labels(Axis.BOTTOM, bottom_axis)

    chart.set_title("Daily Registrations")

    data2.reverse()
    return chart
コード例 #45
0
ファイル: clementine.py プロジェクト: Shedward/Website
    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
            }))
コード例 #46
0
    def linegraph(self, days, bars, output, title=""):
        data = []
        min_count = 0
        max_count = 0
        date = lambda i: datetime.date.today() + datetime.timedelta(-days + i)

        for i in range(0, days + 1):
            count = bars[date(i)]
            max_count = max(count, max_count)
            min_count = min(count, min_count)
            data.append(count)
        chart = SimpleLineChart(800, 350, y_range=[min_count, 60000])
        chart.add_data(data)
        # Set the line colour to blue
        chart.set_colours(['0000FF'])

        # Set the vertical stripes
        d = max(1 / float(days), round(7 / float(days), 2))
        chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', d, 'FFFFFF', d)

        fmt = "%d/%m"
        chart.set_axis_labels(Axis.BOTTOM, \
                              [date(i).strftime(fmt) for i in range(0,days,7)])

        # 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.
        delta = float(max_count - min_count) / 100
        skip = int(delta) / 5 * 100
        left_axis = range(0, 60000 + 1, skip)
        left_axis[0] = ''
        chart.set_axis_labels(Axis.LEFT, left_axis)

        if len(title) > 0:
            chart.set_title(title % days)

        chart.download(output)
コード例 #47
0
ファイル: views.py プロジェクト: BrainIsDead/currency_bot
def history(message):
	try:
		splitted_text = re.search(r'[a-zA-Z]{3}/[a-zA-Z]{3}', message.text).group().split('/')
		base = splitted_text[0].upper()
		symbols = splitted_text[1].upper()
		start = str(date.today() - timedelta(days=7))
		end = str(date.today())
		data = requests.get(
			'https://api.exchangeratesapi.io/history?start_at='+start+'&end_at='+end+'&base='+base+'&symbols='+symbols
		)
		data = data.json()
		chart = SimpleLineChart(700, 400)
		
		chart_data = []
		# using collections.OrderedDict to sort incoming data
		for i in collections.OrderedDict(sorted(data['rates'].items())):
			chart_data.append(round(data['rates'][i][symbols], 2))
		chart.add_data(chart_data)
		print(collections.OrderedDict(sorted(data['rates'].items())))
		# Set the line colour
		chart.set_colours(['0000FF'])
		left_axis= list(
			range(
				round(min(chart_data)),
				round(max(chart_data)+1),
				round(sum(chart_data)/len(chart_data))
			)
		)
		chart.set_axis_labels(Axis.LEFT, left_axis)

		x_labels = []
		# using collections.OrderedDict to sort incoming data
		for i in collections.OrderedDict(sorted(data['rates'].items())):
			x_labels.append(i)
		chart.set_axis_labels(Axis.BOTTOM, x_labels)
		print(chart.get_url())
		bot.send_photo(message.chat.id, chart.get_url())
	except:
		bot.send_message(message.chat.id, 'No exchange rate data is available for the selected currency.')
コード例 #48
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')
コード例 #49
0
ファイル: cvrp_random.py プロジェクト: vrinda1230/cvrp-python
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')
コード例 #50
0
ファイル: chartTest.py プロジェクト: magdamagda/mate2016
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')
コード例 #51
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')
コード例 #52
0
ファイル: chart.py プロジェクト: mserna/Python
def stripes():
    
    # Set the vertical range from 0 to 100
    max_y = 2

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

    # Add the chart data
    data = [ 0.2121649980545044, 0.1335739940404892, 0.1369339972734451, 0.1327839940786362, 0.3375900089740753 ]
    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, 10, 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, 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, \
        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])
    chart.set_axis_labels(Axis.BOTTOM, "Time")

    chart.download('chart.png')
コード例 #53
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()
コード例 #54
0
ファイル: ppchart.py プロジェクト: cyberyoung/sentry
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)
コード例 #55
0
def createChart(title, xaxis, datay, firstweekday):

    # Find the max y value
    max_y = None
    for dd in datay.values():
        max_y = max(max_y, max(dd))

    # Chart size of 400x250 pixels and specifying the range for the Y axis
    if title:
        chart = SimpleLineChart(1000, 250, title=title, y_range=[0, max_y])
    else:
        chart = SimpleLineChart(1000, 250, y_range=[0, max_y])

    # add the data
    for dd in datay.values():
        chart.add_data(dd)

    # Set the line colours
    chart.set_colours(['0000FF', 'FF0000', '00FF00', 'F0F000', '0F0F00'])

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

    # vertical stripes, the width of each stripe is calculated so that it covers one month
    ndatapoints = len(datay.values()[0])

    datapermonth = []
    for year in xaxis:
        for month in xaxis[year]:
            datapermonth.append(xaxis[year][month])

    # mark months using range markers
    stripes = []
    stripcols = ('FFFFFF', 'CCCCCC')
    wlast = 0
    for k in datapermonth:
        w = k * 1.0 / ndatapoints
        icol = len(stripes) / 2 % 2
        stripes.append(stripcols[icol])
        stripes.append(w)
        wlast += w
    chart.fill_linear_stripes(Chart.CHART, 0, *stripes)

    # y axis labels
    if max_y > 30:
        left_axis = range(0, int(max_y) + 1, 5)
    elif max_y > 10:
        left_axis = range(0, int(max_y) + 1, 1)
    elif max_y > 5:
        left_axis = []
        v = 0.
        while v < max_y + 0.5:
            left_axis.append(v)
            v += 0.5
    else:
        left_axis = []
        v = 0.
        while v < max_y + 0.1:
            left_axis.append(v)
            v += 0.1

    left_axis[0] = ''  # no label at 0
    chart.set_axis_labels(Axis.LEFT, left_axis)

    # X axis labels
    monthlabels = []
    for year in xaxis:
        for imonth in xaxis[year]:
            monthlabels.append(months[imonth])

    chart.set_axis_labels(Axis.BOTTOM, monthlabels)
    chart.set_axis_labels(Axis.BOTTOM, xaxis.keys())  # years

    # the axis is 100 positions long, position month labels in the centre for each month
    positions = []
    p = 0
    for y in xaxis:
        datax = xaxis[y]
        for k in datax:
            w = datax[k] * 100.0 / ndatapoints
            positions.append(p + w / 2)
            p += w
    chart.set_axis_positions(1, positions)

    # position year labels at the centre of the year
    positions = []
    p = 0
    for y in xaxis:
        datax = xaxis[y]
        w = sum(datax.values()) * 100.0 / ndatapoints
        positions.append(p + w / 2)
        p += w
    chart.set_axis_positions(2, positions)

    chart.set_legend([k[0] for k in datay.keys()])

    # vertical stripes for marking weeks
    #weeks = [ ]
    nsundays = 0
    daycol = genColourRange(7)
    for p in range(ndatapoints):
        d = firstweekday + p
        if (d % 7) == 0:
            assertSunday(p)
            chart.add_marker(0, p, 'V', 'FF0000', 1)
        #weeks.append(daycol[d % 7])
        #weeks.append(1./ndatapoints) # this does not work if the width is less than 0.01
        #if len(weeks)/2 == 7: # from now it's repeats
        #    break
    #chart.fill_linear_stripes(Chart.CHART, 0, *weeks)
    #chart.add_marker(0, 100, 'V', 'FF0000', 1)
    return chart
コード例 #56
0
    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)

# X axis labels
chart.set_axis_labels(Axis.BOTTOM, numbers)

chart.download('chart-output.png')
コード例 #57
0
ファイル: views.py プロジェクト: tanveerahmad1517/myewb2
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))
コード例 #58
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.',
        }
コード例 #59
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
コード例 #60
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)