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 get(self, request, *args, **kwargs): appointments = AppointmentHistoryModel.objects.values() wait_time_count = 0 wait_time_duration = 0 delay_time_count = 0 delay_time_duration = 0 no_show = 0 extra_time = 0 extra_time_duration = 0 d=0 e=0 for j in appointments: print([j['statusTime'], j['status'], j['session_start_time'],j['session_end_time'], j['appointment_start_time']]) print("\n") if j['session_end_time'] is not None: d = j['session_end_time'] - j['session_start_time'] d = divmod(d.days * 86400 + d.seconds, 60) d = d[0] e = j['session_end_time'] - j['appointment_start_time'] e = divmod(e.days * 86400 + e.seconds, 60) e = e[0] if j['session_end_time'] is not None: wait_time_count = wait_time_count + 1 diff = j['session_start_time'] - j['statusTime'] datetime.timedelta(0, 8, 562000) m_s = divmod(diff.days * 86400 + diff.seconds, 60) wait_time_duration = wait_time_duration + m_s[0] # Patients Wait TIme = Session Start Time - Status Change Time if j['statusTime'] is not None and j['statusTime'] > j['appointment_start_time'] : delay_time_count = delay_time_count + 1 diff = j['statusTime'] - j['appointment_start_time'] datetime.timedelta(0, 8, 562000) m_s = divmod(diff.days * 86400 + diff.seconds, 60) delay_time_duration = delay_time_duration + m_s[0] # Patients Delay TIme = Appointment Start Time - Status Change Time if j['status'] not in [ DrChrono_Shortcuts.Statuses.ARRIVED , DrChrono_Shortcuts.Statuses.IN_SESSION, DrChrono_Shortcuts.Statuses.COMPLETE, DrChrono_Shortcuts.Statuses.NOT_CONFIRMED , DrChrono_Shortcuts.Statuses.NOT_MENTIONED]: no_show = no_show + 1 if d<1800 and e>1800: extra_time = extra_time + 1 extra_time_duration = extra_time_duration + 1 da = [p['status'] for p in appointments] counts = Counter(da) d =[] d = [[k, counts[k]] for k in counts ] d.insert(0,["Status","Number of hits"]) d.append(["In Session",1]) data_source2 = SimpleDataSource(data=d) metrics=dict() metrics["wait_time_count"] = int(wait_time_count) metrics["wait_time_duration"] = wait_time_duration metrics["delay_time_count"] = int(delay_time_count) metrics["delay_time_duration"] = delay_time_duration metrics["no_show"] = int(no_show) metrics["extra_time"] = int(extra_time) metrics["extra_time_duration"] = extra_time_duration context = {'metrics':metrics, 'pc':PieChart(data_source2,options={'title': "Statuses of all Appointments"})} return render(request, self.template_name, context)
def show_counts_by_source(request): _counts = NewsDB().counts_by_source() data_source = SimpleDataSource(data=_counts) # Chart object chart = PieChart(data_source, options={"title": "Articles by Source"}) return render( request, "newsfeed/sources.html", { "num_of_sources": len(_counts) - 1, "chart": chart, "meta_keywords": META_KEYWORDS })
def build_attendance_pie_chart(request, attended_percent, non_attended_percent, title): # Data format: # data = [ # ...[ Title, Value ] # ] # Build up chart data in format expected by Graphos DataSource - starting with the title data title_data = ['Attendance', 'Attended?'] attendance_data = ['Attended', attended_percent] non_attendance_data = ['Absent', non_attended_percent] chart_data = [title_data, non_attendance_data, attendance_data] colors = ViewsUtils().get_pass_fail_colours_2_tone(request) return PieChart(SimpleDataSource(data=chart_data), options={'title': title, 'pieHole': 0.4, 'colors': colors})
def draw(request): queryset = Location.objects.filter(user__pk=request.user.id) data_source = ModelDataSource(queryset, fields=['place', 'population']) if request.method == 'GET' and not 'charts' in request.GET: chart = BarChart(data_source) elif request.GET['charts'] == "BarChart": chart = BarChart(data_source) elif request.GET['charts'] == "LineChart": chart = LineChart(data_source) elif request.GET['charts'] == "PieChart": chart = PieChart(data_source) elif request.GET['charts'] == "ColumnChart": chart = ColumnChart(data_source) context = {'chart': chart} return render(request, 'my_charts/draw.html', context)
def display(request): posts = list(models.form_data.objects.all().values_list('name', 'value')) posts = [list(a) for a in posts] # Chart object end_table_data = [] value_of_bonds = posts[-4][1] value_of_return = posts[-3][1] value_of_volatility = posts[-2][1] value_of_amount = posts[-1][1] volatility_per = posts[-2] returns_per = posts[-3] posts = posts[0:-3] first_graph_data = posts for x in range(len(first_graph_data)): if(x < len(first_graph_data) - 1): first_graph_data[x][1] = first_graph_data[x][1] * (1 - value_of_bonds) first_graph_data.insert(0,['Companies','Values']) data_source = SimpleDataSource(data=first_graph_data) chart1 = PieChart(data_source, html_id='piechart_id', options={'pieHole' : 0.4, 'title': 'Percentage to invest'}) now = [] if_high = [] if_low = [] expected = [] area_graph = [] for x in range(0,13): now.append(value_of_amount) for x in range(0,13): xxx = (value_of_bonds * value_of_amount) xxx = xxx + (xxx * 0.1108) xx = ((1 - value_of_bonds) * value_of_amount) xx = xx + (((value_of_return + value_of_volatility)/12) * x * xx) if_high.append(xx + xxx) for x in range(0,13): xxx = (value_of_bonds * value_of_amount) xxx = xxx + (xxx * 0.1108) xx = ((1 - value_of_bonds) * value_of_amount) xx = xx + (((value_of_return - value_of_volatility)/12) * x * xx) if_low.append(xx + xxx) for x in range(0,13): xxx = (value_of_bonds * value_of_amount) xxx = xxx + (xxx * 0.1108) xx = ((1 - value_of_bonds) * value_of_amount) xx = xx + (((value_of_return)/12) * x * xx) expected.append(xx + xxx) for i in range(0,13): if (i == 0): area_graph.append(['Month','Saved','Max Profit','Min Profit','Expected Profit']) else: area_graph.append([i, now[i], if_high[i], if_low[i], expected[i]]) data_source1 = SimpleDataSource(data=area_graph) chart2 = AreaChart(data_source1,html_id='piechart_id2', options={'title': 'Future Projections'}) end_table_data = list(first_graph_data) end_table_data = end_table_data[1:] end_table_data.insert(0, [returns_per[0], returns_per[1] * 100]) end_table_data.insert(0, [volatility_per[0], volatility_per[1] * 100]) for x in range(len(end_table_data)): if (x < 2): end_table_data[x] = end_table_data[x][0] + ' - ' + str(int(end_table_data[x][1])) + ' %' else: end_table_data[x] = end_table_data[x][0] + ' - ' + 'Rs ' + str(int(end_table_data[x][1] * value_of_amount)) context = {'Portfolio': chart1 , 'Data' : chart2, 'End': end_table_data} return render(request,'displaypage/graphs.html', context)
def empresa_visualizacion(request, pk): empresa = get_object_or_404(Empresa, pk=pk) empresa_pk = 0 if request.user.is_authenticated: usuario = Usuario.objects.get(user=request.user.id) empresa_pk = usuario.id_empresa.pk consumosPorAño = [] consumosPorAño = Consumo.objects.filter( id_empresa=pk).values('año').annotate(consumo=Sum('consumo')) datosChart1 = [['Año', 'Consumo total']] for consumo in consumosPorAño: datosChart1.append([consumo['año'], int(consumo['consumo'])]) consumosPorActivo = [] consumosPorActivo = Consumo.objects.filter( id_empresa=pk).values('id_activo').annotate(consumo=Sum('consumo')) datosChart2 = [['Activo', 'Consumo total']] for consumo in consumosPorActivo: nombreActivo = Activo.objects.filter(pk=consumo['id_activo']) datosChart2.append([str(nombreActivo[0]), int(consumo['consumo'])]) consumosPorTipo = [] consumosPorTipo = Consumo.objects.filter( id_empresa=pk).values('tipo').annotate(consumo=Sum('consumo')) datosChart3 = [['Tipo', 'Consumo total']] for consumo in consumosPorTipo: datosChart3.append([str(consumo['tipo']), int(consumo['consumo'])]) # DataSource object data_source1 = SimpleDataSource(data=datosChart1) data_source2 = SimpleDataSource(data=datosChart2) data_source3 = SimpleDataSource(data=datosChart3) # Chart object chart1 = ColumnChart(data_source1, options={'title': 'Consumo total por año'}) chart2 = PieChart(data_source2, options={'title': 'Consumo total por activo'}) chart3 = PieChart(data_source3, options={'title': 'Consumo total por tipo'}) return render( request, 'empresa_visualizacion.html', { 'empresa': empresa, 'empresa_pk': empresa_pk, 'titulo': 'Graficos', 'chart1': chart1, 'chart2': chart2, 'chart3': chart3 }) else: consumosPorAño = [] consumosPorAño = Consumo.objects.filter( id_empresa=pk).values('año').annotate(consumo=Sum('consumo')) datosChart1 = [['Año', 'Consumo total']] for consumo in consumosPorAño: datosChart1.append([consumo['año'], int(consumo['consumo'])]) consumosPorActivo = [] consumosPorActivo = Consumo.objects.filter( id_empresa=pk).values('id_activo').annotate(consumo=Sum('consumo')) datosChart2 = [['Activo', 'Consumo total']] for consumo in consumosPorActivo: nombreActivo = Activo.objects.filter(pk=consumo['id_activo']) datosChart2.append([str(nombreActivo[0]), int(consumo['consumo'])]) consumosPorTipo = [] consumosPorTipo = Consumo.objects.filter( id_empresa=pk).values('tipo').annotate(consumo=Sum('consumo')) datosChart3 = [['Tipo', 'Consumo total']] for consumo in consumosPorTipo: datosChart3.append([str(consumo['tipo']), int(consumo['consumo'])]) # DataSource object data_source1 = SimpleDataSource(data=datosChart1) data_source2 = SimpleDataSource(data=datosChart2) data_source3 = SimpleDataSource(data=datosChart3) # Chart object chart1 = ColumnChart(data_source1, options={'title': 'Consumo total por año'}) chart2 = PieChart(data_source2, options={'title': 'Consumo total por activo'}) chart3 = PieChart(data_source3, options={'title': 'Consumo total por tipo'}) return render( request, 'empresa_visualizacion.html', { 'empresa': empresa, 'titulo': 'Graficos', 'chart1': chart1, 'chart2': chart2, 'chart3': chart3 })
def get_url_info(self, request, hash): try: rows = url.objects.filter(hash=hash).values() result_data = {} if rows: # get url result_url = rows[0] if result_url is not None: # links result_links = media.objects.raw( 'SELECT *, (SELECT name FROM media WHERE id = url_link.media_id) as mediaName FROM url_link WHERE url_id = ' + str(result_url['id'])) # count result_sum = analytics.objects.filter( url_id=str(result_url['id'])).count() result_count = analytics.objects.raw( 'SELECT *, count(1) AS result FROM count WHERE url_id = ' + str(result_url['id']) + ' GROUP BY count') result_count_per_date = analytics.objects.raw( 'SELECT *, count(1) AS count, DATE(CONVERT_TZ(created_at, \'UTC\',\'Asia/Seoul\')) AS date, count(case when referer like "%%facebook%%" then 1 end) as facebook FROM analytics WHERE url_id = ' + str(result_url['id']) + ' GROUP BY DATE(CONVERT_TZ(created_at, \'UTC\',\'Asia/Seoul\'))' ) for count in result_count_per_date: temp_count = {} temp_count['date'] = count.created_at temp_count['result'] = count.count print(str(temp_count)) # analytics result_analytics = {} result_analytics['referer'] = analytics.objects.raw( "SELECT *, count(1) as count, SUBSTR(referer, 1 , IF(LOCATE('/', referer, 9), LOCATE('/', referer, 9)-1, LENGTH(referer))) as urlHost FROM analytics WHERE url_id = " + str(result_url['id']) + " GROUP BY urlHost ORDER BY count DESC") # graph os_query = analytics.objects.raw( 'SELECT *, count(1) as count FROM analytics WHERE url_id = ' + str(result_url['id']) + ' GROUP BY os ORDER BY count DESC') browser_query = analytics.objects.raw( 'SELECT *, count(1) as count FROM analytics WHERE url_id = ' + str(result_url['id']) + ' GROUP BY browser ORDER BY count DESC') temp_os_data = ModelDataSource(os_query, fields=['os', 'count']) temp_browser_data = ModelDataSource( browser_query, fields=['browser', 'count']) result_analytics['os'] = PieChart(temp_os_data) result_analytics['browser'] = PieChart(temp_browser_data) # media result_media = media.objects.all() # mapping result_data['url'] = result_url result_data['links'] = result_links result_data['sum'] = result_sum result_data['counts'] = result_count result_data['analytics'] = result_analytics result_data['countsPerDate'] = result_count_per_date result_data['medias'] = result_media return render(request, 'url_info.html', result_data) except Exception as e: print('- url_detail_controller GET error ' + str(datetime.datetime.now(tz=pytz.timezone('Asia/Seoul')))) exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) print(''.join('* ' + line for line in lines)) return Response("failed to get url info", status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def results(request, analysis_id): #form = InputForm(request.POST) # check for 0 values e.g. in amt_years!! #data=form.cleaned_data data = Analysis.objects.filter(id=analysis_id).values()[0] total_cost = data['price'] + data['repair_cost'] + data['closing_cost'] down = int(data['price'] * data['down_payment'] / 100) loan_amt = data['price'] - down R = data['loan_rate'] / 100 / 12 # periodic interest rate monthly_PI = float( (loan_amt * R) / (1 - (1 + R)**(-12 * data['amt_years']))) total_cash = data['closing_cost'] + down + data[ 'repair_cost'] + data['loan_points'] / 100 * loan_amt monthly_in = data['rent'] + data['other_income'] monthly_ex=float(data['electric']+data['water_sewer']+data['pmi']+data['garbage']+data['hoa']+data['insurance']+data['taxes']+data['ex_other']) \ + float(monthly_in*(data['vacancy']+data['repairs']+data['cap_ex']+data['management'])/100) \ + float(monthly_PI) monthly_cf = monthly_in - monthly_ex NOI = (monthly_in - monthly_ex + monthly_PI) * 12 pro_forma_cap = NOI / data['arv'] CoC_roi = monthly_cf * 12 / total_cash purchase_cap = NOI / data['price'] percent_rule = monthly_in / data['price'] * 100 initial_equity = data['arv'] - data['price'] - data['repair_cost'] + down GRM = data['price'] / (monthly_in * 12) DCR = NOI / (12 * monthly_PI) # calculate cash flow by purchase price price_bot = 50000 price_top = 150000 price_inc = 500 cf_by_price = [['Offer', 'Cash Flow']] CoC_by_price = [['Offer', 'Cash on Cash Return']] for cur_price in range(price_bot, price_top + 1, price_inc): cur_down = int(cur_price * data['down_payment'] / 100) cur_loan_amt = cur_price - cur_down cur_PI = float( (cur_loan_amt * R) / (1 - (1 + R)**(-12 * data['amt_years']))) cur_ex = monthly_ex - monthly_PI + cur_PI # everything else is fixed so just adjust PI #### currently not accounting for PMI! cf_by_price.append([cur_price, monthly_in - cur_ex]) CoC_by_price.append( [cur_price, (monthly_in - cur_ex) * 12 / total_cash]) # initialize yearly values with first year and rest 0s yearly_in = [monthly_in * 12] + [0] * (data['amt_years'] - 1) yearly_ex = [monthly_ex * 12] + [0] * (data['amt_years'] - 1) yearly_mg = [monthly_PI * 12] * (data['amt_years']) # constant yearly_op = [yearly_ex[0] - yearly_mg[0]] + [0] * (data['amt_years'] - 1) yearly_cf = [yearly_in[0] - yearly_ex[0]] + [0] * (data['amt_years'] - 1) yearly_cc = [yearly_cf[0] / total_cash * 100 ] + [0] * (data['amt_years'] - 1) yearly_pv = [ data['arv'] + data['arv'] * data['annual_propvalue_growth'] / 100 ] + [0] * (data['amt_years'] - 1) yearly_ba = [get_loan_balance(loan_amt, monthly_PI, data['loan_rate']) ] + [0] * (data['amt_years'] - 1) yearly_eq = [yearly_pv[0] - yearly_ba[0]] + [0] * (data['amt_years'] - 1) yearly_pr = [ yearly_pv[0] - yearly_ba[0] - total_cash - (data['sales_ex'] / 100 * yearly_pv[0]) + yearly_cf[0] ] + [0] * (data['amt_years'] - 1) yearly_ar = [yearly_pr[0] / total_cash] + [0] * (data['amt_years'] - 1) # now fill in the rest of the years for i in range(1, data['amt_years']): yearly_in[i] = yearly_in[ i - 1] + yearly_in[i - 1] * data['annual_income_growth'] / 100 yearly_op[i] = yearly_op[ i - 1] + yearly_op[i - 1] * data['annual_ex_growth'] / 100 yearly_ex[i] = yearly_op[i] + yearly_mg[i] yearly_cf[i] = yearly_in[i] - yearly_ex[i] yearly_cc[i] = yearly_cf[i] / total_cash * 100 yearly_pv[i] = yearly_pv[ i - 1] + yearly_pv[i - 1] * data['annual_propvalue_growth'] / 100 yearly_ba[i] = get_loan_balance(yearly_ba[i - 1], monthly_PI, data['loan_rate']) yearly_eq[i] = yearly_pv[i] - yearly_ba[i] total_cf = yearly_cf[0] for j in range(1, i + 1): total_cf = total_cf + yearly_cf[j] yearly_pr[i] = yearly_pv[i] - yearly_ba[i] - total_cash - ( data['sales_ex'] / 100 * yearly_pv[i]) + total_cf yearly_ar[i] = (1 + yearly_pr[i] / total_cash)**(1 / i + 1) - 1 # designate which years to tabulate if (data['amt_years'] < 11): show_years = list(range(0, data['amt_years'])) elif (data['amt_years'] < 16): show_years = [1, 2, 5, 10] + [data['amt_years']] elif (data['amt_years'] < 21): show_years = [1, 2, 5, 10, 15] + [data['amt_years']] elif (data['amt_years'] < 26): show_years = [1, 2, 5, 10, 15, 20] + [data['amt_years']] elif (data['amt_years'] < 31): show_years = [1, 2, 5, 10, 15, 20] + [data['amt_years']] else: show_years = [1, 2, 5, 10, 15, 20, 30] + [data['amt_years']] vals = { 'title': data['address_st'] + ', ' + data['address_city'] + ', ' + data['address_state'] + ' ' + data['address_zip'], 'price': data['price'], 'closing_cost': data['closing_cost'], 'repair_cost': data['repair_cost'], 'total_cost': total_cost, 'arv': data['arv'], 'down': down, 'loan_amt': loan_amt, 'loan_points': data['loan_points'] / 100 * loan_amt, 'amt_years': data['amt_years'], 'loan_rate': data['loan_rate'], 'monthly_PI': monthly_PI, 'monthly_in': monthly_in, 'monthly_ex': monthly_ex, 'monthly_cf': monthly_cf, 'pro_forma_cap': pro_forma_cap * 100, 'NOI': NOI, 'total_cash': total_cash, 'CoC_roi': CoC_roi * 100, 'purchase_cap': purchase_cap * 100, 'yearly_in': yearly_in, 'yearly_ex': yearly_ex, 'yearly_mg': yearly_mg, 'yearly_op': yearly_op, 'yearly_cf': yearly_cf, 'yearly_cc': yearly_cc, 'yearly_pv': yearly_pv, 'yearly_ba': yearly_ba, 'yearly_eq': yearly_eq, 'yearly_pr': yearly_pr, 'yearly_ar': yearly_ar, 'show_years': show_years, 'show_years_index': [x - 1 for x in show_years] } ### plotting with graphos ### ## pie chart piechart_list = [['Category', 'Amount']] # fixed expenses ex_display_names = { 'electric': 'Electric', 'water_sewer': 'Water & Sewer', 'pmi': 'PMI', 'garbage': 'Garbage', 'hoa': 'HOA', 'insurance': 'Insurance', 'taxes': 'Taxes', 'ex_other': 'Other' } for ex in [ 'electric', 'water_sewer', 'pmi', 'garbage', 'hoa', 'insurance', 'taxes', 'ex_other' ]: if (data[ex] > 0): piechart_list.append([ex_display_names[ex], data[ex]]) # percentage of income expenses ex_display_names = { 'vacancy': 'Vacancy', 'repairs': 'Repairs', 'cap_ex': 'CapEx', 'management': 'Management' } for ex in ['vacancy', 'repairs', 'cap_ex', 'management']: if (data[ex] > 0): piechart_list.append( [ex_display_names[ex], data[ex] / 100 * monthly_in]) if (monthly_PI > 0): piechart_list.append(['Mortgage', monthly_PI]) piechart = PieChart(SimpleDataSource(data=piechart_list), options={ 'title': 'Expenses', 'titleTextStyle': { 'fontSize': 16 } }) ## line chart linechart_list = [['Year', 'Income', 'Expenses', 'Cash Flow']] for i in range(0, data['amt_years']): linechart_list.append( [i + 1, yearly_in[i], yearly_ex[i], yearly_cf[i]]) linechart = LineChart(SimpleDataSource(data=linechart_list), html_id='linechart_div', width=600, options={ 'title': 'Income, Expenses, and Cash Flow', 'vAxis': { 'format': '$###,###' }, 'hAxis': { 'title': 'Years' }, 'titleTextStyle': { 'fontSize': 16 } }) ## area chart areachart_list = [['Year', 'Loan Balance', 'Equity', 'Property Value']] for i in range(0, data['amt_years']): areachart_list.append( [i + 1, yearly_ba[i], yearly_eq[i], yearly_pv[i]]) areachart = AreaChart(SimpleDataSource(data=areachart_list), html_id='areachart_div', width=600, options={ 'title': 'Loan Balance, Value, and Equity', 'vAxis': { 'format': '$###,###' }, 'hAxis': { 'title': 'Years' }, 'titleTextStyle': { 'fontSize': 16 } }) ## cash flow by offer chart cfchart = LineChart(SimpleDataSource(data=cf_by_price), html_id='cfchart_div', width=600, options={ 'title': 'Monthly Cashflow by Offer Amount', 'vAxis': { 'title': 'Cashflow', 'format': '$###,###' }, 'hAxis': { 'title': 'Offer Amount', 'format': '$###,###' }, 'legend': { 'position': 'none' }, 'titleTextStyle': { 'fontSize': 16 } }) cocchart = LineChart(SimpleDataSource(data=CoC_by_price), html_id='cocchart_div', width=600, options={ 'title': 'Cash on Cash Return by Offer Amount', 'vAxis': { 'title': 'Cash on Cash Return', 'format': 'percent' }, 'hAxis': { 'title': 'Offer Amount', 'format': '$###,###' }, 'legend': { 'position': 'none' }, 'titleTextStyle': { 'fontSize': 16 } }) # return render(request, 'selected_data.html',{'fields':fields,'fields_day1':fields_day1,'fields_bat':fields_bat,'fields_img':fields_img,'fields_snp':fields_snp,'subj_data_tuples':subj_data_tuples}) return render( request, 'output.html', { 'vals': vals, 'piechart': piechart, 'linechart': linechart, 'areachart': areachart, 'cfchart': cfchart, 'cocchart': cocchart })
def get_context_data(self, **kwargs): context = super(Dashboard, self).get_context_data(**kwargs) # Warn the user if we don't have an available Launch Window has_one_window = False next_window = None launch_windows = LaunchWindow.objects.all() for window in launch_windows: current_date = datetime.now() next_window = croniter(window.cron_format, current_date).get_next(datetime) if (next_window - datetime.now()).seconds < 61: has_one_window = True break if not has_one_window and launch_windows.exists(): messages.add_message( self.request, messages.ERROR, 'No available Launch Windows! Next window on %s @ %s' % (format_date(next_window), format_time(next_window))) # Deployment Stats Data # Build pie chart data to show % projects deployed successfully deployments = Deployment.active_records.order_by('status').values( 'status').annotate(count=Count('id')) items = [['string', 'number']] + [[item['status'], item['count']] for item in deployments] context['pie_chart'] = PieChart(SimpleDataSource(items), width='100%', height=300, options={'title': ''}) # Deployment History Data # Get all projects with the days they were deployed and the count of the deploys on each day chart_data = [] projects = list(Project.active_records.all()) if len(projects) == 0: return context deploys = list( Deployment.objects.select_related('stage').order_by( 'date_created')) # Get the date range for all the deployments ever done start_date = (timezone.now() - timedelta(days=60)).date() end_date = timezone.now().date() # Step through each day and create an array of deployment counts from each project # this would be much easier if we could aggregate by day. # once we can use django 1.7, we could write a __date transform. Then it would work. for day in range(-1, (end_date - start_date).days + 1): date = start_date + timedelta(days=day) if day == -1: data = ['Day'] else: data = [date.strftime('%m/%d')] for project in projects: if day == -1: data.append(project.name) continue count = 0 for d in deploys: if d.stage.project_id == project.pk and d.date_created.date( ) == date: count += 1 data.append(count) chart_data.append(data) context['line_chart'] = LineChart(SimpleDataSource(chart_data), width='100%', height=300, options={'title': ''}) return context
def get_pie(request): if 'pie_category' not in request.GET or request.GET[ 'pie_category'] == 'all': pie_data = [['Task Type', "Completed"]] non_zero = False for cat in [ 'Homework', 'Chore', 'Work', 'Errand', 'Lifestyle', 'Others' ]: num_completed = len( Task.objects.filter(user=request.user.id, completed=True, category=cat)) pie_data.append([cat, num_completed]) non_zero = (num_completed > 0) or non_zero if non_zero: pie = PieChart(SimpleDataSource(pie_data), options={ 'title': 'Tasks Completed by Category', 'width': 1050 }).as_html() else: pie = "No completed tasks to display." else: pie_data = [["Task Status", "Count"]] num_completed = len( Task.objects.filter(user=request.user.id, completed=True, category=request.GET['pie_category'])) num_uncompleted = len( Task.objects.filter(user=request.user.id, completed=False, category=request.GET['pie_category'])) completed_late = len( Task.objects.filter(user=request.user.id, completed=True, date_completed__gt=F('end_time'), category=request.GET['pie_category'])) uncompleted_late = len( Task.objects.filter(user=request.user.id, end_time__lt=datetime.datetime.now(), date_completed__isnull=True, category=request.GET['pie_category'])) pie_data.append(['Completed: On-time', num_completed - completed_late]) pie_data.append(['Completed: Late', completed_late]) pie_data.append([ 'Not completed: Not Yet Late', num_uncompleted - uncompleted_late ]) pie_data.append(['Not completed: Late', uncompleted_late]) non_zero = (num_completed > 0) or (num_uncompleted > 0) or ( completed_late > 0) or (uncompleted_late > 0) if non_zero: pie = PieChart(SimpleDataSource(pie_data), options={ 'title': request.GET['pie_category'] + " On-Time Completion Rate", 'width': 1050 }).as_html() else: pie = "No completed tasks to display for the " + request.GET[ 'pie_category'].lower() + " category." return pie
def chart_archive(request, chartfrom, year, month, day=0): """Funtion""" inyear = int(year) inmonth = int(month) inday = int(day) if inmonth > 0 and inmonth <= 12: now = timezone.now() if inday == 0: startdate = now.replace(year=inyear, month=inmonth, day=1, hour=0, minute=0, second=0, microsecond=0) enddate = startdate.replace(month=inmonth + 1) else: enddate = now.replace(year=inyear, month=inmonth, day=inday, hour=0, minute=0, second=0, microsecond=0) - timezone.timedelta(hours=9) startdate = enddate - timezone.timedelta(days=7) enddate = enddate - timezone.timedelta(microseconds=1) issues = Issue.objects.exclude(email__iexact='').filter( datetime__range=(startdate, enddate)).order_by('count', 'goodcount') data_list = [['media', '좋아요', '나빠요']] for issue in issues: giza = Giza.objects.filter(email__iexact=issue.email) if giza: found = False for item in data_list: if giza[0].belongto == item[0]: item[1] += issue.goodcount item[2] += issue.count found = True break if not found: data_list.append( [giza[0].belongto, issue.goodcount, issue.count]) found = False data = sorted(data_list, key=get_key_2, reverse=True)[0:settings.RANKING_LIST_LIMIT + 1] data_source = SimpleDataSource(data=data) chart_all_bad = ColumnChart(data_source) data = sorted(data_list, key=get_key_1, reverse=True)[0:settings.RANKING_LIST_LIMIT + 1] data_source = SimpleDataSource(data=data) chart_all_good = ColumnChart(data_source) data = sorted(data_list, key=get_key_1, reverse=True) data_source = SimpleDataSource(data=data) chart_good = PieChart(data_source) data = sorted(data_list, key=get_key_2, reverse=True) data_copy = [x[:] for x in data] for l in data_copy: del l[1] data_source = SimpleDataSource(data=data_copy) chart_bad = PieChart(data_source) trend_data = [[ 'date', data_copy[1][0], data_copy[2][0], data_copy[3][0], data_copy[4][0], data_copy[5][0] ]] trend_start = startdate for i in range(7): trend_end = trend_start + timezone.timedelta(1) trend_issues = issues.filter(datetime__range=(trend_start, trend_end)).order_by( 'count', 'goodcount') if i == 0: trend_data.append([trend_end.date(), 0, 0, 0, 0, 0]) else: trend_data.append([ trend_end.date(), trend_data[i][1], trend_data[i][2], trend_data[i][3], trend_data[i][4], trend_data[i][5] ]) for trend_issue in trend_issues: giza = Giza.objects.filter(email__iexact=trend_issue.email) if giza: for j in range(5): if giza[0].belongto == trend_data[0][j + 1]: trend_data[i + 1][j + 1] += trend_issue.count trend_start = trend_end data_source = SimpleDataSource(data=trend_data) chart_trend = LineChart(data_source) if inday == 0: msg = u'%s년 %s월 언론사 데이터입니다.' % (year, month) elif chartfrom == 'live': msg = u'실시간 업데이트되는 일주일간의 언론사 데이터입니다.' else: formatted_start = formats.date_format( startdate + timezone.timedelta(hours=9), "Y-m-d") formatted_end = formats.date_format( enddate + timezone.timedelta(hours=9), "Y-m-d") msg = u'%s ~ %s 사이의 언론사 데이터입니다.' % (formatted_start, formatted_end) return render( request, "issue/chart.html", { 'chart_all_bad': chart_all_bad, 'chart_all_good': chart_all_good, 'chart_good': chart_good, 'chart_bad': chart_bad, 'chart_trend': chart_trend, 'chartfrom': chartfrom, 'msg': msg, }) else: return HttpResponse(u"기간 설정 오류")