def matplotlib_demo(request): line_chart = matplotlib_renderer.LineChart(SimpleDataSource(data=data)) bar_chart = matplotlib_renderer.BarChart(SimpleDataSource(data=data)) context = {"line_chart": line_chart, "bar_chart": bar_chart} return render(request, 'demo/matplotlib.html', context)
def chartjs_demo(request): line_chart = chartjs.LineChart(SimpleDataSource(data=chartjs_sample_data), options={ "fill": False, "borderColor": "rgba(75,192,192,1)" }) bar_chart = chartjs.BarChart(SimpleDataSource(data=chartjs_sample_data)) pie_chart = chartjs.PieChart(SimpleDataSource(data=chartjs_single_series), options={ "backgroundColor": [ "#2ecc71", "#3498db", "#95a5a6", "#9b59b6", ] }) donught_chart = chartjs.DoughnutChart( SimpleDataSource(data=chartjs_single_series), options={ "backgroundColor": [ "#2ecc71", "#3498db", "#95a5a6", "#9b59b6", ] }) context = { "line_chart": line_chart, "bar_chart": bar_chart, "pie_chart": pie_chart, "donought_chart": donught_chart } return render(request, 'demo/chartjs.html', context)
def course_dashboard(request): if not check_loggedin(request): return redirect(login) lecs = databaseconnection.get_lectures(engine) if request.method == "POST": if "lec_id_ele_submit" in request.POST: request.session["lec_id_ele"] = (request.POST.get( "lec_id_ele", None)) data1 = databaseconnection.retrieve_lecture_sentiment( engine, request.session["lec_id_ele"]) data2 = databaseconnection.retrieve_lecture_rating( engine, request.session["lec_id_ele"]) from graphos.sources.simple import SimpleDataSource from graphos.renderers.yui import LineChart chart1 = LineChart(SimpleDataSource(data=data1)) chart2 = LineChart(SimpleDataSource(data=data2)) return render( request, "course_dashboard.html", { "sess_user_type": request.session["user_type"], "chart1": chart1, "chart2": chart2, "sess_lec_id": request.session["lec_id_ele"], "lecs": lecs })
def get_context_data(self, **kwargs): context = super(HighChartsDemo, self).get_context_data(**kwargs) data_source = context.get("data_source") simple_data_source = context.get("simple_data_source") line_chart = self.renderer.LineChart(data_source, options={ 'series': { 'dataLabels': { 'enabled': True }, 'lineWidth': 10 } }) secondary_data = [['year', 'revenue', 'sales'], [2004, 100, 50000], [2005, 240, 65000], [2006, 300, 55000]] context.update({ 'line_chart': line_chart, 'area_chart': self.renderer.AreaChart(data_source), 'donut_chart': self.renderer.DonutChart(data_source), 'scatter_chart': self.renderer.ScatterChart(simple_data_source), 'log_chart': self.renderer.LogarithmicChart(data_source), 'multi_axis_chart': self.renderer.MultiAxisChart(SimpleDataSource(secondary_data)), 'highmap_chart': self.renderer.HighMap( SimpleDataSource(map_data_us), options={'map_area': 'countries/us/custom/us-all-territories'}), }) return context
def get_context_data(self, **kwargs): context = super(GChartDemo, self).get_context_data(**kwargs) data_source = context['data_source'] candlestick_chart = self.renderer.CandlestickChart( SimpleDataSource(data=candlestick_data)) treemap_chart = self.renderer.TreeMapChart( SimpleDataSource(data=treemap_data)) area_chart = self.renderer.AreaChart(data_source) queryset = Account.objects.all() data_source = ModelDataSource(queryset, fields=['year', 'sales']) gauge_chart = self.renderer.GaugeChart(data_source, options={ 'redFrom': 0, 'redTo': 800, 'yellowFrom': 800, 'yellowTo': 1500, 'greenFrom': 1500, 'greenTo': 3000, 'max': 3000, }) context.update({ 'candlestick_chart': candlestick_chart, 'treemap_chart': treemap_chart, 'gauge_chart': gauge_chart, 'area_chart': area_chart }) return context
def get_context_data(self, **kwargs): super_context = super(Demo, self).get_context_data(**kwargs) create_demo_accounts() queryset = Account.objects.all() data_source = ModelDataSource(queryset, fields=['year', 'sales']) simple_data_source = SimpleDataSource(data=data) line_chart = self.renderer.LineChart(data_source, options={'title': "Sales Growth"}) column_chart = self.renderer.ColumnChart(SimpleDataSource(data=data), options={'title': "Sales/ Expense"}) bar_chart = self.renderer.BarChart(data_source, options={'title': "Expense Growth"}) pie_chart = self.renderer.PieChart(data_source) context = { "data_source": data_source, "simple_data_source": simple_data_source, "line_chart": line_chart, "column_chart": column_chart, 'bar_chart': bar_chart, 'pie_chart': pie_chart, } context.update(super_context) return context
def get_context_data(self, **kwargs): context = super(GChartDemo, self).get_context_data(**kwargs) candlestick_chart = gchart.CandlestickChart(SimpleDataSource (data=candlestick_data)) treemap_chart = gchart.TreeMapChart(SimpleDataSource(data=treemap_data)) context.update({'candlestick_chart': candlestick_chart, 'treemap_chart': treemap_chart}) return context
def home(request): chart = flot.LineChart(SimpleDataSource(data=data), html_id="line_chart") g_chart = gchart.LineChart(SimpleDataSource(data=data)) cursor = get_mongo_cursor("graphos_mongo", "zips", max_docs=100) m_data = MongoDBDataSource(cursor=cursor, fields=['_id', 'pop']) m_chart = flot.LineChart(m_data) context = {'chart': chart, 'g_chart': g_chart, 'm_chart': m_chart} return render(request, 'demo/home.html', context)
def image_graphs(request): WIDTH_COUNT = 0 HEIGHT_COUNT = 1 NUMLAYERS_COUNT = 2 FILESIZE_COUNT = 3 COLORPROFILE_COUNT = 4 response = [[], [], [], [], []] try: response[WIDTH_COUNT] = getImageInfo( "width", ["L500", "L1000", "L2000", "L4000", "L8000", "M8000", "Unknown"], "Count", "Width") response[HEIGHT_COUNT] = getImageInfo("height", [ "L500", "L1000", "L2000", "L4000", "L8000", "M8000", "Unknown"], "Count", "Height") response[NUMLAYERS_COUNT] = getImageInfo("numlayers", [ "L1", "L2", "L4", "L8", "L16", "L32", "L64", "M64", "Unknown"], "Count", "Num layers") response[FILESIZE_COUNT] = getImageInfo("filesize", [ "Mb1", "Mb5", "Mb10", "Mb25", "Mb50", "Mb100", "Mb200", "Mb400", "Mb800", "More800", "Unknown"], "Count", "File size") response[COLORPROFILE_COUNT] = getImageInfo("colorprofile", [ "RGBA", "CMYK", "Grayscale", "XYZ", "YCbCr", "Lab", "Unknown"], "Count", "Color Profile") except Exception as e: print(e) return render(request, "treeview_app/error_page.html") # DataSource object data_source = [0, 0, 0, 0, 0] data_source[WIDTH_COUNT] = SimpleDataSource(data=response[WIDTH_COUNT]) data_source[HEIGHT_COUNT] = SimpleDataSource(data=response[HEIGHT_COUNT]) data_source[NUMLAYERS_COUNT] = SimpleDataSource( data=response[NUMLAYERS_COUNT]) data_source[FILESIZE_COUNT] = SimpleDataSource( data=response[FILESIZE_COUNT]) data_source[COLORPROFILE_COUNT] = SimpleDataSource( data=response[COLORPROFILE_COUNT]) # Chart objects chart = [0, 0, 0, 0, 0] chart[WIDTH_COUNT] = BarChart(data_source[WIDTH_COUNT]) chart[HEIGHT_COUNT] = BarChart(data_source[HEIGHT_COUNT]) chart[NUMLAYERS_COUNT] = BarChart(data_source[NUMLAYERS_COUNT]) chart[FILESIZE_COUNT] = BarChart(data_source[FILESIZE_COUNT]) chart[COLORPROFILE_COUNT] = BarChart(data_source[COLORPROFILE_COUNT]) context = {'chart': chart[WIDTH_COUNT], 'chart2': chart[HEIGHT_COUNT], "chart4": chart[NUMLAYERS_COUNT], "chart6": chart[FILESIZE_COUNT], "chart8": chart[COLORPROFILE_COUNT] } return render(request, 'treeview_app/image_graphs.html', context)
def conductivity(request): data = [['DayTime', 'ConductivityProbe1', 'ConductivityProbe2']] db = MySQLdb.connect(host="localhost", user="******", passwd="raspberry", db="myproject") cur = db.cursor() cur.execute('SELECT * FROM myproject.tutorialapp_conductivity') for row in cur.fetchall(): l = [] l.append(row[0]) s = 0.0 for i in range(1, 15 + 1): s += row[i] l.append(s / 15.0) s1 = 0.0 for i in range(16, 30 + 1): s1 += row[i] l.append(s1 / 15.0) data.append(l) db.close() data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': "Conductivity"}) context = {'chart': chart} return render(request, 'tutorial/conductivity.html', context)
def get_chart_specific_data(data, chart_type, chart_kind, options={}): """ Arguments: data: [[]]: A list of lists. This should be in the format usable by SimpleDataSource chart_type: Whether we want line, or bar, or column etc. chart_kind: Whether highcharts or c3 Returns: {}: Dictionary: Keys of returned dictionary will differ based on chart_type and chart_kind. For highcharts, this dictionary must contain x_axis_title, categories, data_series etc. For c3js, this dictionary must contain c3data, x_axis_title etc. This assumes that only supported chart_type and chart_kind will be passed. """ if chart_type != 'table': data = get_formatted_data(data) simple_data_source = SimpleDataSource(data) chart_klass = get_chart_klass(chart_kind, chart_type) if chart_kind == 'highcharts': d = get_highcharts_data(chart_klass, simple_data_source, options) elif chart_kind == 'c3js': d = get_c3_data(chart_klass, simple_data_source, options) else: d = {'chart_unspecific_data': data_list} d['title'] = options.get('title') return d
def gauge_chart(gauge, days, resolution): now = timezone.now() yesterday = now - timezone.timedelta(hours=24 * days) queryset = GaugeValue.objects.filter(gauge=gauge)\ .filter(created_at__range=(yesterday, now))\ .extra({resolution: "date_trunc('"+resolution+"', created_at)"})\ .values(resolution).order_by().annotate(avg=Avg('value'))\ .order_by(resolution).all() if len(queryset) == 0: return None unit = gauge.unit if gauge.unit else "missing" a = [['Time', unit]] for row in queryset: a.append([row[resolution], row['avg']]) data_source = SimpleDataSource(data=a) title = "{} - {} dager ({:4.2f})".format(gauge.title, days, queryset.reverse()[0]['avg']) chart = LineChart(data_source, options={ 'title': title, 'curveType': 'function', }) return chart
def mapPlot(request): # Change to google maps data = [[ 'Daytime', 'Longitude', 'Latitude' ] # create a list to hold the column names and data for the axis names ] db = MySQLdb.connect( host="localhost", user="******", passwd="raspberry", db="myproject") # Access the database to get all the current data cur = db.cursor() cur.execute('SELECT * FROM myproject.tutorialapp_table_gps') for row in cur.fetchall(): # going through each row l = [] l.append( row[0] ) # append each row to the data, only get the columns that we want l.append(row[4]) l.append(row[5]) data.append(l) db.close() data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': "Coordinates"}) # Creating a line chart context = {'chart': chart} return render( request, 'tutorial/mapPlot.html', context ) # rendering the chart when a request has gone through for this page, and using the mapPlot.html to render it
def get_module_line_chart(lecture_attendances, num_students): """Get line chart for module, showing attendance per lecture over time. :param lecture_attendances: lecture attendances for module :param num_students: number of students for lecture attendances :return: line chart object to pass to template """ # Title data for chart: what is shown, and value used title_data = ['Lecture', '% Attendance'] lecture_attendance_map = OrderedDict() for lecture_attendance in lecture_attendances: # Unique lecture identifier to group lectures, and also to display on chart lecture_key = str(lecture_attendance.lecture.date) + ': \n' + lecture_attendance.lecture.session_id attendance_val = 1 if lecture_attendance.attended else 0 lecture_attendance_map.setdefault(lecture_key, 0) lecture_attendance_map[lecture_key] = lecture_attendance_map[lecture_key] + attendance_val # Build up chart data in format expected by Graphos DataSource - starting with the title data chart_data = [title_data] for lecture_key, attendance_val in lecture_attendance_map.items(): percentage_val = (attendance_val / num_students) * 100 chart_data.append([lecture_key, percentage_val]) # Return line chart with some styling configuration return LineChart(SimpleDataSource(data=chart_data), options={'title': 'Attendance per Lecture', 'pieHole': 0.4, 'colors': ['#3498db'], 'hAxis': { 'title': "Lectures", 'titleTextStyle': {'bold': True, 'italic': False} }} )
def create_js_chart(name='ERNAKULAM', html_id='highchart_div', title='ERNAKULAM'): district = Agridata.objects.filter(district_name__icontains=name) years = [ int(value[0]) for value in district.values_list('crop_year').distinct() ] averages = [(Agridata.objects.filter( district_name=name, crop_year=year).aggregate(Avg('production'))).get('production__avg') for year in years] data = [ ['Years', 'Production (Avg)'], ] for year, avg in zip(years, averages): data.append([year, avg]) sd = SimpleDataSource(data) hc = LineChart(sd, html_id, height=450, width=450, options={ 'title': title, 'xAxis': { 'title': { 'text': 'years' } }, 'style': 'float:right;' }) return hc
def player(request, parameter): t = loader.get_template("mlb_app/player.html") player = getData.getPlayerByID(parameter) if "P" in player['position_txt']: playerStats = getData.getPitcherByID(parameter) if playerStats != None: data = getData.avgStatsPitchers() graphData = [[ "Stat", player["name_display_first_last"], "MLB Average" ], ['ERA', float(playerStats['era']), data[0]], ['WHIP', float(playerStats['whip']), data[1]]] else: data = getData.avgStatsHitters() playerStats = getData.getHitterByID(parameter) if playerStats != None: graphData = [[ 'Stat', player["name_display_first_last"], 'MLB Average' ], ['Average', round(float(playerStats["avg"]), 3), data[0]], [ 'On Base Percentage', round(float(playerStats["obp"]), 3), data[1] ]] if playerStats != None: data_source = SimpleDataSource(data=graphData) chart = BarChart(data_source, width="100%") html = t.render({ 'player': player, 'playerStats': playerStats, 'chart': chart }) else: html = t.render({'player': player, 'playerStats': playerStats}) return HttpResponse(html)
def create_line_chart_consumption_sum(self): queryset = Consumption.queryset_consumption_sum_per_day() df = self.create_dataframe_for_chart_consumption_sum(queryset) list_values = self.dataframe_to_list_with_header(df) data_source = SimpleDataSource(data=list_values) chart = LineChart(data_source) return chart
def detalhar(request, pk): if request.user.tipo == 1 and str(request.user.pk) != pk: raise PermissionDenied pessoa = Usuario.objects.get(pk=pk) treinos = Treino.objects.filter(pessoa=pessoa.pk) avaliacoes = AvaliacaoFisica.objects.filter(pessoa=pessoa.pk) gordura_chart = LineChart(SimpleDataSource( gerar_grafico_gordura(avaliacoes))) gordura_chart.options['title'] = '% de gordura' perimetria_chart = LineChart(SimpleDataSource( gerar_grafico_perimetria(avaliacoes))) perimetria_chart.options['title'] = 'Perimetria' return render(request, 'aluno/detalhar.html', { 'pessoa': pessoa, 'treinos': treinos, 'avaliacoes': avaliacoes, 'gordura_chart': gordura_chart, 'perimetria_chart': perimetria_chart })
def plot(): context = {} customerQuarterProductDict = {} moreOverTime = [] with open("/Users/Rick/Desktop/projectFinalFolder/segments/customerMoreQuarterProductDictOverTime.yaml", 'r') as f: customerQuarterProductDict = yaml.load(f) f.close() with open("/Users/Rick/Desktop/projectFinalFolder/segments/moreSpentOverTime.yaml", 'r') as f: moreOverTime = yaml.load(f) f.close() Quarterly_list = [] count = 0 for houseKey in moreOverTime: for houseHoldKey, quarterDict in customerQuarterProductDict.items(): if houseKey == houseHoldKey: if count < 10: Quarterly_list = [['Category', 'Sale_value']] for quarterNo, categoryDict in quarterDict.items(): for item, saleValue in categoryDict.items(): Quarterly_list.append([str(quarterNo) +"_" + item, saleValue]) print houseHoldKey,Quarterly_list data = Quarterly_list data_source = SimpleDataSource(data) chart = BarChart(data_source, height=500, width=500, options={'title': 'Quarterly_list'}) context['chart'+str(count)] = chart context['house'+str(count)]= houseHoldKey count = count+ 1
def tutorial(request): chart = flot.LineChart(SimpleDataSource(data=data), html_id="line_chart") url = "https://raw.github.com/agiliq/django-graphos/master/README.md" str = urllib2.urlopen(url).read() readme = markdown.markdown(str) context = {'chart': chart, "readme": readme} return render(request, 'demo/tutorial.html', context)
def results(request): charts = [] for question in Question.objects.all(): data = [] data.append(['answer', 'votes']) for answer in question.answer_set.all(): list_tmp = [] list_tmp.append(answer.answer_txt) list_tmp.append(answer.answer_votes) data.append(list_tmp) charts.append( ColumnChart(SimpleDataSource(data=data), options={ 'title': str(question.question_txt), 'legend': { 'position': 'bottom' }, 'titleTextStyle': { 'color': 'black', 'fontSize': 22 }, 'colors': ['#ff9400'] })) context = { 'questions': Question.objects.all(), 'title': 'Survey Results', 'survey': Survey.objects.first(), 'charts': charts, } return render(request, 'survey/results.html', context)
def get_context_data(self, **kwargs): context_data = super(SessionChart, self).get_context_data(**kwargs) if not self.client: return context_data data = [('Date', 'Sessions Created')] date_dict = defaultdict(int) for row in models.RequestEvent.objects.values('tracking_key').annotate( new_date=Min('created')).filter( new_date__range=[self.start_date, self.end_date], client=self.client): date_dict[row['new_date'].strftime('%Y-%m-%d')] += 1 d = self.start_date while d <= self.end_date: data.append( (d.strftime('%Y-%m-%d'), date_dict[d.strftime('%Y-%m-%d')])) d += timedelta(days=1) chart = gchart.LineChart(SimpleDataSource(data=data), height=500, width=570, options={ 'title': 'Sessions Created', 'legend': 'none', }) context_data.update({'chart': chart}) return context_data
def plots(request, data_id): vs = VoltageSample.objects.all().filter(id=data_id)[0] if vs: if vs.raw: data = [['Time(seconds)', 'ADC Output']] vaxis = {'title': 'ADC Output'} else: data = [['Time(seconds)', 'Voltage']] vaxis = {'title': 'Volts'} samples = [] i = 0 for d in vs.data: val = [str(i), d] samples.append(val) i = round(i + (1 / vs.freq), 2) data.append(val) # DataSource object data_source = SimpleDataSource(data=data) # Chart object options = { 'title': 'Voltage vs Time', 'vAxis': vaxis, 'hAxis': { 'title': 'Seconds', 'minValue': 0, 'viewWindowMode': 'maximized' } } chart = LineChart(data_source, height=500, width=1000, options=options) context = {'chart': chart, 'points': vs.data, 'freq': vs.freq} return render(request, 'plot.html', context)
def professorResults(request): tempFinishedAssignment = FinishedAssignment.objects.all() tempAssignment = Assignment.objects.all() scoreList = [] data = [['Øving', 'Gruppens Resultat']] #Sorts by assignment. Finds all answered assignments. Tallies scores and adds to graph if request.user.groups.filter(name="Professors").exists(): for assignment in tempAssignment: scoreTotal = 0 for finishedAssignment in tempFinishedAssignment: if finishedAssignment.assignment.assignmentName == assignment.assignmentName: scoreTotal = +finishedAssignment.score data.append([assignment.assignmentName, scoreTotal]) scoreList.append(scoreTotal) studentScore = SimpleDataSource(data=data) chart = LineChart(studentScore, options={'title': "Resultater"}) return render(request, 'professorResults.html', { 'results': tempAssignment, 'score': scoreList, 'chart': chart }) if request.user.groups.filter(name="Students").exists(): return redirect('results') else: return redirect('index')
def create_chart(array, name='Genre'): arrayCount = collections.Counter(array) # Creating a pie chart data = [[name, 'Count']] count = 0 for key in arrayCount: data.append([key, arrayCount[key]]) count += 1 # Create a data source object dataSource = SimpleDataSource(data=data) # Chart object chart = PieChart(dataSource, options={ 'title': 'Genres', 'width': 450, 'height': 250 }) return chart
def vertical(request): data = [ ['Time', 'V1', 'V2', 'VD'] # create a list to hold the column names and data for the axis names ] minstringint = datetime.strptime(request.GET.get('min','2000-01-01T10:00:00'),"%Y-%m-%dT%H:%M:%S").replace(tzinfo=dt.timezone.utc) maxstringint = datetime.strptime(request.GET.get('max','2020-12-25T10:00:00'),"%Y-%m-%dT%H:%M:%S").replace(tzinfo=dt.timezone.utc) ordered_fastmeasurements = models.FastMeasurement.objects.filter(global_id__global_id__transmit_time__gte=minstringint).filter(global_id__global_id__transmit_time__lte=maxstringint).order_by('global_id', 'sub_id') #print(len(ordered_fastmeasurements)) scalar = 0.000125 if request.GET.get('volts','') == 'True' else 1 top = 99999 if not request.GET.get('top','') else float(request.GET.get('top','')) bottom = -99999 if not request.GET.get('bottom','') else float(request.GET.get('bottom','')) onlyWantedData = [] wantedimei = request.GET.get('imei','*') if(wantedimei == "CollinsLaptop"): wantedimei = "888888888888888" for x in ordered_fastmeasurements: if(wantedimei == '*' or wantedimei == str(x.global_id.global_id.imei)): onlyWantedData.append([x.global_id.global_id.transmit_time+x.sub_id*timedelta(seconds=5),x.vert1*scalar if x.vert1*scalar <= top and x.vert1*scalar >= bottom else top if x.vert1*scalar > top else bottom,x.vert2*scalar if x.vert2*scalar <= top and x.vert2*scalar >= bottom else top if x.vert2*scalar > top else bottom,x.vertD*scalar if x.vertD*scalar <= top and x.vertD*scalar >= bottom else top if x.vertD*scalar > top else bottom]) #minstringint = int(request.GET.get('min','0')) #maxstringint = int(request.GET.get('max','999999')) wantedimei = request.GET.get('imei','*') onlyReallyWantedData = [] for x in onlyWantedData: if True: #if(x[0] >= minstringint and x[0] <= maxstringint): onlyReallyWantedData.append(x) data = data + onlyReallyWantedData chartTitle = "Vertical Measurements" chartDescription = "This is a test graph generated from all of the fast measurement data.\n This is mostly for demonstration.\n Please enjoy." data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': chartTitle}) # Creating a line chart context = {'chart': chart, 'title': chartTitle, 'description': chartDescription} return render(request, 'groundstation/graph.html', context)
def productAnalysis(request): context = {} productAnalysis = {} with open( '/Users/Rick/Desktop/projectFinalFolder/srcCopy/plot/customerProductAnalysis.yaml', 'r') as f: customerProductAnalysis = yaml.load(f) f.close() count = 0 for household_key, eachQuarter in customerProductAnalysis.items(): Quarter_list = [['Category', 'Quarter', 'Revenue']] for quarter, quarter_data in eachQuarter.items(): for prod, quant in quarter_data.iteritems(): if quant == 0: continue Quarter_list.append([prod, (quarter), quant]) data = Quarter_list data_source = SimpleDataSource(data) chart = BarChart(data_source, options={ 'lineWidth': 15, 'smooth': False }) context['chart' + str(count)] = chart context['house' + str(count)] = household_key count = count + 1 print Quarter_list return render(request, 'productAnalysis.html', context)
def comparechart(post1, post2, compare1, compare2): data = [] templist = ['status'] templist.append(post1) templist.append(post2) data.append(templist) d1 = {} d2 = {} d1 = draw_chart1(compare1) d2 = draw_chart1(compare2) candidate1 = d1['data'] candidate2 = d2['data'] # agendapercent=[] # ['completed', 20, 40, 20] # ['Completed', 31.03448275862069], for i in range(1, 8): agendapercent = [] agendapercent.append(candidate1[i][0]) agendapercent.append(candidate1[i][1]) agendapercent.append(candidate2[i][1]) if agendapercent[1] or agendapercent[2]: data.append(agendapercent.copy()) print("abc:") print(data) data_source = SimpleDataSource(data=data) # Chart object chart = gchart.ColumnChart(data_source) return chart
def Graphos(request): data = [ ['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit', 'All'], ['2004', 1000, 400, 100, 600, 100], ['2005', 1170, 460, 120, 310, 100], ['2006', 660, 1120, 50, -460, 100], ['2007', 1030, 540, 100, 200, 100], ] from graphos.sources.simple import SimpleDataSource from graphos.renderers.gchart import LineChart from graphos.renderers.gchart import ColumnChart from graphos.renderers.gchart import BarChart from graphos.renderers.gchart import PieChart from graphos.renderers.gchart import AreaChart from graphos.renderers.gchart import TreeMapChart from graphos.renderers.gchart import CandlestickChart from graphos.renderers.gchart import GaugeChart # from graphos.renderers.highcharts import LineChart # DataSource object data_source = SimpleDataSource(data=data) # Chart object chart = LineChart(data_source) chart1 = BarChart(data_source) context = {'chart': chart, 'chart1': chart1 } return render(request, 'char.html', context)
def report(request): url = "http://localhost:3000/api/org.apache.tvmnetwork.Idea" r = requests.get(url) i = r.json() idea_count = {} tvm_count = sum( x.get('owner') == 'resource:org.apache.tvmnetwork.Team#TVM' for x in i) rtm_count = sum( x.get('owner') == 'resource:org.apache.tvmnetwork.Team#RTM' for x in i) fin_count = sum( x.get('owner') == 'resource:org.apache.tvmnetwork.Team#FIN' for x in i) idea_count['TVM'] = tvm_count idea_count['RTM'] = rtm_count idea_count['FIN'] = fin_count data = [['Team', 'No. of Ideas'], ['TVM', tvm_count], ['RTM', rtm_count], ['FIN', fin_count]] # DataSource object data_source = SimpleDataSource(data=data) # Chart object chart = gcolumn(data_source, options={'title': 'Idea Distribution'}) chart1 = fline(data_source) # context = {'chart': chart} # return render(request, 'yourtemplate.html', context) return render(request, 'ideas_report.html', { 'chart': chart, 'chart1': chart1 })