def pygal_chart(chart_type, data, chartname, file_name): ''' Funtion builds charts using pygal (pygal.org) python charting library and saves them in .svg and .png format Chart types supported: bar_basic, bar_horizontal, bar_stacked, line_basic, line_horizontal, line_stacked, pie_basic, pie_donut, pie_halfpie, scatter - see http://pygal.org/en/stable/documentation/types/index.html ''' # Define chart type and set some custom styles if chart_type == 'bar_basic': chart = pygal.Bar() chart = pygal.Bar(print_values=True, style=DefaultStyle( value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', ))) elif chart_type == 'bar_horizontal': chart = pygal.HorizontalBar() chart = pygal.Bar(print_values=True, style=DefaultStyle( value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', ))) elif chart_type == 'bar_stacked': chart = pygal.StackedBar() chart = pygal.Bar(print_values=True, style=DefaultStyle( value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', ))) elif chart_type == 'line_basic': chart = pygal.Line(print_values=True) elif chart_type == 'line_horizontal': chart = pygal.HorizontalLine(print_values=True) elif chart_type == 'line_stacked': chart = pygal.StackedLine(fill=True) elif chart_type == 'pie_basic': chart = pygal.Pie() elif chart_type == 'pie_donut': chart = pygal.Pie(inner_radius=.4) elif chart_type == 'pie_halfpie': chart = pygal.Pie(half_pie=True) elif chart_type == 'scatter': chart = pygal.XY(stroke=False) # Add data chart.title = chartname for ds in data: for key, value in ds.items(): chart.add(key, value) # Render chart chart.render_to_file(file_name + '.svg') chart.render_to_png(file_name + '.png') return True
def __init__(self, **kwargs): self.data = {} self.chart = pygal.Radar(**kwargs) self.chart.style = DefaultStyle(tooltip_font_size=14) self.chart.legend_at_bottom = True self.chart.legend_at_bottom_columns = 3
def expense_plot(): today = datetime.date.today() start = today - datetime.timedelta(days=30) expenses = Expense.objects.filter(Q(date__gte=start) & Q(date__lte=today)) if expenses.count() == 0: return None mapping = {} for expense in expenses: mapping[expense.category] = mapping.setdefault(expense.category, 0) + expense.amount total = 0 for key in mapping.keys(): total += mapping[key] chart = pygal.Pie(print_values=True, style=DefaultStyle(value_font_size=30, value_colors=('white', ))) chart.title = 'Expenses breakdown over the last 30 days' for key in mapping.keys(): chart.add(expense_choices[key], mapping[key]) return chart
def main(quarter, year, code): bu = "https://www.ics.uci.edu/~rang1/{}{}/{}.txt" bu2 = "https://www.ics.uci.edu/~abakis/{}{}/{}.txt" try: with urllib.request.urlopen(bu.format(quarter, year, code)) as inf: src = inf.read().decode('utf-8') with urllib.request.urlopen(bu2.format(quarter, year, code.lstrip('0'))) as inf: description = inf.read().decode('utf-8').replace( "There was no waitlist for this course.", "") # temp patch except: description = 'We do not have data on this section! Maybe because this section was added in late or got canceled or doesn\'t exist!' chart = pygal.Line(no_data_text='Course Not Found', style=DefaultStyle(no_data_font_size=40)) chart.add('line', []) src = chart.render_data_uri() client_agent = request.user_agent if client_agent.browser.strip() == 'msie' or 'Edge' in client_agent.string: return '<p>{}</p><img id="cheerio" src={} />'.format(description, src) # NEW else: return '<p>{}</p><embed id="cheerio" type="image/svg+xml" src= {} />'.format( description, src) # NEW
def get_graph(self): data = self.get_data() if data: max_value = max([value[1] for value in data if value[1] is not None]) else: max_value = 0.5 my_style = DefaultStyle() my_style.font_family = 'googlefont:Roboto' my_style.foreground = 'black' my_style.foreground_strong = 'white' my_style.title_font_size = 18 my_style.background = "#4285f4" if max_value <= 1 and max_value >= 0.5: my_range = (0, 1) else: my_range = (0, max_value * 2) graph = pygal.DateTimeLine( x_value_formatter=lambda dt: dt.strftime('%d.%m.%Y, %H:%M:%S'), range=my_range, title="{} \n From {} to {}".format(self.field_name, self.start, self.end), style = my_style, show_legend = False, interpolate = 'cubic', dots_size=2 ) graph.add(self.field, data) return graph.render_django_response()
def plot_ar_by_customer(): chart = pygal.Pie(print_values=True, style=DefaultStyle(value_font_size=30, value_colors=('white', ))) chart.title = 'A/R By Customer' for cus in Customer.objects.filter(account__balance__gt=0): chart.add(str(cus), cus.total_accounts_receivable) return chart.render(is_unicode=True)
def single_item_composition_plot(item): stock = WareHouseItem.objects.filter(item=item) chart = pygal.Pie(print_values=True, style=DefaultStyle(value_font_size=30, value_colors=('white', ))) chart.title = 'Warehouse composition' for i in stock: chart.add(str(i.warehouse), i.quantity) return chart
def composition_plot(): stock = InventoryItem.objects.filter(type=0) chart = pygal.Pie(print_values=True, style=DefaultStyle(value_font_size=30, value_colors=('white', ))) chart.title = 'Inventory Composition' for i in stock: chart.add(i.name, i.quantity) return chart
def spent_time_by_day_of_the_week(request, member_id=None, week_of_year=None, board_id=None): user_boards = get_user_boards(request.user) if member_id is None: if user_is_member(request.user): member = request.user.member else: member = Member.objects.filter(boards__in=user_boards)[0] else: member = Member.objects.filter(boards__in=user_boards).distinct().get( id=member_id) if week_of_year is None: now = timezone.now() today = now.date() week_of_year_ = get_iso_week_of_year(today) week_of_year = "{0}W{1}".format(today.year, week_of_year_) y, w = week_of_year.split("W") week = Week(int(y), int(w)) start_of_week = week.monday() end_of_week = week.sunday() chart_title = u"{0}'s spent time in week {1} ({2} - {3})".format( member.external_username, week_of_year, start_of_week.strftime("%Y-%m-%d"), end_of_week.strftime("%Y-%m-%d")) board = None if board_id: board = user_boards.get(id=board_id) chart_title += u" for board {0}".format(board.name) spent_time_chart = pygal.HorizontalBar(title=chart_title, legend_at_bottom=True, print_values=True, print_zeroes=False, human_readable=True) try: day = start_of_week while day <= end_of_week: member_spent_time = member.get_spent_time(day, board) spent_time_chart.add(u"{0}".format(day.strftime("%A")), member_spent_time) day += datetime.timedelta(days=1) except AssertionError: spent_time_chart.no_data_text = u"No developers for this board.\nCheck members' attributes." spent_time_chart.style = DefaultStyle(no_data_font_size=20) return spent_time_chart.render_django_response() return spent_time_chart.render_django_response()
def plot_type_treemap_interactive(type_df, fp="type_treemap_pygal.pdf"): # type treemap style = DefaultStyle( legend_font_size=12, tooltip_font_size=12, ) treemap = pygal.Treemap(style=style, margin=0) treemap.title = "Event Type" for idx, row in type_df.iterrows(): treemap.add(row.name, [row["pct"]]) treemap.render_to_file(fp, print_values=False)
def reason_type_chart_pygal(chart_data): pie_chart = pygal.Pie(truncate_legend=-1, human_readable=True) pie_chart.title = 'Reason Type' for data in chart_data: pie_chart.add(data[0], data[1]) pie_chart.render() pie_chart.render_to_file('reason_type_pie.svg') pie_chart.print_values = True pie_chart.style = DefaultStyle(value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', ) * 15) pie_chart.render_to_png('%sreason_type_pie.png' % PIC_DIR) pie_chart.render_to_file('%sreason_type_pie.svg' % PIC_DIR)
def graph2(): with open(filename1, 'rb') as temp_file: times = pickle.load(temp_file) with open(filename2, 'rb') as temp_file: readings = pickle.load(temp_file) my_style = DefaultStyle( background='transparent', font_family='sans-serif', title_font_size=20, label_font_size=14, value_font_size=14, value_label_font_size=14, major_label_font_size=14, tooltip_font_size=16, colors=['#00A5DD'], ) graph = pygal.Line(style=my_style, print_values=True, show_y_guides=False, show_legend=False, stroke_style={'width': 3}) graph.title = 'SMRH - Consumo Total de Água' graph.x_title = 'Horário Registrado' graph.y_title = 'Consumo Total em Litros' graph.dots_size = 4 graph.tooltip_border_radius = 10 graph.width = 1100 first_reading = readings[0] if (len(readings) > 9): times = times[-10:] readings = readings[-10:] for x in range(10): atual = readings[x] readings[x] = atual - first_reading else: for x in range(len(readings)): atual = readings[x] readings[x] = atual - first_reading # Show last 10 readings/times graph.x_labels = times graph.add('Consumo', readings) graph_data = graph.render_data_uri() return render_template('2graph.html', graph_data=graph_data)
def generate(self, user_data): chart_data = self.get_data(user_data) self.chart = pygal.Pie(print_values=True, style=DefaultStyle( legend_font_family='googlefont:Raleway', value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', 'white', 'white', 'white', 'white', 'white', 'white'))) for key, value in chart_data.items(): #self.chart.add(key, value) self.chart.add(key, value, formatter=lambda x: '%s' % x) return self.chart.render(is_unicode=True)
def plot_expense_breakdown(work_order): chart = pygal.Pie(print_values=True, style=DefaultStyle( value_font_size=30, value_colors=('white', ) ) ) chart.title = 'Work Order Expenses Breakdown' for exp in work_order.expenses: chart.add(exp.expense.category_string, exp.expense.amount) total_wages = sum([log.total_cost for log in work_order.time_logs]) chart.add('Wages', total_wages) for con in work_order.consumables_used: chart.add(con.consumable.name, con.line_value) return chart.render(is_unicode=True)
def graphe3(self): pk_formulaire = self.kwargs.get('formulaire_pk') formulaire = Formulaire.objects.get(pk=pk_formulaire) user = User.objects.get(pk=self.kwargs['user_pk']) categorie = formulaire.categories.all() tab = [] tab2 = [] for categ in categorie: for question in formulaire.questions.all(): valeurs = ChoiceUtilisateur.objects.filter( reference_user=user.pk, reference_choice__in=Choice.objects.filter( categorie=categ, question=question ) ).aggregate(Sum('valeur_entier')) tab.append(valeurs['valeur_entier__sum']) tab2.append(sum(tab)) del tab[:] valeurs = [tab2[0], tab2[1], tab2[2], tab2[3], tab2[4]] chart = pygal.Bar( print_values=True, style=DefaultStyle( value_font_family='googlefont:Raleway', value_font_size=16, labels_colors=('black'), labels_font_size=16, ), print_labels=False, print_values_position='top', show_legend=False, pretty_print=True, print_zeroes=False, margin=0, x_labels=[ 'Psychologique', 'Normalisante', 'Magique', 'Rationnelle', 'Systémique' ], ) colors = ('#5EB6DD', '#AEEE00', '#046380', '#C72B10', '#05966D') serie = [] for value, color in zip(valeurs, colors): serie.append({'value': value, 'color': color}) chart.add('', serie) return HttpResponse(chart.render())
def plot_sales_by_customer(start, end): invs = Invoice.objects.filter( Q(date__gte=start) & Q(date__lte=end) & Q(draft=False) & Q(status__in=['paid', 'paid-partially', 'invoice'])) sbc = {} for i in invs: sbc.setdefault(str(i.customer), 0) sbc[str(i.customer)] += i.subtotal chart = pygal.Pie(print_values=True, style=DefaultStyle(value_font_size=30, value_colors=('white', ))) chart.title = 'Sales By Customer' for key in sbc.keys(): chart.add(key, sbc[key]) return chart.render(is_unicode=True)
def employee_roles_chart(): # take all 5 role categories and count the number of employees with each role # plot that count in a pie chart roles = {'Payroll Officers': models.PayrollOfficer, 'Bookkeepers':Bookkeeper, 'Service People':ServicePerson, 'Sales Representatives':SalesRepresentative, 'Inventory Controllers':InventoryController} chart = pygal.Pie(print_values=True, style=DefaultStyle( value_font_size=30, value_colors=('white', ) ) ) for role in roles.keys(): chart.add(role, roles[role].objects.all().count()) return chart
def plot_ar_by_aging(): chart = pygal.Pie(print_values=True, style=DefaultStyle(value_font_size=30, value_colors=('white', ))) chart.title = 'A/R By Aging' invs = Invoice.objects.filter(status__in=['invoice', 'paid-partially']) chart.add( "Current", sum([i.total for i in filter(lambda x: x.overdue_days == 0, invs)])) chart.add( '0-7 Days', sum([ i.total for i in filter( lambda x: x.overdue_days > 0 and x.overdue_days < 7, invs) ])) chart.add( '8-14 Days', sum([ i.total for i in filter( lambda x: x.overdue_days > 6 and x.overdue_days < 15, invs) ])) chart.add( '15-30 Days', sum([ i.total for i in filter( lambda x: x.overdue_days > 14 and x.overdue_days < 31, invs) ])) chart.add( '31-60 Days', sum([ i.total for i in filter( lambda x: x.overdue_days > 30 and x.overdue_days < 61, invs) ])) chart.add( '61+ Days', sum([i.total for i in filter(lambda x: x.overdue_days > 60, invs)])) return chart.render(is_unicode=True)
def plot_sales_by_products_and_services(start, end): lines = InvoiceLine.objects.filter( Q(invoice__date__gte=start) & Q(invoice__date__lte=end) & Q(invoice__draft=False) & Q(expense__isnull=True) & Q(invoice__status__in=['paid', 'paid-partially', 'invoice'])) sbps = {} for l in lines: sbps.setdefault(l.name, 0) sbps[l.name] += l.subtotal chart = pygal.Pie(print_values=True, style=DefaultStyle(value_font_size=30, value_colors=('white', ))) chart.title = 'Sales By Products and Services' ordered = sorted([(key, sbps[key]) for key in sbps.keys()], key=lambda x: x[1], reverse=True) for item in ordered[:10]: chart.add(item[0], item[1]) return chart.render(is_unicode=True)
class Chart(object): Y_AXIS_MULTIPLIER = 1.33 # The default style settings for a bart chart or histogram BAR_CONFIG = Config() BAR_CONFIG.legend_box_size = 15 BAR_CONFIG.width = 1000 BAR_CONFIG.legend_at_bottom = True BAR_CONFIG.truncate_legend = -1 BAR_CONFIG.max_scale = 7 BAR_CONFIG.print_values = True BAR_CONFIG.print_values_position = 'top' BAR_CONFIG.style = DefaultStyle(background='#fff', title_font_size=20) # Shared init stuff among all chart types def __init__(self, title): self.chart.title = title self.chart.range = (0, self.max_y_axis) # Output a chart to png def render_png(self, chart_name): self.chart.render_to_png('app/static/charts/{}.png'.format(chart_name))
import pygal from pygal.style import DefaultStyle chart = pygal.Line(no_data_text='No result found', style=DefaultStyle(no_data_font_size=40)) chart.add('line', []) print(chart.render(is_unicode=True))
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from collections import defaultdict from collections import OrderedDict from pygal.style import DefaultStyle from datetime import datetime from datetime import timedelta import pygal import json import sys yellow_style = DefaultStyle() yellow_style.background = '#EBB82B' def load_data(filename): with open(filename, 'r') as f: data = json.load(f) return data def count_words(data): word_db = defaultdict(int) user_db = defaultdict(int) comments = 0 for stage in data.values(): for comment in stage['comments']:
import pygal from pygal.style import DefaultStyle chart = pygal.Bar(print_values=True, style=DefaultStyle( value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white',))) chart.add('line', [0, 12, 31, 8, -28, 0]) print(chart.render(is_unicode=True))
def HFA_home_wins(filename): if filename == 'mls.csv': league_name = 'MLS' season_label = '2000-2016' save_f = 'mls_home_wins.svg' elif filename == 'england.csv': league_name = 'English Premier League' elif filename == 'spain.csv': league_name = 'La Liga' elif filename == 'italy.csv': league_name = 'Serie A' elif filename == 'france.csv': league_name = 'Ligue 1' elif filename == 'germany.csv': league_name = 'Bundesliga' # Import data with open(filename) as f: data = csv.reader(f) header_row = next(data) # Establish game result variables as zero total_hw, total_draws, total_aw = 0, 0, 0 for row in data: # Remove mls post shoutout era results if filename == 'mls.csv': if int(row[1]) < 2000: continue # Remove lower english divisions # Remove era prior to PL formation if filename == 'england.csv': if row[7] != '1': continue if int(row[1]) < 1992: continue # Count the number of home wins, draws, away wins # Also count per team if row[5] > row[6]: total_hw += 1 elif row[5] == row[6]: total_draws += 1 else: total_aw += 1 # HOW OFTEN DO TEAMS WIN HOME VS AWAY?? # Confirm have proper number of games # Plot MLS home wins, draws, and away wins wins = pygal.Bar(print_values=True, style=DefaultStyle(value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', 'white', 'white'))) wins.title = league_name + ' Total Home Wins, Draws, and Away Wins (in %) for Seasons ' + season_label wins.add('Home Wins', total_hw) wins.add('Draws', total_draws) wins.add('Away Wins', total_aw) wins.render_in_file(save_f)
def HFA_home_win_perc(filename): if filename == 'mls.csv': league_name = 'MLS' season_label = '2000-2016' save_f = 'mls_home_win_perc.svg' elif filename == 'england.csv': league_name = 'English Premier League' elif filename == 'spain.csv': league_name = 'La Liga' elif filename == 'italy.csv': league_name = 'Serie A' elif filename == 'france.csv': league_name = 'Ligue 1' elif filename == 'germany.csv': league_name = 'Bundesliga' # Import data with open(filename) as f: data = csv.reader(f) header_row = next(data) # Establish game result and number of games variables as zero total_hw, total_draws, total_aw, total_games = 0, 0, 0, 0 for row in data: # Remove post shoutout era results if filename == 'mls.csv': if int(row[1]) < 2000: continue # Remove lower english divisions # Remove era prior to PL formation if filename == 'england.csv': if row[7] != '1': continue if int(row[1]) < 1992: continue # Count games per season total_games += 1 # Count the number of home wins, draws, away wins # Also count per team if row[5] > row[6]: total_hw += 1 elif row[5] == row[6]: total_draws += 1 else: total_aw += 1 # Plot home win %, draw %, and away win % assert total_hw + total_draws + total_aw == total_games # Calculate percentages hw_perc = round((total_hw / total_games * 100), 2) draw_perc = round((total_draws / total_games * 100), 2) aw_perc = round((total_aw / total_games * 100), 2) #Plot wins = pygal.Bar(print_values=True, style=DefaultStyle(value_font_family='googlefont:Raleway', value_font_size=30, value_colors=('white', 'white', 'white'))) wins.title = league_name + ' Results (in %) for Seasons ' + season_label wins.add('Home Win %', hw_perc) wins.add('Draw %', draw_perc) wins.add('Away Win %', aw_perc) wins.render_to_file(save_f)
def stats(): a_chart = pygal.Bar(print_values=True, style=DefaultStyle(value_font_family='helvetica', value_font_size=30)) a_chart.title = "Recipes By Continent" a_chart.add("Europe", mongo.db.recipes.find({ "continent_name": "Europe" }).count()) a_chart.add( "North America", mongo.db.recipes.find({ "continent_name": "North America" }).count()) a_chart.add( "South America", mongo.db.recipes.find({ "continent_name": "South America" }).count()) a_chart.add("Asia", mongo.db.recipes.find({ "continent_name": "Asia" }).count()) a_chart.add("Africa", mongo.db.recipes.find({ "continent_name": "Africa" }).count()) a_chart.add("Australia", mongo.db.recipes.find({ "continent_name": "Australia" }).count()) chart1 = a_chart.render_data_uri() b_chart = pygal.HorizontalBar(print_values=True, style=DefaultStyle( value_font_family='helvetica', value_font_size=30)) b_chart.title = "Recipes By Food Type" b_chart.add("Beef", mongo.db.recipes.find({"food_type": "Beef"}).count()) b_chart.add("Chicken", mongo.db.recipes.find({ "food_type": "Chicken" }).count()) b_chart.add("Fish", mongo.db.recipes.find({"food_type": "Fish"}).count()) b_chart.add("Lamb", mongo.db.recipes.find({"food_type": "Lamb"}).count()) b_chart.add("Pork", mongo.db.recipes.find({"food_type": "Pork"}).count()) b_chart.add("Vegan", mongo.db.recipes.find({"food_type": "Vegan"}).count()) b_chart.add("Vegetarian", mongo.db.recipes.find({ "food_type": "Vegetarian" }).count()) chart2 = b_chart.render_data_uri() c_chart = pygal.Bar(print_values=True, style=DefaultStyle(value_font_family='helvetica', value_font_size=30)) c_chart.title = "Allergens in recipes" c_chart.add("Lactose", mongo.db.recipes.find({ 'allergy_name': 'Lactose' }).count()) c_chart.add("Peanuts", mongo.db.recipes.find({ 'allergy_name': 'Peanuts' }).count()) c_chart.add("Gluten", mongo.db.recipes.find({ 'allergy_name': 'Gluten' }).count()) c_chart.add( "Sesame Seeds", mongo.db.recipes.find({ 'allergy_name': 'Sesame Seeds' }).count()) c_chart.add("Seafood", mongo.db.recipes.find({ 'allergy_name': 'Seafood' }).count()) c_chart.add("Beans", mongo.db.recipes.find({ 'allergy_name': 'Beans' }).count()) chart3 = c_chart.render_data_uri() return render_template('stats.html', chart1=chart1, chart2=chart2, chart3=chart3)
{{ id }}.axis.y text { } {{ id }}#tooltip text { } {{ id }}.dot { } {{ id }}.color-0 { } {{ id }} text { } """ default_config.css.append('inline:' + custom_css) default_style = DefaultStyle() default_style.label_font_size = 7 default_style.plot_background = '#F9F9F9' default_style.background = '#F9F9F9' default_style.legend_font_size = 7 default_config.style = default_style def get_rect_attributes(rect): attrib_dict = {s.attrib['class']: s.text for s in rect.itersiblings()} prevrect = rect.getprevious() if prevrect.attrib['class'] == 'label': attrib_dict['label'] = prevrect.text return attrib_dict
def general_campana(self): estadisticas = self._calcular_estadisticas(self.campana, self.fecha_desde, self.fecha_hasta) if estadisticas: logger.info( _("Generando grafico calificaciones de campana por cliente ")) reporte_campana_dir = os.path.join(settings.MEDIA_ROOT, "reporte_campana") try: os.stat(reporte_campana_dir) except IOError: os.mkdir(reporte_campana_dir) # Barra: Cantidad de calificacion de cliente barra_campana_calificacion = pygal.Bar( # @UndefinedVariable show_legend=False, style=LightGreenStyle) barra_campana_calificacion.title = _( 'Calificaciones de Clientes Contactados ') barra_campana_calificacion.x_labels = \ estadisticas['calificaciones_nombre'] barra_campana_calificacion.add('cantidad', estadisticas['calificaciones_cantidad']) barra_campana_calificacion.render_to_png( os.path.join( reporte_campana_dir, "barra_campana_calificacion_{}.png".format(self.campana.id))) barra_campana_calificacion = adicionar_render_unicode( barra_campana_calificacion) # Barra: Total de llamados no atendidos en cada intento por campana. barra_campana_no_atendido = pygal.Bar( # @UndefinedVariable show_legend=False, style=DefaultStyle(colors=('#b93229', ))) barra_campana_no_atendido.title = _( 'Cantidad de llamadas no atendidos ') barra_campana_no_atendido.x_labels = \ estadisticas['resultado_nombre'] barra_campana_no_atendido.add('cantidad', estadisticas['resultado_cantidad']) barra_campana_no_atendido.render_to_png( os.path.join( reporte_campana_dir, "barra_campana_no_atendido_{}.png".format(self.campana.id))) barra_campana_no_atendido = adicionar_render_unicode( barra_campana_no_atendido) # Barra: Detalles de llamadas por evento de llamada. barra_campana_llamadas = pygal.Bar(show_legend=False) barra_campana_llamadas.title = _('Detalles de llamadas ') barra_campana_llamadas.x_labels = \ estadisticas['cantidad_llamadas'][0] barra_campana_llamadas.add( 'cantidad', self._crear_serie_con_color(self.campana, estadisticas['cantidad_llamadas'])) barra_campana_llamadas = adicionar_render_unicode( barra_campana_llamadas) return { 'estadisticas': estadisticas, 'barra_campana_calificacion': barra_campana_calificacion, 'dict_campana_counter': list( zip(estadisticas['calificaciones_nombre'], estadisticas['calificaciones_cantidad'])), 'total_asignados': estadisticas['total_asignados'], 'agentes_venta': estadisticas['agentes_venta'], 'total_calificados': estadisticas['total_calificados'], 'total_ventas': estadisticas['total_ventas'], 'barra_campana_no_atendido': barra_campana_no_atendido, 'dict_no_atendido_counter': list( zip(estadisticas['resultado_nombre'], estadisticas['resultado_cantidad'])), 'total_no_atendidos': estadisticas['total_no_atendidos'], 'calificaciones': estadisticas['calificaciones'], 'barra_campana_llamadas': barra_campana_llamadas, 'dict_llamadas_counter': list( zip(estadisticas['cantidad_llamadas'][0], estadisticas['cantidad_llamadas'][1])), }
def graphe1(self): pk_formulaire = self.kwargs.get('formulaire_pk') formulaire = Formulaire.objects.get(pk=pk_formulaire) user = User.objects.get(pk=self.kwargs['user_pk']) categorie = formulaire.categories.all() tab2 = [] for categ in categorie: tab = [] for question in formulaire.questions.all(): valeurs = ChoiceUtilisateur.objects.filter( reference_user=user.pk, reference_choice__in=Choice.objects.filter( categorie=categ, question=question ) ).aggregate(Sum('valeur_entier')) tab.append(valeurs['valeur_entier__sum']) tab2.append(sum(tab)) val = [tab2[0], tab2[1], tab2[3], tab2[2]] style = DefaultStyle(colors=( '#AEEE00', '#046380', '#C72B10', '#05966D', '#000000', '#000000', )) axis_max = formulaire.nb_points * formulaire.questions.count() chart = pygal.XY( width=400, height=400, print_labels=True, print_values=False, print_values_position='bottom', xrange=(-1 * axis_max, axis_max), range=(-1 * axis_max, axis_max), fill=True, show_dots=False, inner_radius=20, show_x_labels=False, show_y_labels=False, show_legend=False, style=style, margin=0, ) chart.add( 'Analytique', [ (0, 0), (0, -val[0]), {'value': (-val[0], -val[0]), 'label': str(val[0])}, (-val[0], 0), (0, 0), ], dots_size=1 ) chart.add( 'Relationnel individuel', [ (0, 0), (0, -val[1]), {'value': (val[1], -val[1]), 'label': str(val[1])}, (val[1], 0), (0, 0), ], dots_size=1 ) chart.add( 'Centré resultat', [ (0, 0), (0, val[2]), {'value': (-val[2], val[2]), 'label': str(val[2])}, (-val[2], 0), (0, 0), ], dots_size=1 ) chart.add( 'entraineur de groupe', [ (0, 0), (0, val[3]), {'value': (val[3], val[3]), 'label': str(val[3])}, (val[3], 0), (0, 0), ], dots_size=1 ) chart.add('', [(-1 * axis_max, 0), (axis_max, 0)], dots_size=0) chart.add('', [(0, -1 * axis_max), (0, axis_max)], dots_size=0) return HttpResponse(chart.render())
def graphe2(self): pk_formulaire = self.kwargs.get('formulaire_pk') formulaire = Formulaire.objects.get(pk=pk_formulaire) user = User.objects.get(pk=self.kwargs['user_pk']) categorie = formulaire.categories.all() tab2 = [] for categ in categorie: tab = [] for question in formulaire.questions.all(): valeurs = ChoiceUtilisateur.objects.filter( reference_user=user.pk, reference_choice__in=Choice.objects.filter( categorie=categ, question=question ) ).aggregate(Sum('valeur_entier')) tab.append(valeurs['valeur_entier__sum']) tab2.append(sum(tab)) val = [tab2[2], tab2[3], tab2[0], tab2[1]] style = DefaultStyle( colors=('#F44336', '#3F51B5', '#3F51B5', '#009688', '#009688') ) axis_max = formulaire.nb_points * formulaire.questions.count() chart = pygal.XY( width=400, height=400, print_labels=True, print_values=False, xrange=(-1 * axis_max, axis_max), range=(-1 * axis_max, axis_max), fill=False, show_dots=True, inner_radius=20, show_x_labels=False, show_y_labels=False, show_legend=False, style=style, margin=0, ) chart.add( '', [ {'value': (-val[0], -val[0]), 'label': str(val[0])}, {'value': (-val[1], val[1]), 'label': str(val[1])}, {'value': (val[2], val[2]), 'label': str(val[2])}, {'value': (val[3], -val[3]), 'label': str(val[3])}, {'value': (-val[0], -val[0])}, ], stroke_style={'width': 4}, dots_size=2, ) chart.add( '', [(-1 * axis_max, 0), (axis_max, 0)], show_dots=False, stroke_style={'width': 2} ) chart.add( '', [(0, -1 * axis_max), (0, axis_max)], show_dots=False, stroke_style={'width': 2} ) chart.add( '', [(i, i) for i in range(-1 * axis_max, 1 * axis_max, 10)], stroke_style={'width': 1}, dots_size=1, ) chart.add( '', [(-1 * i, i) for i in range(-1 * axis_max, 1 * axis_max, 10)], stroke_style={'width': 1}, dots_size=1, ) return HttpResponse(chart.render())
{{ id }}.axis.y text { } {{ id }}#tooltip text { } {{ id }}.dot { } {{ id }}.color-0 { } {{ id }} text { } """ default_config.css.append('inline:' + custom_css) default_style = DefaultStyle() default_style.label_font_size = 7 default_style.plot_background='#F9F9F9' default_style.background='#F9F9F9' default_style.legend_font_size = 7 default_config.style = default_style def get_rect_attributes(rect): attrib_dict = {s.attrib['class']: s.text for s in rect.itersiblings()} prevrect = rect.getprevious() if prevrect.attrib['class'] == 'label': attrib_dict['label'] = prevrect.text return attrib_dict def get_tooltip_label(attrib_dict):
def dashboard(): """ Generates dashboard for week selected """ graphStyle = DefaultStyle(label_font_family='googlefont:Roboto Condensed', label_font_size=20, label_colors=('black'), value_font_family='googlefont:Roboto Condensed', value_font_size=15, value_colors=('black')) weeks = dashboard_df['week'].tolist() weeks = list(set(weeks)) search_term = request.args.get("week") print(search_term) print(type(search_term)) if search_term is None: search_term = weeks[-1] results = dashboard_df[dashboard_df['week'] == search_term] else: search_term = int(search_term) print(search_term) print(type(search_term)) results = dashboard_df[dashboard_df['week'] == int(search_term)] print(results) total_points = results['total_points'].sum() total_sleep = results['sleep'].sum() total_drive = results['driving'].sum() results['timestamp'] = pd.to_datetime(results['date'], dayfirst=True) week_days = results['week_day'].unique() #build sleep chart sleep_line = pygal.Bar(print_labels=True, print_values=True, show_legend=False, style=graphStyle) sleep_line.title = "Sleep Chart" sleep_line.x_title = 'Days' sleep_line.y_title = 'Hours of Sleep' sleep_values = list(zip(week_days, results['sleep'].tolist())) for item in sleep_values: sleep_line.add(item[0].upper(), [{ 'value': item[1], 'label': item[0].upper() }]) sleep_chart = sleep_line.render_data_uri() #build drive chart drive_bar = pygal.Bar(show_legend=False, print_labels=True, print_values=True) drive_bar.title = 'Driving hours logged' drive_bar.x_title = 'Days' drive_bar.y_title = 'Hours' drive_values = results['driving'].tolist() values = list(zip(week_days, drive_values)) for item in values: drive_bar.add(item[0].upper(), [{ 'value': item[1], 'label': item[0].upper() }]) drive_chart = drive_bar.render_data_uri() #build points chart points_pie = pygal.StackedLine(fill=True, legend_at_bottom=True) points_pie.title = 'Points Distribution' points_pie.x_labels = week_days points_pie.add('Driving Points', results['driving_points'].tolist()) points_pie.add('Sleeping Points', results['sleep_points'].tolist()) chart = points_pie.render_data_uri() return render_template('dashboard.html', weeks=weeks, selected_week=search_term, chart=chart, sleep_chart=sleep_chart, drive_chart=drive_chart, total_drive=total_drive, total_points=total_points, total_sleep=total_sleep)