Esempio n. 1
0
def generate_bridge_sparkline(data):
    """ Generates a sparkline that shows the development of the
        bridge's traffic over a period of time.
    """
    style = Style()
    style.background = 'transparent'
    style.plot_background = 'transparent'
    chart = pygal.StackedLine(fill=True, show_x_labels=False, show_y_labels=False,
                               margin=0, style=TorcollectStyle(), include_x_axis=True)
    chart.add('', data['sent'])
    chart.add('', data['received'])
    return clean_graph(chart.render_sparkline(interpolate="cubic"))
Esempio n. 2
0
def gu_style(rows):
    style = Style(
        opacity=1,
        opacity_hover=0.7,
        background='white',
        plot_background='white',
        foreground='rgba(0, 0, 0, 0.7)',
        foreground_light='rgba(0, 0, 0, 0.9)',
        foreground_dark='rgba(0, 0, 0, 0.5)',
        colors=('#242424', '#9f6767', '#92ac68',
                '#d0d293', '#9aacc3', '#bb77a4',
                '#77bbb5', '#777777'))
    style.colors = [row.get('colour', alt) for row, alt in
            izip(rows, cycle(style.colors))]
    return style
Esempio n. 3
0
def bar():
    with open('bitcoin_prices.json', 'r') as data_file:
        bitcoin_data = json.load(data_file)
    with open('ethereum_prices.json', 'r') as data_file:
        ethereum_data = json.load(data_file)
    with open('litecoin_prices.json', 'r') as data_file:
        litecoin_data = json.load(data_file)
    with open('monero_prices.json', 'r') as data_file:
        monero_data = json.load(data_file)
    with open('dash_prices.json', 'r') as data_file:
        dash_data = json.load(data_file)
    with open('iota_prices.json', 'r') as data_file:
        iota_data = json.load(data_file)
    with open('nem_prices.json', 'r') as data_file:
        nem_data = json.load(data_file)
    with open('omisego_prices.json', 'r') as data_file:
        omisego_data = json.load(data_file)
    with open('qtum_prices.json', 'r') as data_file:
        qtum_data = json.load(data_file)
    with open('stratis_prices.json', 'r') as data_file:
        stratis_data = json.load(data_file)
    with open('waves_prices.json', 'r') as data_file:
        waves_data = json.load(data_file)

    custom_style = Style(colors=('#0f2c58', '#005a8e', '#008cad', '#00677b',
                                 '#14837c', '#00bdab', '#3cea8d'),
                         background='#000000',
                         plot_background='#1a1a1a',
                         foreground='#ffffff',
                         foreground_subtle='#ffffff',
                         foreground_strong='#ffffff',
                         legend_font_size=10,
                         font_family='googlefont:Raleway',
                         major_label_font_size=7,
                         label_font_size=8,
                         title_font_size=12)
    chart = pygal.HorizontalBar(width=600,
                                height=300,
                                style=custom_style,
                                x_title='Open - Close')
    chart.title = 'Average difference between Open and Close prices'
    #chart.x_labels = ['Bitcoin', 'Ethereum', 'Nem', 'Omisego', 'Qtum', 'Stratis', 'Waves']

    bitcoin_list = []
    for x in bitcoin_data:
        bitcoin_list.append(x['Open'] - x['Close'])
    avg = sum(bitcoin_list) / len(bitcoin_list)
    chart.add('Bitcoin', avg)

    ethereum_list = []
    for x in ethereum_data:
        ethereum_list.append(x['Open'] - x['Close'])
    avg = sum(ethereum_list) / len(ethereum_list)
    chart.add('Ethereum', avg)

    nem_list = []
    for x in nem_data:
        nem_list.append(x['Open'] - x['Close'])
    avg = sum(nem_list) / len(nem_list)
    chart.add('Nem', avg)

    omisego_list = []
    for x in omisego_data:
        omisego_list.append(x['Open'] - x['Close'])
    avg = sum(omisego_list) / len(omisego_list)
    chart.add('Omisego', avg)

    qtum_list = []
    for x in qtum_data:
        qtum_list.append(x['Open'] - x['Close'])
    avg = sum(qtum_list) / len(qtum_list)
    chart.add('Qtum', avg)

    stratis_list = []
    for x in stratis_data:
        stratis_list.append(x['Open'] - x['Close'])
    avg = sum(stratis_list) / len(stratis_list)
    chart.add('Stratis', avg)

    waves_list = []
    for x in waves_data:
        waves_list.append(x['Open'] - x['Close'])
    avg = sum(waves_list) / len(waves_list)
    chart.add('Waves', avg)

    chart.render_to_file('static/images/bar_chart.svg')
    img_url = 'static/images/bar_chart.svg?cache=' + str(time.time())
    return render_template('template.html', image_url=img_url)
Esempio n. 4
0
def home():

    #    print ("__xlabels__",var_x_labels)
    #####################################Active session chart #####
    custom_style = Style(colors=('#351508', '#404040', '#9BC850'))
    title = 'STB Uptime'
    bar_chart = pygal.Bar(width=400,
                          height=400,
                          explicit_size=True,
                          title=title,
                          x_label_rotation=90,
                          style=custom_style)
    var_x_labels = []
    var_data = []
    for idx1 in list(range(0, len(data_time_spent))):
        var_end_time = datetime.utcfromtimestamp(
            int(data_time_spent.Date_Time[idx1])).strftime('%Y-%m-%d %H:%M:%S')
        var_x_labels.append(var_end_time)
        var_data.append(data_time_spent.Time_spent[idx1])
#        print(data_time_spent.Time[idx1])

    bar_chart.x_labels = var_x_labels
    var_time_spent = var_data

    bar_chart.add('Active session time', var_time_spent)
    bar_chart.render_to_file('static/images/bar_chart.svg')
    #####################################Active session line chart #####
    line_chart = pygal.Line()
    line_chart.title = 'Time series'
    # line_chart.x_labels = map(
    #     date.isoformat,
    #     rrule(DAILY, dtstart=date(2010, 8, 1), until=date.today())
    # )
    # line_chart.y_labels = map(str,range(1,25))
    var_date_series = []
    var_start_time_series = []
    var_end_time_series = []
    var_time_series_plot = []
    for idx1 in list(range(0, len(data_time_spent))):
        tmp_start_time = data_time_spent.Date_Time[
            idx1] - data_time_spent.Time_spent[idx1]
        var_date_series.append(
            datetime.utcfromtimestamp(
                int(tmp_start_time)).strftime('%Y-%m-%d'))
        var_start_time_series.append(
            datetime.utcfromtimestamp(
                int(tmp_start_time)).strftime('%H:%M:%S'))
        var_end_time_series.append(
            datetime.utcfromtimestamp(int(
                data_time_spent.Date_Time[idx1])).strftime('%H:%M:%S'))
    line_chart.x_labels = var_date_series
    line_chart.x_labels = map(str, range(2002, 2013))
    print("##########var date series####", var_date_series)
    print("##########var start time series####", var_start_time_series)
    print("##########var end time  series####", var_end_time_series)
    line_chart.add("start Time", [12, 34, 10, 5, 7])
    line_chart.add("End Time", [22, 12, 13, 16, 5])
    line_chart.render_to_file('static/images/line_chart.svg')

    ################################### Avg time spent chart #######
    title2 = 'Avg time spent on each screen'
    custom_style = Style(colors=('#059467', '#9BC850', '#E80080'))
    avg_bar_chart = pygal.Bar(width=1200,
                              height=800,
                              explicit_size=True,
                              title=title2,
                              x_label_rotation=70,
                              style=custom_style)
    var_x_labels = []
    var_data = []
    #    print ("__xlabels__",var_x_labels)
    #    print ("avg time spent===",avg_time_spent)
    for idx1 in list(range(0, len(avg_time_spent))):
        var_x_labels.append(avg_time_spent.Screen_id[idx1])
        var_data.append(avg_time_spent.Avg_Time[idx1])
#        print(avg_time_spent.Avg_Time[idx1])

    avg_bar_chart.x_labels = var_x_labels
    #    bar_chart.y_labels = var_y_labels
    #    var_time_spent = [data_time_spent[x] for x in data_time_spent]
    #    print ("_Time spent_",var_time_spent)
    #    print ("_Time spent_0___",var_time_spent[0])
    #    print ("_Time spent_1___",var_time_spent[1])
    var_time_spent = var_data
    avg_bar_chart.add('Avg time sec', var_data)
    avg_bar_chart.render_to_file('static/images/screen_avg_chart.svg')

    ###################################
    title2 = 'Least used screens'
    custom_style = Style(colors=('#1878f7', '#404040', '#E80080'))
    avg_bar_chart = pygal.Bar(width=1200,
                              height=600,
                              explicit_size=True,
                              title=title2,
                              x_label_rotation=90,
                              style=custom_style)
    var_x_labels = []
    var_data = []
    #    print ("__xlabels__",var_x_labels)

    for idx1 in list(range(0, len(data_tf_idf))):
        var_x_labels.append(data_tf_idf.GUI[idx1])
        var_data.append(data_tf_idf.Priority[idx1])
#        print(avg_time_spent.Avg_Time[idx1])

    avg_bar_chart.x_labels = var_x_labels
    #    bar_chart.y_labels = var_y_labels
    #    var_time_spent = [data_tf_idf[x] for x in data_tf_idf]
    #    print ("_Time spent_",var_time_spent)
    #    print ("_Time spent_0___",var_time_spent[0])
    #    print ("_Time spent_1___",var_time_spent[1])
    var_time_spent = var_data
    avg_bar_chart.add('Least used screen', var_time_spent)
    avg_bar_chart.render_to_file('static/images/tf_idf_chart.svg')

    #====================Donut chart of the screens used==================

    pie_chart = pygal.Pie(width=1200,
                          height=600,
                          explicit_size=True,
                          inner_radius=.2)
    pie_chart.title = 'Time spent on each screen (in %)'
    var_x_labels = []
    var_data = []
    total_values = 0
    for idx1 in list(range(0, len(avg_time_spent))):
        total_values = total_values + avg_time_spent.Avg_Time[idx1]

#    print ("Total value===",total_values)
    for idx1 in list(range(0, len(avg_time_spent))):
        prcnt = round((avg_time_spent.Avg_Time[idx1] / total_values) * 100, 2)
        #        print ("% = ",prcnt)
        pie_chart.add(avg_time_spent.Screen_id[idx1], prcnt)

    pie_chart.render_to_file('static/images/donut.svg')

    #==================================Gauge chart==========
    gauge = pygal.SolidGauge(inner_radius=0.70)
    percent_formatter = lambda x: '{:.10g}%'.format(x)
    gauge.value_formatter = percent_formatter

    #====Screen Pattern Table Info=====================================

    for idx in list(range(0, len(avg_time_spent))):
        #        print (idx,"=>",avg_time_spent.Screen_id[idx])
        for idx2 in list(range(0, len(var_full_data))):
            if (avg_time_spent.Screen_id[idx] == var_full_data.ScreenName[idx2]
                ):
                #                print (idx2,"count=",var_full_data.ScreenName[idx2])
                if (idx2 + 1 >= len(var_full_data)):
                    continue
                else:
                    var_screen_id_dict[avg_time_spent.Screen_id[idx]].append(
                        var_full_data.ScreenName[idx2 + 1])
#                    print("screneid =",avg_time_spent.Screen_id[idx],"next id=",var_full_data.ScreenName[idx2+1])

#    print("The next screen list stored==========")
#    print (var_screen_id_dict)

#====scatter plot=====================================
#    xy_chart = pygal.XY(width=1200,height=600,explicit_size=True,stroke=False)
#    xy_chart.title = 'Scatter plot of the screen ID and time spent'
#    xy_chart.add('2', [(.1, .15), (.12, .23), (.4, .3), (.6, .4), (.21, .21), (.5, .3), (.6, .8), (.7, .8)])
#    xy_chart.add('3', [(.05, .01), (.13, .02), (1.5, 1.7), (1.52, 1.6), (1.8, 1.63), (1.5, 1.82), (1.7, 1.23), (2.1, 2.23), (2.3, 1.98)])
#    xy_chart.render_to_file('static/images/scatter.svg')

#======================================

    my_html = create_html_page()

    return my_html
Esempio n. 5
0
from sipa.units import (format_as_traffic, max_divisions, reduce_by_base)
from sipa.utils.babel_utils import get_weekday


def rgb_string(r, g, b):
    return "#{:02X}{:02X}{:02X}".format(int(r), int(g), int(b))


def hsl(h, s, l):
    return rgb_string(*hsl_to_rgb(h, s, l))


traffic_style = Style(background='transparent',
                      opacity='.6',
                      opacity_hover='.9',
                      transition='200ms ease-in',
                      colors=(hsl(130, 80, 60), hsl(70, 80,
                                                    60), hsl(190, 80, 60)),
                      font_family='default')


def default_chart(chart_type, title, inline=True, **kwargs):
    return chart_type(
        fill=True,
        title=title,
        height=350,
        show_y_guides=True,
        human_readable=False,
        major_label_font_size=12,
        label_font_size=12,
        style=traffic_style,
Esempio n. 6
0
def color_and_shape():
    # Style
    indonesia_progress_style = Style(
        background='transparent',
        plot_background='transparent',
        foreground='#00000',
        foreground_strong='#000000',
        #foreground_subtle='#630C0D',
        opacity='1',
        opacity_hover='.9',
        transition='400ms ease-in',
        font_family='googlefont:Roboto Slab',
        colors=('#FEE101', 'rgba(192,192,192,1)', 'burlywood'),
    )

    sports_style = Style(
        background='transparent',
        plot_background='transparent',
        foreground='#000000',
        foreground_strong='rgba(0,0,0,1)',
        foreground_subtle='#630C0D',
        opacity=1,
        transition='400ms ease-in',
        font_family='googlefont:Roboto Slab',
        colors=('#FEE101', '#AD8A56', 'rgba(255,0,0,1)'),
    )

    host_style = Style(
        background='transparent',
        plot_background='transparent',
        foreground='#000000',
        foreground_strong='#000000',
        foreground_subtle='#000000',
        opacity='1',
        opacity_hover='.9',
        transition='400ms ease-in',
        font_family='googlefont:Roboto Slab',
        colors=('#a0a0a0', '#a0a0a0', '#e6194b', '#a0a0a0', '#a0a0a0',
                '#a0a0a0', '#a0a0a0', '#228b22'),
    )

    # indonesia progress chart
    with open('data/indonesia_progress.json') as json_file:
        indonesia_progress_data = json.load(json_file)

    indonesia_progress_chart = IndonesiaProgressChart(
        data=indonesia_progress_data, style=indonesia_progress_style)
    indonesia_progress_chart.draw2()
    indonesia_progress_chart_rendered = indonesia_progress_chart.render()

    # sports chart
    with open('data/indonesia_medal.json') as json_file:
        sports_2018_data = json.load(json_file)

    indonesia_medal_sports_chart = IndonesiaSports2018Chart(
        data=sports_2018_data, style=sports_style)
    indonesia_medal_sports_chart.draw()
    indonesia_medal_sports_chart_rendered = indonesia_medal_sports_chart.render(
    )

    # host progress chart
    with open('data/asia_medal.json') as json_file:
        asia_progress_data = json.load(json_file)

    host_progress_chart = HostProgressChart(data=asia_progress_data,
                                            style=host_style)
    host_progress_chart.draw2()
    host_progress_chart_rendered = host_progress_chart.render()

    return render_template(
        'index.html',
        indonesia_progress_chart=indonesia_progress_chart_rendered,
        sports_chart=indonesia_medal_sports_chart_rendered,
        host_chart=host_progress_chart_rendered)
Esempio n. 7
0
import pygal
from datetime import datetime, date
from pygal.style import Style

invis_style = Style(background='transparent')


def generate(libraries, metric, chart_type):
    # default for chart_type is default chart to be created
    chart = None
    if metric == 'popularity':

        if chart_type == 'default' or chart_type == 'bar_raw':
            chart = generate_bar_chart_popularity(libraries)
        elif chart_type == 'pie':
            chart = generate_pie_chart_popularity(libraries)
        elif chart_type == 'gauge':
            chart = generate_solid_gauge_chart_popularity(libraries)

    elif metric == 'release-frequency':

        if chart_type == 'default' or chart_type == 'bar_avg':
            chart = generate_bar_chart_release_frequency(libraries)
        elif chart_type == 'box':
            chart = generate_box_chart_release_frequency(libraries)
        elif chart_type == 'line':
            chart = generate_line_chart_release_frequency(libraries)

    elif metric == 'last-modification-date':

        if chart_type == 'default' or chart_type == 'bar_days':
import pygal
from pygal.style import Style

#import my pokemon.py file to retrieve the dictionaries.
import pokemon as poke

#style for the radar chart
custom_style = Style(background='transparent',
                     plot_background='#ffffff',
                     opacity='0.1',
                     opacity_hover='0.9',
                     transition='400ms ease-out',
                     colors=('#d22800', '#00aad2', '#000000', '#d3d3d3',
                             '#008000', '11006c'),
                     font_family='googlefont:VT323',
                     major_label_font_size=16,
                     label_font_size=16,
                     title_font_size=40,
                     legend_font_size=24,
                     tooltip_font_size=16)

radar_chart = pygal.Radar(fill=True, style=custom_style)
radar_chart.title = 'Number of Each Type Per Generation'

#set the x labels
radar_chart.x_labels = [
    'Psychic', 'Ice', 'Flying', 'Ground', 'Electric', 'Normal', 'Water',
    'Fire', 'Fairy', 'Rock', 'Dark', 'Bug', 'Poison', 'Ghost', 'Fighting',
    'Dragon', 'Grass', 'Steel'
]
Esempio n. 9
0
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see http://www.gnu.org/licenses/.
#

"""Modulo utiles para reporteria"""

from pygal.style import Style

ESTILO_AMARILLO_VERDE_ROJO = Style(
    background='transparent',
    plot_background='transparent',
    foreground='#555',
    foreground_light='#555',
    foreground_dark='#555',
    opacity='1',
    opacity_hover='.6',
    transition='400ms ease-in',
    colors=('#fefd6f', '#5cb85c', '#b93229')
)

ESTILO_AZUL_VIOLETA_NARANJA_CELESTE = Style(
    background='transparent',
    plot_background='transparent',
    foreground='#555',
    foreground_light='#555',
    foreground_dark='#555',
    opacity='1',
    opacity_hover='.6',
    transition='400ms ease-in',
Esempio n. 10
0
            if row[7] == "ชาย":
                cnt6[0] += 1
            if row[7] == "หญิง":
                cnt6[1] += 1
        elif row[0][-2:] == "57":
            if row[7] == "ชาย":
                cnt7[0] += 1
            if row[7] == "หญิง":
                cnt7[1] += 1
        elif row[0][-2:] == "58":
            if row[7] == "ชาย":
                cnt8[0] += 1
            if row[7] == "หญิง":
                cnt8[1] += 1
    from pygal.style import Style
    custom_style = Style(colors=( '#339966','#32CD32', '#00FF7F', '#00CED1', \
    '#0000CD', '#0033FF', '#8A2BE2', '#EE82EE'))
    line_chart = pygal.HorizontalBar(style=custom_style)
    line_chart.title = 'เพศของบุคคลที่เกิดอุบัติเหตุ'
    line_chart.x_labels = map(str, ["ชาย", "หญิง"])
    line_chart.add('ปี 2551', cnt1)
    line_chart.add('ปี 2552', cnt2)
    line_chart.add('ปี 2553', cnt3)
    line_chart.add('ปี 2554', cnt4)
    line_chart.add('ปี 2555', cnt5)
    line_chart.add('ปี 2556', cnt6)
    line_chart.add('ปี 2557', cnt7)
    line_chart.add('ปี 2558', cnt8)
    line_chart.render_to_file('sex.svg')

Esempio n. 11
0
# COLORS = ("#2589BD", "#A39171", "#86BAA1", "#FFCF56", "#38686A", "#00635D", "#6D9DC5", "#A3B4A2")
COLORS = ("#009E73", "#E69F00", "#56B4E9", "#F0E442", "#0072B2", "#D55E00",
          "#CC79A7", "#999999")

style_args = dict(
    label_font_size=28,
    major_label_font_size=28,
    value_font_size=28,
    value_label_font_size=28,
    # tooltip_font_size=18,
    title_font_size=40,
    legend_font_size=34,
)

netdevops_style_trends = Style(colors=TRENDS_COLOR, **style_args)
netdevops_style_language = Style(colors=TRENDS_COLOR, **style_args)


def reorder_index_we_havent(indexes):
    """
    In a list of indexes, search for a string that start with either
        we haven or we are not
    and move it at the top of the list

    Return:
    List if indexes
    """
    tmp = list(indexes)

    # Identify if and where is the response "we haven't automated ..." and move it to the end
Esempio n. 12
0
import pandas as pd
import pygal as pg

from pygal.style import Style
custom_style = Style(background='transparent',
                     colors=('#18301e', '#0B421A', '#00723F', '#EAC784',
                             '#e5a632', '#604C4C', '#BBBBBB', '#AAAAAA'),
                     value_colors='#212320')


def main():
    raw_data = pd.read_csv('../../data/starbucks_drinkMenu_expanded.csv')

    beverage = dict()  #making dict for {beverage:[vlues]}
    for i in range(
            102,
            151):  #chage Number to index (see index in Data/beverage-index)
        if raw_data['Beverage'][i] not in beverage:
            beverage[raw_data['Beverage'][i]] = [raw_data[' Sugars (g)'][i]]
        else:
            beverage[raw_data['Beverage'][i]].append(
                raw_data[' Sugars (g)'][i])


#find sugar avg
    sugar_avg = 0
    for i in beverage:
        sugar_avg += sum(beverage[i])
    sugar_avg /= 49

    #graph making zone
Esempio n. 13
0
from flask import render_template

from update_server import app, db, model

from calendar import monthrange
from pygal.style import Style

# Py2 compat
try:
    FileNotFoundError
except NameError:
    FileNotFoundError = IOError


custom_style1 = Style(
    # Custom style to differenciate a graph
    colors=('blue', 'red'))



@app.route('/updates/geheime_stats', methods=['GET','POST'])
def stats():
    # Stats related to the CrossCloud's usage
    channel_activity_data = user_activity_per_channel()
    weekly_user_variation = weekly_user_gain_loss()
    weekly_user_count = weekly_users()
    monthly_user_count = monthly_users()
    current_versions_in_use = version_usage()
    return render_template("graphing.html",
                            channel_activity_data=channel_activity_data,
                            weekly_user_variation=weekly_user_variation,
Esempio n. 14
0
    def get(self, start_index):
        try:
            custom_style = Style(
                background='transparent',
                plot_background='transparent',
                foreground='#6c757d',
                foreground_strong='#6c757d',
                foreground_subtle='#6c757d',
                opacity='0.1',
                opacity_hover='0.2',
                transition='0ms',
                colors=('#749363', '#007acc'),
            )

            graph = pygal.Line(stroke_style={'width': 0.4},
                               show_legend=False,
                               fill=True,
                               style=custom_style,
                               disable_xml_declaration=True)

            start_index = int(start_index)
            total_entries = len(ctx.history.instance_history)
            detail_level = 500
            zoom_increment_factor = 2
            interval = max(1, ceil(
                (total_entries - start_index) / detail_level))
            instance_count = [
                history['time'] for history in
                ctx.history.instance_history[start_index::interval]
            ]

            if len(instance_count) > 0:
                graph.x_labels = [timeago.format(instance_count[0])]

            instance_counts = [
                {
                    'value': int(history['count']),
                    'label': timeago.format(history['time'])
                } for history in
                ctx.history.instance_history[start_index::interval]
            ]
            client_counts = [{
                'value': int(history['count']),
                'label': timeago.format(history['time'])
            } for history in ctx.history.client_history[start_index::interval]]
            server_counts = [{
                'value': int(history['count']),
                'label': timeago.format(history['time'])
            } for history in ctx.history.server_history[start_index::interval]]
            previous_zoom_point = 0 if start_index == total_entries else max(
                0, start_index - ceil(
                    (len(ctx.history.instance_history) - start_index)))
            next_zoom_point = start_index + ceil(
                (len(ctx.history.instance_history) - start_index) /
                zoom_increment_factor)

            graph.add('Client Count', client_counts)
            graph.add('Instance Count', instance_counts)
            return {
                'message':
                graph.render().replace("<title>Pygal</title>", ""),
                'instance_count':
                0 if len(instance_counts) is 0 else instance_counts[-1],
                'client_count':
                0 if len(client_counts) is 0 else client_counts[-1],
                'server_count':
                0 if len(server_counts) is 0 else server_counts[-1],
                'next_zoom_point':
                next_zoom_point,
                'previous_zoom_point':
                previous_zoom_point
            }, 200
        except Exception as e:
            return {'message': str(e)}, 500
Esempio n. 15
0
import os, sys, datetime, pygal
from pygal.style import Style
from pygal import Config

#define the chart settings
custom_style = Style(
    guide_stroke_dasharray='1,4',
    major_guide_stroke_dasharray='2,4',
    colors=('#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5',
            '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5',
            '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5',
            '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5', '#5B9BD5',
            '#5B9BD5'))

config = Config()
config.show_legend = False
config.show_x_lables = True
config.box_mode = 'tukey'
config.x_title = 'Hour'
config.y_title = 'GB'
config.x_labels = [
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
    21, 22, 23
]


def genBoxPlot(plotTitle, srcPath, svgName, plotStartDate):
    dirs = os.listdir(srcPath)

    dictHoursWeekday = {0:[],1:[],2:[],3:[],4:[],5:[],6:[],7:[],8:[],9:[],\
                   10:[],11:[],12:[],13:[],14:[],15:[],16:[],17:[],18:[],19:[],\
Esempio n. 16
0
def line():
    with open('us_exchange_extracted.json', 'r') as data_file:
        us_exchange_data = json.load(data_file)
    with open('bitcoin_prices.json', 'r') as data_file:
        bitcoin_data = json.load(data_file)
    with open('ethereum_prices.json', 'r') as data_file:
        ethereum_data = json.load(data_file)
    custom_style = Style(colors=('#6699ff', '#1cbc7c'),
                         background='#000000',
                         plot_background='#1a1a1a',
                         foreground='#ffffff',
                         foreground_subtle='#ffffff',
                         foreground_strong='#ffffff',
                         legend_font_size=10,
                         font_family='googlefont:Raleway',
                         major_label_font_size=7,
                         label_font_size=8)
    chart = pygal.Line(width=600,
                       height=300,
                       style=custom_style,
                       dots_size=0.8,
                       label_font_size=6,
                       x_title='Time',
                       y_title='Price',
                       x_labels_major_every=300,
                       y_labels_major_every=None,
                       x_label_rotation=20,
                       show_minor_x_labels=False)
    chart.title = 'Exchange rates of US Dollar'

    coin_chart = pygal.Line(width=600,
                            height=300,
                            style=custom_style,
                            dots_size=0.8,
                            label_font_size=10,
                            x_title='Time',
                            y_title='Price',
                            x_labels_major_every=200,
                            y_labels_major_every=None,
                            x_label_rotation=20,
                            show_minor_x_labels=False)
    coin_chart.title = 'Prices of coins'
    francs_list = []
    for x in us_exchange_data:
        temp = {'value': x['FRANCS/US$'], 'label': x['YEAR']}
        francs_list.append(temp)

    chart.add('Francs/USD', francs_list)

    singapore_list = []
    for x in us_exchange_data:
        temp = {'value': x['SINGAPORE/US$'], 'label': x['YEAR']}
        singapore_list.append(temp)

    chart.add('Singapore/USD', singapore_list)

    kroner_list = []
    for x in us_exchange_data:
        temp = {'value': x['KRONER/US$'], 'label': x['YEAR']}
        kroner_list.append(temp)

    chart.add('Kroner/USD', kroner_list)

    ethereum_list = []
    for x in ethereum_data:
        temp = {'value': x['Open'], 'label': x['Date']}
        ethereum_list.append(temp)

    ethereum_list.reverse()

    coin_chart.add('Ethereum', (ethereum_list))

    coin_chart.x_labels = [x['label'] for x in ethereum_list]

    bitcoin_list = []
    for x in bitcoin_data:
        temp = {'value': x['Open'], 'label': x['Date']}
        bitcoin_list.append(temp)

    bitcoin_list.reverse()

    coin_chart.add('Bitcoin', (bitcoin_list))

    chart.x_labels = [x['YEAR'] for x in us_exchange_data]

    coin_chart.render_to_file('static/images/coin_line_chart.svg')
    chart.render_to_file('static/images/line_chart.svg')
    img_url = 'static/images/line_chart.svg?cache=' + str(time.time())
    coin_url = 'static/images/coin_line_chart.svg?cache=' + str(time.time())
    return render_template('line_chart.html',
                           image_url=img_url,
                           coin_chart=coin_url)
Esempio n. 17
0
# -*- coding: utf-8 -*-
"""
Created on Mon Jan  4 12:52:20 2016

@author: Ronan
"""

import numpy, pygal
from pygal.style import Style

def sigmoid(x):
    return 1/(1+numpy.exp(-x))
    

# This script needs one object in the environment: le

data = numpy.load('train_data.npy')
freq = numpy.mean(data[:,:20], axis=0)
labels = le.inverse_transform(numpy.array(range(20)))

custom_style = Style(colors = ['#D0D0E0'])
custom_style.label_font_size = 17
custom_style.background = '#FFFFFF'
config = pygal.Config()
config.x_label_rotation = 30
hist = pygal.Bar(config, style = custom_style)
hist.add('cuisine', freq)
hist.x_labels = labels
hist.show_legend = False
hist.render_to_file('_histogram.svg')
Esempio n. 18
0
 def __init__(self):
     Style.__init__(self)
     self.background = 'transparent'
     self.plot_background = 'transparent'
     self.colors = ('#aaff00', '#550055')
     self.foreground_dark = '#010101'
Esempio n. 19
0
# -----------------------------------------------------------------------------
# group the countries into 3 population levels to have the colouring be more
# informative (otherwise it just shows China and India a contrastig colour).

cc_pop1, cc_pop2, cc_pop3 = {}, {}, {}
for cc, pop in cc_populations.items():
    if pop < 10000000:  # 10 million
        cc_pop1[cc] = pop
    elif pop < 1000000000:  # 1 billion
        cc_pop2[cc] = pop
    else:
        cc_pop3[cc] = pop

# see how many countries are in each group:
print(len(cc_pop1), len(cc_pop2), len(cc_pop3))

my_style = Style(legend_font_size=9, colors=('#509aff', '#01e7d4', '#ff6e67'))

wm = World(style=my_style)
wm.title = 'World Population in 2010'

# wm.add('North America',['ca', 'mx', 'us'])
# wm.add('North America',{'ca': 34126000, 'mx': 113423000, 'us': 309349000})
# wm.add('2010', cc_populations)

wm.add('0-10m', cc_pop1)
wm.add('10m-1b', cc_pop2)
wm.add('>1b', cc_pop3)

wm.render_to_file('americas.svg')
Esempio n. 20
0
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, RadioField
from wtforms.validators import DataRequired, Required
from wtforms.validators import InputRequired, ValidationError
from werkzeug.datastructures import MultiDict
import pickle
import pandas as pd
import numpy as np
import lime
import lime.lime_tabular
import pygal

from pygal.style import Style
custom_style = Style(
  background='transparent',
  plot_background='transparent',
  label_font_family='sans serif',
  )

app = Flask(__name__)
app.config.from_object(Config)
app.config["CACHE_TYPE"] = "null"
#feature list

feature = ["age","dependents","annual income","monthly loans","income stability","portfolio status","investment objective","duration","comfort","behaviour"]
#data for lime custom
file = open("user_risk_dtree.sav","rb")
dtree =  pickle.load(file)
df_riskcat = pd.read_csv("user_risk.csv")
df_riskcat.drop(columns=['output'],inplace=True)
X = df_riskcat.drop(columns=['categories'])
Esempio n. 21
0
def index():
    tasks = []
    api = tweepy.API(auth,
                     wait_on_rate_limit=True,
                     wait_on_rate_limit_notify=True)
    top_10 = twitter_trend(api, 10)
    if request.method == 'POST':
        tweet_query = request.form['content']
        tweet_number = int(request.form['number'])
        texts = []

        search_words = tweet_query
        new_search = search_words + " -filter:retweets"
        search = tweepy.Cursor(api.search,
                               q=new_search,
                               lang="th",
                               tweet_mode="extended").items(tweet_number)
        texts = [item.full_text for item in search]
        clean_list = text_cleaning(texts)
        #return clean_list[3]
        term_weighting = tfidf_model.transform(clean_list)

        # from pythainlp.tag import pos_tag_sents
        # pos = pos_tag_sents(word_list,corpus='orchid_ud')
        # keep_tag = ['VERB', 'ADJ', 'ADV', 'INTJ', 'AUX']
        # pos_list = []
        # for sent in pos:
        #     dt_tags = [t[0] for t in sent if t[1] in keep_tag]
        #     pos_list.append(dt_tags)

        # clean_list = delete_stop(word_list)
        # new = tfidf_model.transform(clean_list)
        new = term_weighting.toarray()
        new = [n[support] for n in new]

        pred = clf_model.predict(new)
        #pred = clean_list
        #return pred[1]
        neg_count = 0
        pos_count = 0
        my_list = []
        with open("dataset.csv", mode='w', newline='', encoding='utf-8') as f:
            thewriter = csv.writer(f)
            thewriter.writerow(["text", "sentiment"])
            for i in range(len(texts)):
                my_list.append([texts[i], pred[i]])
                if pred[i] == 1.0:
                    neg_count = neg_count + 1
                    thewriter.writerow(
                        [texts[i].replace('\n', ''), 'Negative'])
                else:
                    pos_count = pos_count + 1
                    thewriter.writerow(
                        [texts[i].replace('\n', ''), 'Positive'])
        custom_style = Style(colors=('#800000', '#3CB371'))
        pie_chart = pygal.Pie(style=custom_style)
        pie_chart.title = 'Sentiment ratio'
        pie_chart.add('Negative', neg_count)
        pie_chart.add('Positive', pos_count)

        chart_data = pie_chart.render_data_uri()

        #return str(len(top_10))
        return render_template('index.html',
                               tasks=my_list,
                               trends=top_10,
                               keyword=tweet_query,
                               chart=chart_data)

    else:

        #tasks = Todo.query.order_by(Todo.date_created).all()
        top_10 = twitter_trend(api, 10)
        #return top_10[0]
        return render_template('index.html', tasks=[], trends=top_10)
Esempio n. 22
0
from ominicontacto_app.utiles import datetime_hora_maxima_dia, datetime_hora_minima_dia
from ominicontacto_app.models import CalificacionCliente, Campana
from reportes_app.actividad_agente_log import AgenteTiemposReporte
from reportes_app.models import LlamadaLog, ActividadAgenteLog

from utiles_globales import obtener_cantidad_no_calificados

logger = _logging.getLogger(__name__)


ESTILO_AZUL_ROJO_AMARILLO = Style(
    background='transparent',
    plot_background='transparent',
    foreground='#555',
    foreground_light='#555',
    foreground_dark='#555',
    opacity='1',
    opacity_hover='.6',
    transition='400ms ease-in',
    colors=('#428bca', '#5cb85c', '#5bc0de', '#f0ad4e', '#d9534f',
            '#a95cb8', '#5cb8b5', '#caca43', '#96ac43', '#ca43ca')
)


class EstadisticasAgenteService():

    def _obtener_cantidad_no_calificados_agente(self, campana, fecha_desde, fecha_hasta,
                                                total_calificados, agente):
        """
        Devuelve la cantidad de llamadas recibidas por agentes pero no calificadas por estos
        """
        """
from datetime import datetime, timedelta, date
import pygal
import os
from pygal.style import Style
custom_style = Style(
    colors=['#4CAF50'])


def getDateTime(s):
    year = int(s[0:4])
    month = int(s[5:7])
    day = int(s[8:10])
    print(year, type(year), month, type(month), day, type(day))
    return datetime(year, month, day)


def pricesGraph(candles):
    date_chart = pygal.Line(fill=False, x_label_rotation=20, show_legend=False, style=custom_style)
    date_chart.title = '10-Day Price Graph (USD)'

    count = 0
    closings = []
    dates = []

    for row in candles[-11:-1]:
        dates.append(getDateTime(row['timestamp'][0:10]))
        closings.append(float(row['close']))
        count += 1
        if count == 10:
            break
Esempio n. 24
0
from sqlalchemy import extract  
import pygal                                                        
from pygal.style import Style
 
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz


 

custom_style = Style(
  background='transparent',
  plot_background='transparent',
  foreground='#ffff',
  foreground_strong='#fff',
  foreground_subtle='#fffa',
  opacity='.6',
  opacity_hover='.9',
  transition='400ms ease-in',
  value_colors = '#fff'
#   colors=('#E853A0', '#E8537A', '#E95355', '#E87653', '#E89B53'))
)



@app.before_first_request
def setup():

   db.create_all()
   db.session.commit()

   User.query.filter(User.username == "Admin").delete()
Esempio n. 25
0
datafile = 'API_EN/API_EN.ATM.CO2E.KT_DS2_en_csv_v2.csv'
emissions = {}
no_data = {}
try:
    with open(datafile) as csvfile:
        file = csv.reader(csvfile)
        for _ in range(5):
            next(file)
        for line in file:
            country = line[0]
            if country in country_mapping:
                country = country_mapping[country]
            code = country_code(country)
            if code:
                emission = line[-6]
                if emission:
                    emissions[code] = float(emission)
                else:
                    no_data[code] = '?'
            else:
                print(f'Leaving out {country}')
except FileNotFoundError:
    print(f'Could not open {datafile}, giving up.')
    sys.exit()
emissions_map = World(style=Style(
    colors=('#B22222', '#A9A9A9'), tooltip_font_size=8, legend_font_size=10))
emissions_map.title = 'CO2 emissions in 2011'
emissions_map.add('Known data', emissions)
emissions_map.add('No data', no_data)
emissions_map.render_to_file('CO2_emissions.svg')
Esempio n. 26
0
def index():
    user_id = session.get('user_id')
    form = login_form.LoginForm()
    db = GraficoModel()
    now = datetime.now()
    ano = now.strftime('%Y')
    mes = now.strftime('%m')

    este_mes = db.get_levyings_sum(mes)
    if este_mes[0]:
        este_mes2 = este_mes[0]
        este_mes = real_br_money_mask(este_mes[0])
    else:
        este_mes = '0'
        este_mes2 = 0.0

    if mes != 1:
        mes = str(int(mes) - 1)
        ultimo_mes = db.get_levyings_sum(mes)
        if ultimo_mes[0]:
            ultimo_mes2 = ultimo_mes[0]
            ultimo_mes = real_br_money_mask(ultimo_mes[0])
        else:
            ultimo_mes = '0'
            ultimo_mes2 = 0.0

    else:
        ultimo_mes = db.get_levyings_sum(mes)
        ultimo_mes = real_br_money_mask(ultimo_mes[0])
        ultimo_mes2 = ultimo_mes[0]

    if este_mes2 > ultimo_mes2:
        text_info = "text-info"
        text_primary = "text-primary"
    else:
        text_info = "text-primary"
        text_primary = "text-info"

    result = db.get_numero_empresas(user_id)
    numero_clientes = result[0]
    if not numero_clientes:
        numero_clientes = "0"

    total_clientes = result[1]
    porcentagem = int(ceil((numero_clientes * 100) / total_clientes))
    porcentagem = porcentagem - (porcentagem % 10)

    result = db.get_tributacao('SIMPLES NACIONAL', 'PRESUMIDO', 'REAL',
                               user_id)
    chart = pygal.Pie(style=CleanStyle)
    chart.force_uri_protocol = 'http'
    chart.title = 'Faturamento por Cliente'
    chart.add('Simples Nacional', result[0])
    chart.add('Lucro Presumido', result[1])
    chart.add('Lucro Real', result[2])
    graph_data = chart.render_data_uri()

    result = db.get_ocorrencias(user_id)
    custom_style = Style(colors=('#9e0808', '#041e70', '#04753c'))
    chart = pygal.Bar(style=custom_style)
    chart.force_uri_protocol = 'http'
    chart.title = 'Ocorrências em Aberto / Fechado / Andamento'
    chart.add('Aberto', result[0])
    chart.add('Andamento', result[2])
    chart.add('Fechado', result[1])
    graph_data2 = chart.render_data_uri()

    result1 = db.get_cobrancas('Continuo')
    result2 = db.get_cobrancas('Nao_Continuo')
    chart = pygal.Bar(style=CleanStyle)
    chart.force_uri_protocol = 'http'
    chart.title = 'Cobranças, ano ' + str(ano) + ':'
    chart.x_labels = ('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago',
                      'Set', 'Out', 'Nov', 'Dez')
    chart.add('Contínuo', result1)
    chart.add('Não Contínuo', result2)
    graph_data3 = chart.render_data_uri()

    return render_template('index/index.html',
                           form=form,
                           graph_data=graph_data,
                           graph_data2=graph_data2,
                           graph_data3=graph_data3,
                           total_clientes=total_clientes,
                           numero_clientes=numero_clientes,
                           porcentagem=porcentagem,
                           este_mes=este_mes,
                           ultimo_mes=ultimo_mes,
                           flag_index=1,
                           text_info=text_info,
                           text_primary=text_primary)
Esempio n. 27
0
from pygal.style import Style

hsvgpath = "../view/history/"

h = history.History("../data/history.dat")

custom_style = Style(
    background='white',
    plot_background='rgba(255, 255, 255, 0.1)',
    foreground='rgba(0, 0, 0, 0.5)',
    foreground_light='rgba(0, 0, 0, 0.7)',
    foreground_dark='rgba(0, 0, 0, 0.3)',
    colors=('rgb(163, 190, 140)',
            'rgb(123, 163, 168)',
            'rgb(130, 192, 175)',
            'rgb(159, 224, 246)',
            'rgb(0, 146, 199)',
            'rgb(91, 144, 191)',
            'rgb(40, 81, 113)',
            'rgb(190, 173, 146)',
            'rgb(243, 90, 74)',
            'rgb(91, 73, 71)',
            'rgb(218, 145, 122)',
            'rgb(242, 156, 156)')
)

line = pygal.Line(
    width=800, height=400, interpolate='hermite', style=custom_style)
line.title = u'每月种子下载平均量统计'
line.x_labels = [u'1月', u'2月', u'3月', u'4月', u'5月',
                 u'6月', u'7月', u'8月', u'9月', u'10月', u'11月', u'12月']
Esempio n. 28
0
def article(DOI):
    import pygal
    from pygal.style import Style
    from py2neo import Graph, Node, Relationship

    graph = Graph("http://localhost:7474", auth=("neo4j", ""))
    #Overall
    query = """
    MATCH (article{DOI:'%s'})-[*]->(section:`STROBE-nut section`)-[*]->(n:`STROBE-nut item`)
    return count(n.name)
    """ % (DOI)
    dataset = graph.run(query).data()
    if dataset == []:
        Overall = 0
    else:
        Overall = 0.5 * (dataset[0]['count(n.name)']) / 24 * 100

    #Title/Abstract
    query = """
    MATCH (article{DOI:'%s'})-[*]->(section:`STROBE-nut section`{name:'Title/Abstract'})-[*]->(n:`STROBE-nut item`)
    return section.name, count(n.name)
    """ % (DOI)
    dataset = graph.run(query).data()
    if dataset == []:
        Title = 0
    else:
        Title = 0.5 * (dataset[0]['count(n.name)']) * 100

    #Methods
    query = """
    MATCH (article{DOI:'%s'})-[*]->(section:`STROBE-nut section`{name:'Methods'})-[*]->(n:`STROBE-nut item`)
    return section.name, count(n.name)
    """ % (DOI)
    dataset = graph.run(query).data()
    if dataset == []:
        Methods = 0
    else:
        Methods = 0.5 * (dataset[0]['count(n.name)']) / 15 * 100

    #Results
    query = """
    MATCH (article{DOI:'%s'})-[*]->(section:`STROBE-nut section`{name:'Results'})-[*]->(n:`STROBE-nut item`)
    return section.name, count(n.name)
    """ % (DOI)
    dataset = graph.run(query).data()
    if dataset == []:
        Results = 0
    else:
        Results = 0.5 * (dataset[0]['count(n.name)']) / 4 * 100

    #Discussion
    query = """
    MATCH (article{DOI:'%s'})-[*]->(section:`STROBE-nut section`{name:'Discussion'})-[*]->(n:`STROBE-nut item`)
    return section.name, count(n.name)
    """ % (DOI)
    dataset = graph.run(query).data()
    if dataset == []:
        Discussion = 0
    else:
        Discussion = 0.5 * (dataset[0]['count(n.name)']) / 2 * 100

    #Other information
    query = """
    MATCH (article{DOI:'%s'})-[*]->(section:`STROBE-nut section`{name:'Other information'})-[*]->(n:`STROBE-nut item`)
    return section.name, count(n.name)
    """ % (DOI)
    dataset = graph.run(query).data()
    if dataset == []:
        info = 0
    else:
        info = 0.5 * (dataset[0]['count(n.name)']) / 2 * 100

    custom_style = Style(value_label_font_size=50, label_font_size=20)
    radar_chart = pygal.Radar(style=custom_style)
    radar_chart.title = 'Reporting completeness of article (in %)'
    radar_chart.x_labels = [
        'Overall', 'Title/Abstract', 'Methods', 'Results', 'Discussion',
        'Other information'
    ]
    radar_chart.add('STROBE-nut', [100, 100, 100, 100, 100, 100],
                    show_dots=False)
    radar_chart.add(DOI, [Overall, Title, Methods, Results, Discussion, info],
                    fill=True)
    #radar_chart.render_in_browser()
    radar_chart.render_to_png('/Users/chenyang/Desktop/strobenut.png')
Esempio n. 29
0
def scatter():
    with open('bitcoin_prices.json', 'r') as data_file:
        bitcoin_data = json.load(data_file)
    with open('ethereum_prices.json', 'r') as data_file:
        ethereum_data = json.load(data_file)
    with open('litecoin_prices.json', 'r') as data_file:
        litecoin_data = json.load(data_file)
    with open('monero_prices.json', 'r') as data_file:
        monero_data = json.load(data_file)
    with open('dash_prices.json', 'r') as data_file:
        dash_data = json.load(data_file)
    with open('iota_prices.json', 'r') as data_file:
        iota_data = json.load(data_file)
    with open('nem_prices.json', 'r') as data_file:
        nem_data = json.load(data_file)
    with open('omisego_prices.json', 'r') as data_file:
        omisego_data = json.load(data_file)
    with open('qtum_prices.json', 'r') as data_file:
        qtum_data = json.load(data_file)
    with open('stratis_prices.json', 'r') as data_file:
        stratis_data = json.load(data_file)
    with open('waves_prices.json', 'r') as data_file:
        waves_data = json.load(data_file)

    custom_style = Style(colors=('#E853A0', '#E8537A', '#E95355', '#E87653',
                                 '#E89B53'),
                         background='#000000',
                         plot_background='#1a1a1a',
                         foreground='#ffffff',
                         foreground_subtle='#ffffff',
                         foreground_strong='#ffffff',
                         legend_font_size=10,
                         font_family='googlefont:Raleway',
                         major_label_font_size=7,
                         label_font_size=8)
    chart = pygal.Line(width=600,
                       height=300,
                       style=custom_style,
                       dots_size=0.2,
                       label_font_size=6,
                       x_title='Time',
                       y_title='Price',
                       y_labels_major_every=None,
                       x_label_rotation=20,
                       show_minor_x_labels=False,
                       stroke=False)
    chart.title = 'Comparison of lesser known coins'
    bitcoin_list = []
    for x in bitcoin_data:
        temp = {'value': x['Open'] / 100, 'label': x['Date']}
        bitcoin_list.append(temp)
    bitcoin_list.reverse()
    chart.add('Bitcoin/100', bitcoin_list)

    nem_list = [x['Open'] for x in nem_data]
    # nem_list = []
    # for x in nem_data:
    #     temp = {
    #     'value': x['Open'],
    #     'label': x['Date']
    #     }
    nem_list.reverse()
    chart.add('Nem', nem_list)

    stratis_list = [x['Open'] for x in stratis_data]
    # stratis_list = []
    # for x in stratis_data:
    #     temp = {
    #     'value': x['Open'],
    #     'label': x['Date']
    #     }
    stratis_list.reverse()
    chart.add('Stratis', stratis_list)

    waves_list = [x['Open'] for x in waves_data]
    # waves_list = []
    # for x in waves_data:
    #     temp = {
    #     'value': x['Open'],
    #     'label': x['Date']
    #     }
    waves_list.reverse()
    chart.add('Waves', waves_list)

    iota_list = [x['Open'] for x in iota_data]
    # iota_list = []
    # for x in iota_data:
    #     temp = {
    #     'value': x['Open'],
    #     'label': x['Date']
    #     }
    iota_list.reverse()
    chart.add('Iota', iota_list)

    label_list = []
    for x in nem_data:
        temp = {'value': x['Open'], 'label': x['Date']}
        label_list.append(temp)

    label_list.reverse()
    chart.x_labels = [x['label'] for x in label_list]

    chart.render_to_file('static/images/scatter_chart.svg')
    img_url = 'static/images/scatter_chart.svg?cache=' + str(time.time())
    return render_template('template.html', image_url=img_url)
Esempio n. 30
0
from tempfile import NamedTemporaryFile

try:
    import cairosvg
    from pygal import Config, Pie
    from pygal.style import Style
    IMPORTS = True
except ImportError:
    IMPORTS = False

from bundlewrap.utils import LOG

if IMPORTS:
    STYLE = Style(
        background='transparent',
        opacity=1,
        plot_background='transparent',
        colors=('#00ae19', '#25ff44', '#ffde00', '#c90000'),
    )

def node_apply_end(repo, node, duration=None, interactive=None, result=None, **kwargs):
    if environ.get('TERM_PROGRAM', None) != "iTerm.app" or not interactive:
        LOG.debug("skipping iTerm stats (wrong terminal)")
        return

    if not IMPORTS:
        LOG.error("failed to import dependencies of itermstats plugin")
        return

    css_file = NamedTemporaryFile(delete=False)
    css_file.write(".text-overlay { display: none; }")
    css_file.close()
Esempio n. 31
0
def StackedLine():
    with open('us_exchange_extracted.json', 'r') as data_file:
        us_exchange_data = json.load(data_file)
    with open('bitcoin_prices.json', 'r') as data_file:
        bitcoin_data = json.load(data_file)
    with open('ethereum_prices_extracted.json', 'r') as data_file:
        ethereum_data = json.load(data_file)

    custom_style = Style(colors=('#E853A0', '#E8537A', '#E95355', '#E87653',
                                 '#E89B53'),
                         background='#000000',
                         plot_background='#1a1a1a',
                         foreground='#ffffff',
                         foreground_subtle='#ffffff',
                         foreground_strong='#ffffff',
                         legend_font_size=10,
                         font_family='googlefont:Raleway',
                         major_label_font_size=7,
                         label_font_size=8,
                         title_font_size=12,
                         opacity='.6',
                         opacity_hover='.9',
                         transition='100ms ease-in')

    chart = pygal.StackedLine(width=600,
                              height=300,
                              fill=True,
                              interpolate='cubic',
                              style=custom_style,
                              show_dots=False,
                              x_title='Time',
                              y_title='Price')
    chart.title = 'Nominal Broad Dollar Index Comparison'
    nominal_list = []
    for x in us_exchange_data:
        y = x['Nominal Broad Dollar Index']
        if (y != None):
            y = y * 10
        temp = {'value': y, 'label': x['YEAR']}
        nominal_list.append(temp)

    chart.add('Nominal Broad Dollar Index', nominal_list)

    #print(resample.size, file=sys.stderr)

    bitcoin_list = []
    for x in bitcoin_data:
        temp = {'value': x['Open'], 'label': x['Date']}
        bitcoin_list.append(temp)
    bitcoin_list.reverse()
    chart.add('Bitcoin', bitcoin_list)

    ethereum_list = []
    for x in ethereum_data:
        temp = {'value': x['Open'], 'label': x['Date']}
        ethereum_list.append(temp)
    ethereum_list.reverse()
    chart.add('Ethereum', (ethereum_list))

    chart.render_to_file('static/images/stacked_line_chart.svg')
    img_url = 'static/images/stacked_line_chart.svg?cache=' + str(time.time())
    return render_template('template.html', image_url=img_url)
Esempio n. 32
0
""" StackBehavior - User World Map
This module visualize user count by country into world map using pygal library
"""
import pygal
import csv
from pygal.style import Style

custom_style = Style(colors=('#F6D18B', '#F0AE58', '#EF8823', '#EB7A3E',
                             '#F05328', '#C24320'))

# source, output = './dataset/data/user_location_min.csv', './visualize/output/user_world_map.svg'
source, output = './dataset/data/reputation_min.csv', './visualize/output/user_rep_world_map.svg'


def read(stt, stp=0):
    """ Convert data from an csv file into dict """
    data_dict = {}
    with open(source, encoding="utf8") as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        for row in readCSV:
            if stt <= int(row[1]) <= stp or (int(row[1]) >= stt and not stp):
                # data_dict[row[0]] = int(row[1])
                data_dict[row[0]] = 1
    return data_dict


def visualize_user():
    worldmap_chart = pygal.maps.world.World(style=custom_style)
    worldmap_chart.title = 'Numbers of StackOverflow users by country'
    worldmap_chart.add('1 - 10000', read(1, 10000))
    worldmap_chart.add('10001 - 40000', read(10001, 40000))
Esempio n. 33
0
from wtforms import Form, BooleanField, StringField, PasswordField, validators, SelectField, IntegerField
from flask import Flask, Blueprint, render_template, request, session, make_response

from grinlib import lib

home_profile = Blueprint('home_profile',
                         __name__,
                         template_folder='templates',
                         static_folder='static')

# Grin Network Graph Style
grin_style_pygal = Style(background='transparent',
                         plot_background='transparent',
                         foreground='#53E89B',
                         foreground_strong='#02e205',
                         foreground_subtle='#274427',
                         opacity='.6',
                         opacity_hover='.9',
                         transition='400ms ease-in',
                         colors=('#C0C0C0', '#E8537A', '#E95355', '#E87653',
                                 '#E89B53'))

# Pool Graph Style
pool_style_pygal = Style(
    background='transparent',
    plot_background='transparent',
    foreground='#8c8c8c',
    foreground_strong='#fffcfc',
    foreground_subtle='#2d2d2d',
    opacity='.6',
    opacity_hover='.9',
    transition='400ms ease-in',
Esempio n. 34
0
def home():
    custom_style = Style(colors=('#351508', '#404040', '#9BC850'))
    title = 'Screen ID analysis'
    bar_chart = pygal.Bar(width=400,
                          height=400,
                          explicit_size=True,
                          title=title,
                          style=custom_style)
    var_x_labels = []
    var_data = []
    #    print ("__xlabels__",var_x_labels)

    for idx1 in list(range(0, len(data_time_spent))):
        var_x_labels.append(idx1 + 1)
        var_data.append(data_time_spent.Time[idx1])
#        print(data_time_spent.Time[idx1])

    bar_chart.x_labels = var_x_labels
    #    bar_chart.y_labels = var_y_labels
    #    var_time_spent = [data_time_spent[x] for x in data_time_spent]
    #    print ("_Time spent_",var_time_spent)
    #    print ("_Time spent_0___",var_time_spent[0])
    #    print ("_Time spent_1___",var_time_spent[1])
    var_time_spent = var_data
    #    print ("==bar chart==",var_time_spent)
    bar_chart.add('Avg active session', var_time_spent)
    bar_chart.render_to_file('static/images/bar_chart.svg')

    ###################################
    title2 = 'Avg time spent on each screen'
    custom_style = Style(colors=('#059467', '#9BC850', '#E80080'))
    avg_bar_chart = pygal.Bar(width=1200,
                              height=800,
                              explicit_size=True,
                              title=title2,
                              x_label_rotation=90,
                              style=custom_style)
    var_x_labels = []
    var_data = []
    #    print ("__xlabels__",var_x_labels)
    #    print ("avg time spent===",avg_time_spent)
    for idx1 in list(range(0, len(avg_time_spent))):
        var_x_labels.append(avg_time_spent.Screen_id[idx1])
        var_data.append(avg_time_spent.Avg_Time[idx1])
#        print(avg_time_spent.Avg_Time[idx1])

    avg_bar_chart.x_labels = var_x_labels
    #    bar_chart.y_labels = var_y_labels
    #    var_time_spent = [data_time_spent[x] for x in data_time_spent]
    #    print ("_Time spent_",var_time_spent)
    #    print ("_Time spent_0___",var_time_spent[0])
    #    print ("_Time spent_1___",var_time_spent[1])
    var_time_spent = var_data
    avg_bar_chart.add('Avg time sec', var_data)
    avg_bar_chart.render_to_file('static/images/screen_avg_chart.svg')

    ###################################
    title2 = 'Least used screens'
    custom_style = Style(colors=('#1878f7', '#404040', '#E80080'))
    avg_bar_chart = pygal.Bar(width=1200,
                              height=600,
                              explicit_size=True,
                              title=title2,
                              x_label_rotation=90,
                              style=custom_style)
    var_x_labels = []
    var_data = []
    #    print ("__xlabels__",var_x_labels)

    for idx1 in list(range(0, len(data_tf_idf))):
        var_x_labels.append(data_tf_idf.GUI[idx1])
        var_data.append(data_tf_idf.Priority[idx1])
#        print(avg_time_spent.Avg_Time[idx1])

    avg_bar_chart.x_labels = var_x_labels
    #    bar_chart.y_labels = var_y_labels
    #    var_time_spent = [data_tf_idf[x] for x in data_tf_idf]
    #    print ("_Time spent_",var_time_spent)
    #    print ("_Time spent_0___",var_time_spent[0])
    #    print ("_Time spent_1___",var_time_spent[1])
    var_time_spent = var_data
    avg_bar_chart.add('Least used screen', var_time_spent)
    avg_bar_chart.render_to_file('static/images/tf_idf_chart.svg')

    #====================Donut chart of the screens used==================
    print("===Dounut Chart==========")
    pie_chart = pygal.Pie(width=1200,
                          height=600,
                          explicit_size=True,
                          inner_radius=.2)
    pie_chart.title = 'Time spent on each screen (in %)'
    var_x_labels = []
    var_data = []
    total_values = 0
    for idx1 in list(range(0, len(avg_time_spent))):
        total_values = total_values + avg_time_spent.Avg_Time[idx1]

#    print ("Total value===",total_values)
    for idx1 in list(range(0, len(avg_time_spent))):
        prcnt = round((avg_time_spent.Avg_Time[idx1] / total_values) * 100, 2)
        #        print ("% = ",prcnt)
        pie_chart.add(avg_time_spent.Screen_id[idx1], prcnt)

    pie_chart.render_to_file('static/images/donut.svg')

    #==================================Gauge chart==========
    gauge = pygal.SolidGauge(inner_radius=0.70)
    percent_formatter = lambda x: '{:.10g}%'.format(x)
    gauge.value_formatter = percent_formatter

    #====scatter plot=====================================

    xy_chart = pygal.XY(width=1200,
                        height=600,
                        explicit_size=True,
                        stroke=False)
    xy_chart.title = 'Scatter plot of the screen ID and time spent'
    #    var_temp_lst = []
    var_screen_id_dict = defaultdict(list)

    for idx in list(range(0, len(avg_time_spent))):
        #        var_screen_id_dict[avg_time_spent.Screen_id[idx]]={}
        print(idx, "=>", avg_time_spent.Screen_id[idx])
        for idx2 in list(range(0, len(var_full_data))):
            if (avg_time_spent.Screen_id[idx] == var_full_data.ScreenName[idx2]
                ):
                #                print (idx2,"count=",var_full_data.ScreenName[idx2])
                if (idx2 + 1 >= len(var_full_data)):
                    continue
                else:
                    var_screen_id_dict[avg_time_spent.Screen_id[idx]].append(
                        var_full_data.ScreenName[idx2 + 1])
#                    print("screneid =",avg_time_spent.Screen_id[idx],"next id=",var_full_data.ScreenName[idx2+1])

    print("The next screen list stored==========")
    print(var_screen_id_dict)

    #        var_x_labels.append(var_full_data.ScreenName[idx1])
    #        var_data.append(data_tf_idf.ActiveTime[idx1])
    #    print ("===values==",var_data)
    #    xy_chart.add('ScreenIds', var_data)
    xy_chart.add('2', [(.1, .15), (.12, .23), (.4, .3), (.6, .4), (.21, .21),
                       (.5, .3), (.6, .8), (.7, .8)])
    xy_chart.add('3', [(.05, .01), (.13, .02), (1.5, 1.7), (1.52, 1.6),
                       (1.8, 1.63), (1.5, 1.82), (1.7, 1.23), (2.1, 2.23),
                       (2.3, 1.98)])
    xy_chart.render_to_file('static/images/scatter.svg')

    #======================================

    my_html = create_html_page()

    #    print ("==========================")
    #    print (my_html)
    #    print ("==========================")
    return my_html