def GetGLineUrl(plot_list, width=600, height=500): """Get Google line chart url string. Args: plot_list: Numeric number list. A list also can contain negative value elements. width: Image width when it is rendered in web browser. height: Image height when it is rendered in web browseor. Returns: An url string that will create chart image in google chart. """ max_y = max(plot_list) min_y = min(plot_list) gchart = GChart() gchart.type('line') gchart.dataset(plot_list) gchart.size(width, height) gchart.axes.type('y') gchart.axes.range(0, min_y, max_y) gchart.scale(min_y, max_y) return str(gchart)
def gchart(context, nodelist, type, dataset, **kwargs): G = GChart(type, dataset, encoding=kwargs.pop('encoding', 'text')) for node in nodelist: if isinstance(node, TextNode): for part in node.render(context).splitlines(): cmd, value = parse_cmd(part) if cmd is None: continue if cmd.startswith('axes'): cmd = getattr(G.axes, cmd[5:]) else: cmd = getattr(G, cmd) cmd(*value.split()) if 'instance' in kwargs: return G return G.img(**kwargs)
def gchart(context, nodelist, type, dataset, **kwargs): G = GChart(type, dataset, encoding=kwargs.pop('encoding','text')) for node in nodelist: if isinstance(node, TextNode): for part in node.render(context).splitlines(): cmd,value = parse_cmd(part) if cmd is None: continue if cmd.startswith('axes'): cmd = getattr(G.axes, cmd[5:]) else: cmd = getattr(G, cmd) cmd(*value.split()) if 'instance' in kwargs: return G return G.img(**kwargs)
def simple(self): # Instantiate the GChart instance, this is all you will need for making charts # GChart(type=None, dataset=None), see the doc for more G = GChart() # Set the chart type, either Google API type or regular name G.type('pie') # Update the chart's dataset, can be two dimensional and contain string data G.dataset('helloworld') # Set the size of the chart, default is 300x150 G.size(250, 100) return G
def simple(): G = GChart() # Set the chart type, either Google API type or regular name G.type('pie') # Update the chart's dataset, can be two dimensional or contain string data G.dataset('helloworld') # Set the size of the chart, default is 300x150 G.size(250, 100) print G
def practice_list(request, club = None): club = get_object_or_404(Club, Slug = club) practices = club.practice_set.all().annotate(NumPeople = Count('person')).order_by('-Date') if practices.count() > 10: chart = GChart(ctype = 'line') data = sliding_window(practices) chart.dataset(data[:500]).axes.type('xy') if request.method == 'POST': form = PracticeModelForm(request.POST) new_practice = form.save(commit = False) new_practice.Club = club new_practice.save() return HttpResponseRedirect(new_practice.get_absolute_url()) else: form = PracticeModelForm() return render_to_response('Dojo/Practice_object_list.html', locals(), context_instance = RequestContext(request))
def render_macro(self, req, name, content): # XXX: This is a big security hole. Need to replace this with something that # only accepts simple key/value pairs. options = eval("dict(%s)" % content) query = options.get('query', None) ctype = options.get('type', None) columns = options.get('columns', None) if query is None or ctype is None: raise ValueError("Chart 'type' and 'query' parameters are required") for key in NON_API_KEYS: if key in options: del options[key] datasets = {} scales = {} labels = {} if columns is not None: for idx, val in enumerate(columns): if len(val) >= 2: if val[1] == 'labels': labels[idx] = [] elif val[1] in ('percentage', 'scaled'): datasets[idx] = [] scales[idx] = (0,0) db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute(query) col_count = 0 if columns is not None: col_count = len(columns) # Collect label, scale and dataset data for row in cursor: if not col_count: col_count = len(row) if columns is None: columns = [] for idx in range(col_count): columns.append((None, 'percentage')) datasets[idx] = [] scales[idx] = (0,0) elif len(columns) != col_count: raise KeyError("Table has %d columns, but 'columns' parameter has %d items" % \ (col_count, len(columns),)) for idx, col in enumerate(row): if idx in labels: labels[idx].append(col) elif idx in datasets: try: col_value = float(col) except (TypeError, ValueError): continue datasets[idx].append(col_value) scales[idx] = (min(scales[idx][0], col_value), max(scales[idx][1], col_value),) dense_dataset = [] dataset_to_idx = {} idx_to_axis = {} axis_to_idx = {} axis_types = [] # x, x, y - in order scaled_axes = {} # idx -> min/max for that scale current_dataset = 0 current_axis = 0 for idx, col in enumerate(columns): if len(col) >= 1 and col[0]: idx_to_axis[idx] = current_axis axis_to_idx[current_axis] = idx axis_types.append(col[0]) current_axis += 1 if len(col) >= 2 and col[1] == 'scaled': scale_min = len(col) >= 3 and col[2] or scales[idx][0] scale_max = len(col) >= 4 and col[3] or scales[idx][1] scaled_axes[idx] = (scale_min, scale_max,) if idx in datasets: dataset_to_idx[current_dataset] = idx dense_dataset.append(datasets[idx]) current_dataset += 1 # Add axes if 'chxt' not in options: if axis_types: options['chxt'] = ','.join(axis_types) # Add axis labels if 'chxl' not in options: label_data = [] for idx, values in sorted(labels.items()): if idx not in idx_to_axis: continue label_data.append('%d:|%s' % (idx_to_axis[idx], '|'.join(values),)) if label_data: options['chxl'] = '|'.join(label_data) # Add scale range axes if 'chxr' not in options: range_triples = [] for idx, (scale_min, scale_max) in sorted(scaled_axes.items()): if idx not in idx_to_axis: continue range_triples.append('%d,%.1f,%.1f' % (idx_to_axis[idx], scale_min, scale_max,)) if range_triples: options['chxr'] = '|'.join(range_triples) # Add data scaling if 'chds' not in options and scaled_axes: scale_data = [] for cnt in range(len(dense_dataset)): idx = dataset_to_idx[cnt] scale_item = ',' if idx in scaled_axes: scale_min, scale_max = scaled_axes[idx] scale_item = '%.1f,%.1f' % (scale_min, scale_max) scale_data.append(scale_item) if scale_data: options['chds'] = ','.join(scale_data) chart = GoogleChart(ctype=ctype, dataset=dense_dataset, **options) return Markup(chart.img())
def tarp_subsidies(request): estimated_subsidies = [] subsidy_rates = [] amounts_received = [] names = [] colors = [] for r in SubsidyRecord.objects.all(): estimated_subsidies.append(r.estimated_subsidy) subsidy_rates.append(r.subsidy_rate) amounts_received.append(r.amount_received) names.append(r.name) colors.append(r.color) # reverse names (API wrapper bug?) names.reverse() # estimated subsidies chart estimates_subsidies_normalized = _normalize_chart_range( estimated_subsidies) estimated_subsidies_chart = GChart('bhs', estimates_subsidies_normalized.values()) estimated_subsidies_chart.size((500, 250)) estimated_subsidies_chart.color('|'.join(colors)) estimated_subsidies_chart.bar(18, 2, 0) estimated_subsidies_chart.axes.type('xy') estimated_subsidies_chart_xlabels = range( 0, (_get_scale_bound(estimated_subsidies) + 1), 5) estimated_subsidies_chart_xlabels = map((lambda x: str(x)), estimated_subsidies_chart_xlabels) estimated_subsidies_chart.axes.label( str('|'.join(estimated_subsidies_chart_xlabels))) estimated_subsidies_chart.axes.label('|'.join(names)) estimated_subsidies_chart.axes.style('000000') estimated_subsidies_chart.axes.style('000000') i = 0 for x in estimated_subsidies: marker_text = 't $%.1f' % x estimated_subsidies_chart.marker(marker_text, '000000', 0, i, 10, -1) i = i + 1 # subsidy rates chart subsidy_rates_normalized = _normalize_chart_range(subsidy_rates) subsidy_rate_chart = GChart('bhs', subsidy_rates_normalized.values()) subsidy_rate_chart.size((500, 250)) subsidy_rate_chart.color('|'.join(colors)) subsidy_rate_chart.bar(18, 2, 0) subsidy_rate_chart.axes.type('xy') subsidy_rate_chart_xlabels = range(0, (_get_scale_bound(subsidy_rates) + 1), 10) subsidy_rate_chart_xlabels = map((lambda x: str(x)), subsidy_rate_chart_xlabels) subsidy_rate_chart.axes.label(str('|'.join(subsidy_rate_chart_xlabels))) subsidy_rate_chart.axes.label('|'.join(names)) subsidy_rate_chart.axes.style('000000') subsidy_rate_chart.axes.style('000000') i = 0 for x in subsidy_rates: marker_text = 't %d%%' % x subsidy_rate_chart.marker(marker_text, '000000', 0, i, 10, -1) i = i + 1 # amounts received chart amounts_received_normalized = _normalize_chart_range(amounts_received) amounts_received_chart = GChart('bhs', amounts_received_normalized.values()) amounts_received_chart.size((500, 250)) amounts_received_chart.color('|'.join(colors)) amounts_received_chart.bar(18, 2, 0) amounts_received_chart.axes.type('xy') amounts_received_chart_xlabels = range( 0, (_get_scale_bound(amounts_received) + 1), 10) amounts_received_chart_xlabels = map((lambda x: str(x)), amounts_received_chart_xlabels) amounts_received_chart.axes.label( str('|'.join(amounts_received_chart_xlabels))) amounts_received_chart.axes.label('|'.join(names)) amounts_received_chart.axes.style('000000') amounts_received_chart.axes.style('000000') i = 0 for x in amounts_received: marker_text = 't $%.1f' % x amounts_received_chart.marker(marker_text, '000000', 0, i, 10, -1) i = i + 1 return render_to_response( 'bailout/tarp_subsidy_table.html', { 'estimated_subsidies_chart': estimated_subsidies_chart.img(), 'subsidy_rate_chart': subsidy_rate_chart.img(), 'amounts_received_chart': amounts_received_chart.img(), 'estimated_subsidies': estimated_subsidies, 'subsidy_rates': subsidy_rates, 'amounts_received': amounts_received, 'names': ' '.join(names), 'colors': '|'.join(colors) }, context_instance=RequestContext(request))
def get_context_data(self, **kwargs): context = super(RedDetailView, self).get_context_data(**kwargs) app_label = 'rtg' model = models.get_model(app_label, 'ReservaIp') self.admin_object = admin_rtg._registry[model] #IGNORE:protected-access self.admin_object.red_ips = Red_Ips(self.object) if self.object.externa: ips_activas = "No disponible (red externa)" else: ips_activas = self.admin_object.red_ips.ips_activas if self.object.asignacion_ip: #gestionamos las IPs ips_asignadas = len(self.admin_object.red_ips.asignadas) ips_libres = self.admin_object.red_ips.ips_libres self.admin_object.change_list_template = 'rtg/red_detail.django.html' else: #no gestionamos las IPs ips_asignadas = 'No se gestionan las IPs de la red' ips_libres = '' self.admin_object.change_list_template = 'rtg/red_detail_sin_ips.django.html' hist_asignadas = [] hist_activas = [] for i in range(1,13): d=HistoricoIpsEnRed.objects.filter(red=self.object).filter(fecha__month=i).aggregate(Max('ips_asignadas'),Max('ips_activas')) #IGNORE:no-member hist_asignadas.append(d['ips_asignadas__max']) hist_activas.append(d['ips_activas__max']) hist_libres = deque(map(lambda x:'_' if x==None else str(self.admin_object.red_ips.num_ips-x), hist_asignadas)) #IGNORE:bad-builtin) hist_asignadas = deque(map(lambda x:'_' if x==None else str(x), hist_asignadas)) #IGNORE:bad-builtin hist_activas = deque(map(lambda x:'_' if x==None else str(x), hist_activas)) #IGNORE:bad-builtin meses = deque(['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic']) mes_actual = datetime.date.today().month # rotamos los datos para que apareza en la grafica el mes actual como último mes meses.rotate(-mes_actual) hist_libres.rotate(-mes_actual) hist_asignadas.rotate(-mes_actual) hist_activas.rotate(-mes_actual) #Creamos el GChart pasando el dataset porque no se soporta el parametro t2 G = GChart(ctype="bvs", chd="t2:" + ','.join(hist_asignadas)+'|'+','.join(hist_libres)+'|'+','.join(hist_activas)) G.bar('a',1) G.size(350,200) G.color('4D89F9','C6D9FD','0000FF') G.marker('D','0000FF','2','0','2') G.marker('s','0000FF','2','-1','8') G.title('Historico Utilizacion') #Fallan los acentos G.legend('Asignadas','Libres','Activas') G['chdlp'] = 'b|l' G.scale(0,self.admin_object.red_ips.num_ips) G.margin(0,0,5,0) G.axes.type('yx') G.axes.label(1,*meses) #IGNORE:W0142 G.axes.range(0,0,self.admin_object.red_ips.num_ips) context.update( { 'model_name': 'red', 'num_ips': self.admin_object.red_ips.num_ips, 'ips_asignadas': ips_asignadas, 'ips_libres': ips_libres, 'ips_activas': ips_activas, 'admin_url': get_admin_url(self.request.get_full_path()), 'chart_ips_libres': G, } ) return context