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)
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)
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, }))
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()
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, }))
def get_pace_chart_url(self, width, height): if len(self.positions()) == 0: return '' pace = [] int_dist = [] s = 0 last_p = None for p in self.positions(): if last_p != None: ds = distance.distance((p.latitude, p.longitude), \ (last_p.latitude, last_p.longitude)).kilometers s = s + int(ds * 1000) dt = (p.time - last_p.time).seconds if ds > 0: pace.append(dt / ds) int_dist.append(s) last_p = p int_pace = [int(p) for p in ema(pace, 20)] min_pace = int(min(int_pace) * 0.95) max_pace = int(max(int_pace) / 0.95) mid_pace = (max_pace + min_pace) / 2 min_pace_str = '%02d:%02d' % (min_pace / 60, min_pace % 60) mid_pace_str = '%02d:%02d' % (mid_pace / 60, mid_pace % 60) max_pace_str = '%02d:%02d' % (max_pace / 60, max_pace % 60) chart = SimpleLineChart(width, height, y_range = (min_pace, max_pace)) chart.add_data(int_pace) chart.set_axis_labels(Axis.LEFT, [min_pace_str, mid_pace_str, max_pace_str]) return chart.get_url()
def 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 }))
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})
def gchart(data, node, check, metric, start=datetime.now() - timedelta(days=1), end=datetime.now()): d = [] ts = [] for p in data['metrics'][0]['data']: d.append(float(p['avg'])) ts.append(p['ts']) # Chart size of 200x125 pixels and specifying the range for the Y axis max_y = int(max(d)) chart = SimpleLineChart(450, 250, y_range=[0, max_y]) chart.add_data(d) left_axis = range(0, max_y + 1, max_y / 5) left_axis[0] = '' chart.set_axis_labels(Axis.LEFT, left_axis) min_dt = datetime.fromtimestamp(min(ts)) max_dt = datetime.fromtimestamp(max(ts)) chart.set_axis_labels(Axis.BOTTOM, [str(min_dt), str(max_dt)]) title = '%s.%s.%s' % (node['name'], check['type'], metric) chart.set_title(title) return chart.get_url()
def getRollingAverageGraph(cursor, colName, rollingWindowDays, title=""): sqlCMD = "SELECT pDate, %s from %s" %(colName, N.JOBS_SUMMARY_TABLENAME) cursor.execute(sqlCMD) results = cursor.fetchall() beginWindowIndex = 0 endWindowIndex = 0 xData = [] yData = [] while endWindowIndex < len(results): while endWindowIndex < len(results) and (results[endWindowIndex][0] - results[beginWindowIndex][0]).days <= rollingWindowDays: endWindowIndex += 1 yData.append( sum(results[i][1] for i in xrange(beginWindowIndex, endWindowIndex, 1)) / float(endWindowIndex - beginWindowIndex)) xData.append(results[endWindowIndex-1][0]) beginWindowIndex = endWindowIndex chart = SimpleLineChart(680, 400, y_range = (min(yData)-1, max(yData)+1)) chart.add_data(yData) yLabels = range(0, int(max(yData)+1), 5) yLabels[0] = '' xLabels = [str(xData[-i]) for i in xrange(1, len(xData)-1, int(0.2*len(xData)))] xLabels.reverse() chart.set_axis_labels(Axis.LEFT, yLabels) chart.set_axis_labels(Axis.BOTTOM, xLabels) chart.set_title("Rolling %i-Day Average %s" % (rollingWindowDays, title)) imgbin = chart.download() toReturn = cStringIO.StringIO(imgbin) toReturn.seek(0) return chart.get_url(), toReturn
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)
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()
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()
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)
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
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
def simple_random(): chart = SimpleLineChart(300, 100, y_range=(0, 100)) max_y = 100 list_data = [10, 90, 80, 10, 10, 20, 30, 20, 15, 45, 56, 42, 92] chart.add_data(list_data) chart.add_data(reversed(list_data)) chart.set_axis_labels(Axis.LEFT, ['', max_y / 2, max_y]) chart.set_axis_labels(Axis.BOTTOM, ['Sep', 'Oct', 'Nov', 'Dec']) chart.download('line-simple-random.png')
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')
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
def simpleChart(bottom_labels, data): # round min and max to nearest integers datamin = int(min(data) - 0.5) datamax = int(max(data) + 0.5) chart = SimpleLineChart(200, 125, y_range=[datamin, datamax]) chart.add_data(data) left_axis = [datamin,0,datamax] chart.set_axis_labels(Axis.LEFT, left_axis) chart.set_axis_labels(Axis.BOTTOM, bottom_labels) return chart
def simpleChart(bottom_labels, data): # round min and max to nearest integers datamin = int(min(data) - 0.5) datamax = int(max(data) + 0.5) chart = SimpleLineChart(200, 125, y_range=[datamin, datamax]) chart.add_data(data) left_axis = [datamin, 0, datamax] chart.set_axis_labels(Axis.LEFT, left_axis) chart.set_axis_labels(Axis.BOTTOM, bottom_labels) return chart
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)
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()
def mk_chart(self): from pygooglechart import SimpleLineChart chart = SimpleLineChart(self.width, self.height, colours=('91CF60', 'FC8D59')) all_labels = [d[0] for d in self.cumulative] chart.add_data([d[1] for d in self.cumulative]) chart.add_data([d[1] for d in self.newdata]) chart.set_axis_labels('y', range(0, self.cmax, (self.cmax / 4))) chart.set_axis_labels('x', [all_labels[x] for x in range(0, len(all_labels), (len(all_labels) / 4))]) return chart
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
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()
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()
def create_graph(self, particle_data, time_data): # Set the vertical range from 0 to 2 max_y = 2 # Chart size of 500x500 pixels and specifying the range for the Y axis chart = SimpleLineChart(500, 500, y_range=[0, max_y]) # Add the chart data data = particle_data chart.add_data(data) # Set the line color blue chart.set_colours(['0000FF']) # Set the vertical stripes chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2) # Set the horizontal dotted lines chart.set_grid(0, 25, 5, 5) # The Y axis labels left_axis = ['0.25', '0.5', '0.75', '1'] left_axis[0] = '' chart.set_axis_labels(Axis.LEFT, left_axis) left_axis2 = "Proton Flux"[::-1] chart.set_axis_labels(Axis.LEFT, left_axis2) # X axis labels chart.set_axis_labels(Axis.BOTTOM, time_data[0:3][::-1]) chart.set_axis_labels(Axis.BOTTOM, "Time") chart.download('chart.png') return True
def group_membership_activity(request, group_slug): group = get_object_or_404(BaseGroup, slug=group_slug) listcount = [] listdate = [] currentcount = group.member_users.all().count() thedate = date.today() skip = False while thedate.year != date.today().year - 1 or thedate.month != date.today( ).month: if thedate.month == 1: startdate = date(year=thedate.year - 1, month=12, day=1) else: startdate = date(year=thedate.year, month=thedate.month - 1, day=1) joins = GroupMemberRecord.objects.filter( group=group, membership_start=True, datetime__range=(startdate, thedate)).count() unsubs = GroupMemberRecord.objects.filter( group=group, membership_end=True, datetime__range=(startdate, thedate)).count() listcount.append(currentcount - joins + unsubs) if not skip: listdate.append(thedate.strftime("%B %y")) else: listdate.append("") skip = not skip thedate = startdate listcount.reverse() listdate.reverse() activity = SimpleLineChart(600, 450, y_range=(min(listcount), max(listcount))) activity.add_data(listcount) yaxis = range( min(listcount), max(listcount) + 1, max(max(listcount) / 10, 1)) # that last number should be 25 or 50. but for testing... if len(yaxis) < 2: # only for testing... yaxis.append(1) yaxis[0] = '' activity.set_axis_labels(Axis.LEFT, yaxis) activity.set_axis_labels(Axis.BOTTOM, listdate) return activity.get_url()
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('"','"'), 'query2' : query2.replace('"','"')}) 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> ' %(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>')
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)
def month_graph(data, start, end): """Helper for making graphy graph for a month's worth of data on something.""" from pygooglechart import SimpleLineChart, Axis WIDTH, HEIGHT = 700, 200 y_range = (0, max(max(data), 1)) # todo: have extra room when I figure out how to do labels (set_axis_positions?) x_range = (0, 30) chart = SimpleLineChart(WIDTH, HEIGHT, y_range=y_range, x_range=x_range) chart.add_data(data) chart.set_axis_labels(Axis.LEFT, y_range) #chart.left.labels = chart.left.label_positions = [0, max(data)] chart.set_axis_labels(Axis.BOTTOM, [d.strftime('%D') for d in date_range(start, end, datetime.timedelta(days=10))]) #chart.bottom.label_positions = [0, 10, 20, 30] return chart.get_url()
def get_pace_chart_url(self, width, height): def calc_pace_and_dist_from_previous(acc, p): last_p = acc[0] s = acc[1] pace = acc[2] int_dist = acc[3] ds = distance.distance((p.latitude, p.longitude), \ (last_p.latitude, last_p.longitude)).kilometers s = s + int(ds * 1000) dt = (p.time - last_p.time).seconds if ds > 0: pace.append(dt / ds) int_dist.append(s) acc[0] = p acc[1] = s return acc if len(self.positions) == 0: return '' pace = [] int_dist = [] s = 0 last_p = None r = reduce(calc_pace_and_dist_from_previous, self.positions[1:len(self.positions)], [self.positions[0], 0, [], []]) pace = r[2] int_dist = r[3] int_pace = [int(p) for p in ema(pace, 30)] min_pace = int(min(int_pace) * 0.95) max_pace = int(max(int_pace) / 0.95) mid_pace = (max_pace + min_pace) / 2 min_pace_str = '%02d:%02d' % (min_pace / 60, min_pace % 60) mid_pace_str = '%02d:%02d' % (mid_pace / 60, mid_pace % 60) max_pace_str = '%02d:%02d' % (max_pace / 60, max_pace % 60) chart = SimpleLineChart(width, height, y_range = (min_pace, max_pace)) chart.add_data(int_pace) chart.set_axis_labels(Axis.LEFT, [min_pace_str, mid_pace_str, max_pace_str]) return chart.get_url()
def mk_chart(self): from pygooglechart import SimpleLineChart chart = SimpleLineChart(self.width, self.height, colours=('91CF60', 'FC8D59')) all_labels = [d[0] for d in self.cumulative] chart.add_data([d[1] for d in self.cumulative]) chart.add_data([d[1] for d in self.newdata]) chart.set_axis_labels('y', range(0, self.cmax, (self.cmax / 4))) chart.set_axis_labels('x', [ all_labels[x] for x in range(0, len(all_labels), (len(all_labels) / 4)) ]) return chart
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
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()
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
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')
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')
def report(request): # data report if Invoice.objects.all().count() == 0: return redirect("/openbook") min_year = Invoice.objects.order_by("date")[0].date.year max_year = Invoice.objects.order_by("-date")[0].date.year report = [] for year in range(min_year,max_year+1): year_report = [] for month in range(1,13): total = get_total(year, month) year_report.append(total) s = sum(year_report) tax = round((s * (0.13 / 1.13)), 2) year_report.append(tax) year_report.append(s) year_report.insert(0, year) report.append(year_report) # graphical data year report year_total_data = [i[-1] for i in report] max_y = max(year_total_data) min_y = min(year_total_data) gr = SimpleLineChart(800, 300, y_range=[0,max_y]) gr.add_data(year_total_data) gr.set_grid(0, 25, 5, 5) left_axis = range(min_y, max_y + 1, (max_y/10)) left_axis[0] = '' gr.set_axis_labels(Axis.LEFT, left_axis) gr.set_axis_labels(Axis.BOTTOM, \ [str(i) for i in range(min_year, max_year+1)]) # yearly report gs = [] months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"] for data in report: max_y = max(data[1:-2]) # excluding the first and the last 2 entries g = SimpleLineChart(800, 300, y_range=[0, max_y]) g.add_data(data[1:-2]) # excluding the frist and the last 2 entries g.set_grid(0, 25, 5, 5) left_axis = range(0, max_y + 1, (max_y/10)) left_axis[0] = '' g.set_axis_labels(Axis.LEFT, left_axis) g.set_axis_labels(Axis.BOTTOM, \ months) gs.append((data[0], g.get_url())) gs.reverse() grurl = gr.get_url() if max_year == min_year: grurl = None return render_to_response( "admin/invoice/report.html", {'report' : report, 'gr': grurl, 'gs':gs}, RequestContext(request, {}), )
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
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)
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
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')
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
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
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 }))
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)
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
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
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.')
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')
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')
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')
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')
def getRollingAverageGraph(cursor, colName, rollingWindowDays, title=""): sqlCMD = "SELECT pDate, %s from %s" % (colName, N.JOBS_SUMMARY_TABLENAME) cursor.execute(sqlCMD) results = cursor.fetchall() beginWindowIndex = 0 endWindowIndex = 0 xData = [] yData = [] while endWindowIndex < len(results): while endWindowIndex < len(results) and ( results[endWindowIndex][0] - results[beginWindowIndex][0]).days <= rollingWindowDays: endWindowIndex += 1 yData.append( sum(results[i][1] for i in xrange(beginWindowIndex, endWindowIndex, 1)) / float(endWindowIndex - beginWindowIndex)) xData.append(results[endWindowIndex - 1][0]) beginWindowIndex = endWindowIndex chart = SimpleLineChart(680, 400, y_range=(min(yData) - 1, max(yData) + 1)) chart.add_data(yData) yLabels = range(0, int(max(yData) + 1), 5) yLabels[0] = '' xLabels = [ str(xData[-i]) for i in xrange(1, len(xData) - 1, int(0.2 * len(xData))) ] xLabels.reverse() chart.set_axis_labels(Axis.LEFT, yLabels) chart.set_axis_labels(Axis.BOTTOM, xLabels) chart.set_title("Rolling %i-Day Average %s" % (rollingWindowDays, title)) imgbin = chart.download() toReturn = cStringIO.StringIO(imgbin) toReturn.seek(0) return chart.get_url(), toReturn
def simpleChart1(bottom_labels, data): # round min and max to nearest integers datamin = int(min(data) - 0.5) datamax = int(max(data) + 0.5) chart = SimpleLineChart(200, 125, y_range=[datamin, datamax]) chart.add_data(data) left_axis = [datamin, 0, datamax] chart.set_axis_labels(Axis.LEFT, left_axis) chart.set_axis_labels(Axis.BOTTOM, bottom_labels) 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 return chart
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')
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')