Exemple #1
0
    def plot_pop(self):
        pop_size, rdm_individuals, populations = self.get_population_data()

        #CHART 1
        x = range(len(pop_size))
        chart1 = pygal.XY(style=DarkStyle,
                          legend_at_bottom=True,
                          show_dots=False,
                          fill=True,
                          include_x_axis=True)
        chart1.title = str('Population size over  ' + str(len(pop_size)) +
                           ' generations.')
        chart1.add('Population size', list(zip(x, pop_size)))
        chart1.render_to_file('charts/Sexual_reproduction_1.svg')

        #CHART 2
        genes = sorted(self.get_genes_data(rdm_individuals))

        x2 = map(str, range(len(genes)))
        chart2 = pygal.StackedBar(style=DarkStyle,
                                  legend_at_bottom=True,
                                  truncate_label=-1)
        chart2.title = (
            'Genome of a random individual from the population over \n ' +
            str(len(pop_size)) + ' generations. \n Monogamy: ' +
            str(self.population.monogamy) + ',    Long term: ' +
            str(self.population.long_term))
        chart2.x_labels = self.get_x_lables(pop_size)

        for x2_, genes_ in genes:
            chart2.add(x2_, genes_)
        chart2.render_to_file('charts/Sexual_reproduction_2.svg')

        #CHART 3

        for population in populations:
            if populations.index(population) % 50 == 0:
                genes = sorted(self.get_genes_data(population))

                x2 = map(str, range(len(genes)))
                chart2 = pygal.StackedBar(style=DarkStyle,
                                          legend_at_bottom=True,
                                          truncate_label=-1)
                chart2.title = ('Gentoype of each individual of generation #' +
                                str(populations.index(population)) +
                                '. \n Monogamy: ' +
                                str(self.population.monogamy) +
                                ',    Long term: ' +
                                str(self.population.long_term))

                for x2_, genes_ in genes:
                    chart2.add(x2_, genes_)
                chart2.render_to_file('charts/Genes_' +
                                      str(populations.index(population)) +
                                      '.svg')
Exemple #2
0
def pygal_bar_stacked(data, chartname, file_name):
    bar_chart = pygal.StackedBar()
    bar_chart = pygal.StackedBar(print_values=True,
                                 style=DefaultStyle(
                                     value_font_family='googlefont:Raleway',
                                     value_font_size=30,
                                     value_colors=('white', )))
    bar_chart.title = chartname
    for ds in data:
        for key, value in ds.items():
            bar_chart.add(key, value)
    bar_chart.render_to_file(file_name + '.svg')
    bar_chart.render_to_png(file_name + '.png')
    return True
Exemple #3
0
def prepare_bar_plot():
    result, years, no_of_projects = languageStatistic()

    my_style = define_style()

    my_config = pygal.Config()
    my_config.x_label_rotation = 45
    my_config.title_font_size = 30
    my_config.label_font_size = 25
    my_config.major_label_font_size = 20
    my_config.truncate_label = 15
    my_config.show_y_guides = False
    my_config.width = 1300

    result.loc[:, result.columns != 'Language'] = (
        result.loc[:, result.columns != 'Language'] /
        result.loc[:, result.columns != 'Language'].sum()) * 100

    bar_plot = pygal.StackedBar(my_config, style=my_style)
    bar_plot.title = 'Timeline analysis'
    year_start, year_end = min(years), max(years)
    bar_plot.x_labels = map(str, range(year_start, year_end + 1))

    for i, lang in enumerate(result['Language']):
        cut_lang = result.loc[:, result.columns != 'Language']
        values_yearly = list(cut_lang.iloc[i])
        bar_plot.add(lang, values_yearly)

    return bar_plot
Exemple #4
0
def _report_2(request, ctx):
    ctx['report_title'] = 'Presupuestos expandidos (en el tiempo)'
    chart = pygal.StackedBar(legend_at_bottom=True,
                             y_title="$",
                             x_label_rotation=20)  # @UndefinedVariable
    chart.title = ctx['report_title']

    cursor = connection.cursor()
    # FIXME: use only accepted quotes! (not canceled, or rejected by customer)
    cursor.execute(
        "SELECT "
        " lsq.created AS \"date_for_report\","
        " lsq.cost AS \"orig_cost\","
        " lsqa.cost AS \"selected_quote_alternative_cost\","
        " c.name AS \"customer\""
        " FROM lumina_session AS ls"
        " JOIN lumina_sessionquote AS lsq ON lsq.session_id = ls.id"
        " JOIN lumina_customer AS c ON ls.customer_id = c.id"
        " LEFT OUTER JOIN lumina_sessionquotealternative AS lsqa"
        "    ON lsq.accepted_quote_alternative_id = lsqa.id"
        " WHERE ls.studio_id = %s", [request.user.studio.id])
    desc = cursor.description
    values_as_dict = [
        dict(list(zip([col[0] for col in desc], row)))
        for row in cursor.fetchall()
    ]

    # pprint.pprint(values_as_dict)

    group_by_date = defaultdict(list)
    for item in values_as_dict:
        group_by_date[(item['date_for_report'].year,
                       item['date_for_report'].month)].append(item)
    dates = list(group_by_date.keys())
    dates.sort()

    logger.info("group_by_date: %s", pprint.pformat(group_by_date))

    serie_cost = []
    serie_alt_quote = []
    labels = []

    for year, month in dates:
        acum_cost = 0.0
        acum_alt_quote = 0.0
        for item in group_by_date[(year, month)]:
            acum_cost += float(item['orig_cost'])
            if item['selected_quote_alternative_cost']:
                acum_alt_quote += float(
                    item['selected_quote_alternative_cost'])
        labels.append("{}/{}".format(month, year))
        serie_cost.append(acum_cost)
        serie_alt_quote.append(acum_alt_quote)

    chart.x_labels = labels
    chart.add('Presupuesto original', serie_cost)
    chart.add('Presupuesto expandido', serie_alt_quote)
    chart.print_values = False
    ctx['svg_chart'] = chart.render()
    ctx['show_form_2'] = True
Exemple #5
0
def create_chart(hvgc, hhgc, msw):
    """ Create chart """
    chart = pygal.StackedBar(truncate_label=5,
                             style=CleanStyle,
                             fill=True,
                             dots_size=1.75,
                             interpolate='cubic')

    chart.x_title = 'Year'
    chart.y_title = 'Video Games Amount'

    chart.x_labels = [i for i in range(1980, 2017)]
    chart.x_labels_major_count = 8
    chart.show_minor_x_labels = False
    chart.y_labels = [i for i in range(0, 18001, 2000)]

    chart.legend_at_bottom = True
    chart.legend_at_bottom_columns = 3
    chart.legend_box_size = 16

    chart.add("Home Video Game Consoles", hvgc)
    chart.add("Handheld Game Consoles", hhgc)
    chart.add("Microsoft Windows", msw)

    chart.render_to_file('growth.svg')
Exemple #6
0
def create_missing_emotions_chart_V2(trusted_src_dict):
    
    custom_style = Style(label_font_size = 14, major_label_font_size=14,value_font_size=14,value_label_font_size=14)
    
    
    
    keys = trusted_src_dict.keys()
    
    sadness_vals = []
    anger_vals = [] 
    joy_vals = []
    disgust_vals = []
    fear_vals = []
    
    for key in trusted_src_dict.keys():
        sadness_vals.append(trusted_src_dict[key]['sadness'])
        anger_vals.append(trusted_src_dict[key]['anger'])
        joy_vals.append(trusted_src_dict[key]['joy'])
        disgust_vals.append(trusted_src_dict[key]['disgust'])
        fear_vals.append(trusted_src_dict[key]['fear'])
    
    line_chart = pygal.StackedBar(x_label_rotation=90,style=custom_style)
    line_chart.x_labels = keys
    line_chart.add('sadness', sadness_vals)
    line_chart.add('anger',  anger_vals)
    line_chart.add('joy',      joy_vals)
    line_chart.add('disgust',  disgust_vals)
    line_chart.add('fear',  fear_vals)
    line_chart.render_to_png('./example_missing_emotion.png')
Exemple #7
0
def graphSentenceWordUse(sentences, top=0, fileName=args.args.file):
    num = len(sentences) + 1
    chart = pygal.StackedBar(print_labels=True, show_legend=False)
    chart.title = 'Word Use By Sentence'
    if top > 0:
        chart.title += ' Of Top ' + str(top) + ' Words'
        mostUsed = most_used_words.mostUsed(fileName, top=top)
        mostUsed = {word['label']: word['value'] \
            for word in mostUsed}
    chart.x_labels = map(str, range(1, num))
    sentencesByWord = [[taxonomy.sanitize(word) for word in sentence.split()] \
        for sentence in sentences]
    allWords = {}
    for sentence in sentencesByWord:
        for word in sentence:
            allWords[word] = {'label': word, 'value': 0}
    wordCounts = [copy.deepcopy(allWords) for sentence in sentencesByWord]
    for i in xrange(0, len(sentencesByWord)):
        for word in sentencesByWord[i]:
            wordCounts[i][word]['value'] += 1
    perWord = {}
    for i in xrange(0, len(wordCounts)):
        for word in wordCounts[i]:
            if not word in perWord:
                perWord[word] = []
            if wordCounts[i][word]['value'] < 1 or \
                (top > 0 and not word in mostUsed):
                wordCounts[i][word]['label'] = ''
                wordCounts[i][word]['value'] = 0
            perWord[word].append(wordCounts[i][word])
    for word in perWord:
        chart.add(word, perWord[word])
    fileName = chart.title.lower().replace(' ', '_')
    chart.render_to_png(taxonomy.outdir(fileName + '.png'))
def stacked_bar():
    chart = pygal.StackedBar()
    chart.title = 'starked_bar'
    chart.x_labels = map(str, range(size))
    chart.add('Number 1 Test one', get_random_data(size))
    chart.add('Number 2 Test two', get_random_data(size))
    chart.render_to_file(get_file_name(inspect.stack()[0][3]))
Exemple #9
0
def stacked(data, dirname):
    data = deepcopy(data)
    tasks = sorted(data.keys())

    # Use a fixed order of methods in the plot
    methods = ("mel", "cmds", "PyMEL", "cmdx")

    # [group1 result, group2 result, ... of MEL]
    # [group1 result, group2 result, ... of cmds]
    # ...

    cols = list()
    for method in methods:
        col = list()
        for task in tasks:
            col += [data[task].get(method, {}).get("min", 0)]
        cols.append(col)

    # Normalise along Y-axis
    rows = zip(*cols)

    for index, row in enumerate(rows[:]):
        rows[index] = [100.0 * col / sum(row) for col in row]

    cols = zip(*rows)

    line_chart = pygal.StackedBar()
    line_chart.title = "cmdx performance plot (in %)"
    line_chart.x_labels = tasks

    for method, col in enumerate(cols):
        line_chart.add(methods[method], col)

    fname = os.path.join(dirname, "stacked.svg")
    line_chart.render_to_file(fname)
Exemple #10
0
def graph(total):
    # this is the name of each county and the total votes
    print("--- graph test ---")
    county_and_votes = {}
    county_names = []
    county_votes = []
    for county_name, d in total.items():
        county_names.append(county_name)
        total_votes = 0
        for party_name, count in total[county_name].items():
            total_votes = total_votes + total[county_name][party_name]
        county_and_votes[county_name] = total_votes
    top_five_names = Nmaxelements(county_and_votes, 5)

    my_config = pygal.Config()
    my_config.x_label_rotation = 0
    my_config.x_label_font_size = 14
    my_config.show_legend = True
    my_config.truncate_label = 15
    my_config.width = 1000
    chart = pygal.StackedBar(my_config)
    chart.title = 'Parties'
    chart.x_labels = top_five_names
    chart.add('UNA', [total[x]['UNA'] for x in top_five_names])
    chart.add('DEM', [total[x]['DEM'] for x in top_five_names])
    chart.add('REP', [total[x]['REP'] for x in top_five_names])
    chart.add('LIB', [total[x]['LIB'] for x in top_five_names])
    chart.add('GRE', [total[x]['GRE'] for x in top_five_names])
    chart.add('CST', [total[x]['CST'] for x in top_five_names])
    chart.render_in_browser()
Exemple #11
0
def weekly_users():
    # unique active users per week
    # Get URL parameters
    number_of_weeks = int(request.args.get('weeks', 4))
    selected_filter = request.args.get('filter', 'version')
    # Create a list with the number of weeks you want to compare
    sunday = (
    datetime.date.today() - datetime.timedelta(days=datetime.date.today().weekday()) + datetime.timedelta(days=6,
                                                                                                          weeks=-1))
    week_list = list(reversed([(sunday - datetime.timedelta(days=(x + 1) * 7),
                                (sunday - datetime.timedelta(days=+1)) - datetime.timedelta(days=(x) * 7)) for x in
                               range(0, number_of_weeks-1)]))
    week_list.append([sunday, datetime.date.today()])
    if selected_filter is not None:
        filter_list = get_filter_list(selected_filter, week_list[0][0], week_list[-1][1])
    users_per_week = []
    for filter in filter_list:
        filter, = filter
        week_data = [filter, []]
        for week in week_list:
            week_data[1].append(len(get_users_between_dates(week[0], week[1], selected_filter, filter)))
        users_per_week.append(week_data)
    line_chart = pygal.StackedBar()
    line_chart.title = 'Weekly unique users count, segmented by {}'.format(selected_filter)
    line_chart.x_labels = [(str(week_list[i][0])+'/'+str(week_list[i][1])) for i in range(0, len(week_list))]
    for week in users_per_week:
        line_chart.add(week[0], week[1])
    return line_chart.render_data_uri()
Exemple #12
0
def stacked_bar(news_src, num_pos, num_neg, num_neut):
    totals = [
        num_pos[0] + num_neg[0] + num_neut[0],
        num_pos[1] + num_neg[1] + num_neut[1],
        num_pos[2] + num_neg[2] + num_neut[2],
        num_neut[3] + num_pos[3] + num_neg[3],
        num_pos[4] + num_neg[4] + num_neut[4],
        num_pos[5] + num_neg[5] + num_neut[5]
    ]
    bar_chart = pygal.StackedBar()
    bar_chart.title = 'Sentiment Across News Sources'
    bar_chart.x_labels = [
        news_src[0], news_src[1], news_src[2], news_src[3], news_src[4],
        news_src[5]
    ]
    bar_chart.add('Positive', [(num_pos[0] / totals[0]),
                               (num_pos[1] / totals[1]),
                               (num_pos[2] / totals[2]),
                               (num_pos[3] / totals[3]),
                               (num_pos[4] / totals[4]),
                               (num_pos[5] / totals[5])])
    bar_chart.add('Negative', [(num_neg[0] / totals[0]),
                               (num_neg[1] / totals[1]),
                               (num_neg[2] / totals[2]),
                               (num_neg[3] / totals[3]),
                               (num_neg[4] / totals[4]),
                               (num_neg[5] / totals[5])])
    bar_chart.add('Neutral', [(num_neut[0] / totals[0]),
                              (num_neut[1] / totals[1]),
                              (num_neut[2] / totals[2]),
                              (num_neut[3] / totals[3]),
                              (num_neut[4] / totals[4]),
                              (num_neut[5] / totals[5])])
    bar_chart.render_to_file('stacked_bar.svg')
Exemple #13
0
    def _generar_grafico_de_barras_de_llamadas_entrantes(self, estadisticas):
        grafico = pygal.StackedBar(show_legend=True,
                                   style=ESTILO_VERDE_GRIS_NEGRO)

        nombres_campanas = []
        atendidas = []
        expiradas = []
        abandonadas = []
        abandonadas_anuncio = []
        por_campana = estadisticas['tipos_de_llamada_por_campana'][str(
            Campana.TYPE_ENTRANTE)]
        for datos_campana in por_campana.values():
            nombres_campanas.append(datos_campana['nombre'])
            atendidas.append(datos_campana['atendidas'])
            abandonadas.append(datos_campana['abandonadas'])
            abandonadas_anuncio.append(datos_campana['abandonadas_anuncio'])
            expiradas.append(datos_campana['expiradas'])

        grafico.x_labels = nombres_campanas
        grafico.add(_(u'Atendidas'), atendidas)
        grafico.add(_(u'Abandonadas'), abandonadas)
        grafico.add(_(u'Abandonadas durante anuncio'), abandonadas_anuncio)
        grafico.add(_(u'Expiradas'), expiradas)
        self.graficos[
            'barra_campana_llamadas_entrantes'] = adicionar_render_unicode(
                grafico)
Exemple #14
0
def percent_graph():
    hours = int(request.args.get('hours', 24))
    since = datetime.now() - timedelta(hours=hours)

    stats_query = db.session.query(WorkerStat).filter(
        WorkerStat.created > since).with_entities(WorkerStat.created,
                                                  WorkerStat.toots,
                                                  WorkerStat.tweets,
                                                  WorkerStat.instas)

    df = pd.read_sql(stats_query.statement, stats_query.session.bind)
    df.set_index(['created'], inplace=True)

    df.groupby(level=0).sum()
    r = df.resample('h').sum()
    r = r.fillna(0)

    r['total'] = r['toots'] + r['tweets'] + r['instas']
    r['tweets_p'] = r['tweets'] / r['total']
    r['toots_p'] = r['toots'] / r['total']
    r['instas_p'] = r['instas'] / r['total']

    toots_p = r['toots_p'].tolist()
    tweets_p = r['tweets_p'].tolist()
    instas_p = r['instas_p'].tolist()

    chart = pygal.StackedBar(
        title=f"Ratio of Incoming Messages ({timespan(hours)})",
        human_readable=True,
        legend_at_bottom=True)
    chart.add('Toots', toots_p)
    chart.add('Tweets', tweets_p)
    chart.add('Instas', instas_p)

    return chart.render_response()
Exemple #15
0
    def _generar_grafico_de_barras_de_llamadas_dialer(self, estadisticas):
        grafico = pygal.StackedBar(show_legend=True,
                                   style=ESTILO_ROJO_VERDE_GRIS_NEGRO)

        nombres_campanas = []
        no_atendidas = []
        conectadas = []
        expiradas = []
        abandonadas = []
        por_campana = estadisticas['tipos_de_llamada_por_campana'][str(
            Campana.TYPE_DIALER)]
        for datos_campana in por_campana.values():
            nombres_campanas.append(datos_campana['nombre'])
            no_atendidas.append(datos_campana['efectuadas'] -
                                datos_campana['atendidas'])
            conectadas.append(datos_campana['conectadas'])
            abandonadas.append(datos_campana['abandonadas'])
            expiradas.append(datos_campana['expiradas'])

        grafico.x_labels = nombres_campanas
        grafico.add(_(u'No contactadas'), no_atendidas)
        grafico.add(_(u'Procesadas'), conectadas)
        grafico.add(_(u'Abandonadas'), abandonadas)
        grafico.add(_(u'Expiradas'), expiradas)
        self.graficos[
            'barra_campana_llamadas_dialer'] = adicionar_render_unicode(
                grafico)
Exemple #16
0
 def __init__(self, start_time, end_time, study_groups, **kwargs):
     style = custom_style()
     style.colors = ["#4c7e80", "#FC7100", "#FFBC1A", "#B7D500", "#05C6B4"]
     self.chart = pygal.StackedBar(style=style, order_min=0, y_title="Number of ratings", x_label_rotation=30, **kwargs)
     self.study_groups = study_groups
     self.start_time = start_time
     self.end_time = end_time
Exemple #17
0
def plot_memory(data):
    chart = pygal.StackedBar(CONFIG)
    _plot_generic(
        data, chart, 'Peakmem', lambda p: p[VALID_ATTRS['peakmem']]
    )

    return chart.render(is_unicode=True)
Exemple #18
0
def create_issue_classification_chart(domain):
    line_chart = pygal.StackedBar(height=200)
    selected_domain = Domain.objects.get(name=domain)
    libraries = selected_domain.library_set.all()

    library_names = []
    performance_issues = []
    security_issues = []
    performance_security_issues = []
    no_classification_issues = []
    for library in libraries:
        library_names.append(library.name)
        performance_issues.append(library.issue_set.all().filter(
            performance_issue=True, security_issue=False).count())
        security_issues.append(library.issue_set.all().filter(
            security_issue=True, performance_issue=False).count())
        performance_security_issues.append(library.issue_set.all().filter(
            security_issue=True, performance_issue=True).count())
        no_classification_issues.append(library.issue_set.all().filter(
            security_issue=False, performance_issue=False).count())
    line_chart.x_labels = library_names
    line_chart.add('Performance', performance_issues)
    line_chart.add('Security', security_issues)
    line_chart.add('Both', performance_security_issues)
    line_chart.add('None', no_classification_issues)
    data = line_chart.render_data_uri()
    saveData(data, domain + '_issue_classification_chart.pkl')
    return data
Exemple #19
0
def plot_dist_lengths(lengths, length_limit, x_step, max_x, y_step, max_y, outimg):
    """
    Plot a length distribution over sentences
            Inputs:
                - lengths: list of numerical lenghts
                - length_limit: maximum allowed length
                - x_step: step in the horizontal axis
                - max_x: maximum value in the horizontal axis
                - y_step: step in the vertical axis
                - max_y: maximum value in the vertical axis
                - outimg: output image
    """
    # count number of occurrences for each length value
    c = Counter(lengths)
    max_val = min(max_x, max(max_x, max(c.keys())))

    # output in svg format
    xdata = list(range(1, max_val + x_step + 1))
    ydata_used = [c[k] if k in c and k <= length_limit else 0 for k in xdata]
    ydata_unused = [c[k] if k in c and k > length_limit else 0 for k in xdata]

    line_chart = pygal.StackedBar(width=1300, height=800, x_label_rotation=-45,
                                  x_title='Number of words', y_title='Number of sentences',
                                  show_minor_x_labels=False)
    line_chart.x_labels = xdata
    line_chart.x_labels_major = list(set([x // x_step * x_step for x in xdata]))
    line_chart.y_labels = range(0, max_y + 1, y_step)
    line_chart.add('Truncated data', ydata_unused)
    line_chart.add('Unchanged data', ydata_used)

    # circumvent potential svg styling problems
    line_chart.render_to_file(outimg)
    cairosvg.svg2svg(url=outimg, write_to=outimg)
Exemple #20
0
def ia_coverage_histogram(rows):
    """
    Note: this returns a raw pygal chart; it does not render it to SVG/PNG
    """

    raw_years = [int(r[0]) for r in rows]
    years = dict()
    for y in range(min(raw_years), max(raw_years)+1):
        years[int(y)] = dict(year=int(y), available=0, missing=0)
    for r in rows:
        if r[1]:
            years[int(r[0])]['available'] = r[2]
        else:
            years[int(r[0])]['missing'] = r[2]

    years = sorted(years.values(), key=lambda x: x['year'])

    CleanStyle.colors = ("green", "purple")
    label_count = len(years)
    if len(years) > 20:
        label_count = 10
    chart = pygal.StackedBar(dynamic_print_values=True, style=CleanStyle,
        width=1000, height=500, x_labels_major_count=label_count,
        show_minor_x_labels=False)
    #chart.title = "Perpetual Access Coverage"
    chart.x_title = "Year"
    #chart.y_title = "Releases"
    chart.x_labels = [str(y['year']) for y in years]
    chart.add('via Fatcat', [y['available'] for y in years])
    chart.add('Missing', [y['missing'] for y in years])
    return chart
def create_issue_classification_chart(domain):
    domain_name = domain.name
    line_chart = pygal.StackedBar(height=200)
    line_chart.title = "Number of issues of each type per library"
    selected_domain = Domain.objects.get(name=domain_name)
    libraries = selected_domain.libraries.all()

    library_names = []
    performance_issues = []
    security_issues = []
    performance_security_issues = []
    no_classification_issues = []
    for library in libraries:
        library_names.append(library.name)
        performance_issues.append(
            library.issues.filter(performance_issue=True,
                                  security_issue=False).count())
        security_issues.append(
            library.issues.filter(security_issue=True,
                                  performance_issue=False).count())
        performance_security_issues.append(
            library.issues.filter(security_issue=True,
                                  performance_issue=True).count())
        no_classification_issues.append(
            library.issues.filter(security_issue=False,
                                  performance_issue=False).count())
    line_chart.x_labels = library_names
    line_chart.add('Performance', performance_issues)
    line_chart.add('Security', security_issues)
    line_chart.add('Both', performance_security_issues)
    line_chart.add('None', no_classification_issues)
    data = line_chart.render_data_uri()
    saveData(data, domain_name + '_issue_classification_chart.pkl')
    save_chart_in_db(line_chart, domain, metric_name="issue classification")
Exemple #22
0
    def get_trades_chart(self, days=None):
        trades = self.bottrade_set.filter(
            time__gte=now() - datetime.timedelta(days=60),
            profit_usd__isnull=False,
            bot_trade=True,
        )

        chart = pygal.StackedBar(
            x_title="Days",
            y_title="Value in USD",
            legend_at_bottom=True,
            style=CleanStyle(font_family="googlefont:Raleway",
                             value_font_size=10),
            dynamic_print_values=True,
        )
        chart.value_formatter = lambda x: "$%.2f USD" % x
        chart.title = "Aggregated profits over time"

        if days is None:
            days = [1, 3, 7, 14, 30]

        chart.x_labels = days
        profits = {"buy": [], "sell": []}

        if not self.base:
            return chart.render_data_uri()

        movements = get_price_movement(self.base_price_url, self.base)

        for side in ["buy", "sell"]:
            running_total = 0
            previous_day = 0

            for day in days:
                profit = trades.filter(
                    trade_type=side,
                    time__lt=now() - datetime.timedelta(days=previous_day),
                    time__gte=now() - datetime.timedelta(days=day),
                ).aggregate(profit=Sum("profit_usd"))["profit"]

                movement_factor = 1

                if movements:
                    movement_factor = (movements.get("number_of_days", {}).get(
                        str(day), {}).get("movement_factor", 1))

                if profit:
                    adjusted_profit = profit * movement_factor
                else:
                    adjusted_profit = 0

                running_total += adjusted_profit
                profits[side].append(running_total)

                previous_day = day

        chart.add("Buy", profits["buy"])
        chart.add("Sell", profits["sell"])
        return chart.render_data_uri()
def chart(data, label):
    want = 10
    line_chart = pygal.StackedBar()
    line_chart.title = 'skill want top 10'
    line_chart.x_labels = label[:want]
    for i, j in data:
        line_chart.add(i, j[:want])
    line_chart.render_to_file('img/allskillwant2.svg')
Exemple #24
0
 def _get_bar_chart(self):
     return pygal.StackedBar(
         self.config,
         style=self._get_style(),
         no_data_text=self.config.no_data_text,
         disable_xml_declaration=True,  # for correct svg in web page
         explicit_size=True,
         show_dots=False)
Exemple #25
0
 def create_hybrid_month():
     """create graph"""
     bar_chart = pygal.StackedBar(x_label_rotation=90)
     bar_chart.title = "ผลรวมของรถยนต์ไฮบริดแต่ละประเภทของแต่ละเดือน"
     bar_chart.x_labels = all_months()
     for i in np(hybrid_by_month):
         bar_chart.add(i[0], i[1:])
     bar_chart.render_to_file('All_hybrid_each_month.svg')
Exemple #26
0
    def get_trades_chart(self, days=None):
        trades = self.bottrade_set.filter(time__gte=now() -
                                          datetime.timedelta(days=60),
                                          profit_usd__isnull=False,
                                          bot_trade=True)

        chart = pygal.StackedBar(
            x_title='Days',
            y_title='Value in USD',
            legend_at_bottom=True,
            style=CleanStyle(font_family='googlefont:Raleway',
                             value_font_size=10),
            dynamic_print_values=True,
        )
        chart.value_formatter = lambda x: "$%.2f USD" % x
        chart.title = 'Aggregated profits over time'

        if days is None:
            days = [1, 3, 7, 14, 30]

        chart.x_labels = days
        profits = {'buy': [], 'sell': []}

        if not self.base:
            return chart.render_data_uri()

        movements = get_price_movement(self.base_price_url, self.base)

        for side in ['buy', 'sell']:
            running_total = 0
            previous_day = 0

            for day in days:
                profit = trades.filter(
                    trade_type=side,
                    time__lt=now() - datetime.timedelta(days=previous_day),
                    time__gte=now() - datetime.timedelta(days=day)).aggregate(
                        profit=Sum('profit_usd'))['profit']

                movement_factor = 1

                if movements:
                    movement_factor = movements.get('number_of_days', {}).get(
                        str(day), {}).get('movement_factor', 1)

                if profit:
                    adjusted_profit = profit * movement_factor
                else:
                    adjusted_profit = 0

                running_total += adjusted_profit
                profits[side].append(running_total)

                previous_day = day

        chart.add('Buy', profits['buy'])
        chart.add('Sell', profits['sell'])
        return chart.render_data_uri()
Exemple #27
0
def forecast():
    """ render svg graph """
    bar_chart = pygal.StackedBar(style=NeonStyle)
    bar_chart.title = "Hyderabad Forecast"
    lower,higher,days = get_forecast()
    bar_chart.add('Kanishtam', lower)
    bar_chart.add('Garishtam', higher)
    bar_chart.x_labels = days
    return Response(response=bar_chart.render(), content_type='image/svg+xml')
def dump_stacked_bar_chart(dirname, filename, title, x_labels, chart_data):
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    filepath = os.path.join(dirname, filename)
    chart = pygal.StackedBar(show_y_guides=True, x_label_rotation=20)
    chart.title = title
    chart.x_labels = x_labels
    for name, stuff in chart_data.items():
        chart.add(name, stuff)
    chart.render_to_file(filepath)
Exemple #29
0
 def get_svg_count_by_day(self):
     chart = pygal.StackedBar(width=960,
                              height=480,
                              explicit_size=True,
                              show_legend=False)
     chart.title = "Registered users by day"
     chart.x_labels = map(lambda d: d.strftime('%d'), self.active.index)
     chart.add('Activated', self.active['id'])
     chart.add('Non-activated', self.nonactive['id'])
     return chart.render()
def barChart():
    bar_chart= pygal.StackedBar()
    datalist = []
    proselect = Projectpy.select()
    for amountkdj in proselect:
        datalist.append(amountkdj.amount)
    label1 = 'amount'
    bar_chart.add(label1, datalist)
    bar_chart = bar_chart.render_data_uri()
    return bar_chart