Ejemplo n.º 1
0
        'value': response_dict.get('descendants', 0),
        'label': response_dict['title'],
        'xlink': 'http://news.ycombinator.com/item?id=' + str(submission_id),
    }
    graph_list.append(submission_dict)
    names.append(response_dict['title'])

graph_list = sorted(graph_list, key=itemgetter('value'), reverse=True)

my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000

chart = pygal.Bar(my_config, x_label_rotation=45, show_legend=False)
chart.title = 'Most active disscusions on Hacker News'
chart.x_labels = names
chart.add('', graph_list)
chart.render_to_file('Desktop/Coding_Projects/Working_With_APIs/hn_visual.svg')
print('A popularity graph for the language has been made')

#Here we use requests again, this time calling Hacker News
#The first call returns the 500 most popular articles on the website
#we then loop through 30 of the most popular of those, creating a nice index of-
#- popular articles
Ejemplo n.º 2
0
def success(data, test=False):
    """ Main generate function get data and weapon id = 0 (Overall) """
    # Graph generate goes here!
    # Export file name as Targets_Frequency_SuccessRate

    targets = {
        1: "Business",
        2: "Government (General)",
        3: "Police",
        4: "Military",
        5: "Abortion Related",
        6: "Airports & Aircraft",
        7: "Government (Diplomatic)",
        8: "Educational Institution",
        9: "Food or Water Supply",
        10: "Journalists & Media",
        11: "Maritime",
        12: "NGO",
        13: "Other",
        14: "Private Citizen & Property",
        15: "Religious",
        16: "Telecommunication",
        17: "Terrorists/Non-State Militias",
        18: "Tourists",
        19: "Transportation",
        20: "Unknown",
        21: "Utilities",
        22: "Violent Political Parties"
    }
    result_x = [targets[x] for x in sorted(targets)]
    result_y = []

    for x in sorted(targets):
        if len(data[data['targtype1'] == x]) == 0:
            freq = 0
        else:
            freq = len(
                data[(data['targtype1'] == x) & (data['success'] == 1)]) / len(
                    data[data['targtype1'] == x])
        result_y.append(freq)

    chart = pygal.Bar(show_minor_x_labels=False,
                      truncate_legend=40,
                      truncate_label=20,
                      x_label_rotation=90,
                      y_labels_major_every=3,
                      show_minor_y_labels=False,
                      value_formatter=lambda x: "%d%%" % x)

    chart.x_labels = []

    chart.title = 'Overall success rate by targets from 1970 to 2016 except 1993'

    for x in range(22):
        if result_y[x] == 0:
            continue
        chart.add(
            result_x[x] + " (" + str("%.3f" % (result_y[x] * 100)) + "%)",
            round(result_y[x] * 100, 3))

    chart.render_to_file('Charts/Targets_Frequency_SuccessRate.svg')

    # End of modules and return back to main
    if test:
        return
    print("\nGraph generated!")
    targets_main.main(data)
Ejemplo n.º 3
0
#print("Repositories returned:",len(repo_dicts))

#可视化
my_style = LS('#333366', base_style=LCS)

my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000

chart = pygal.Bar(style=my_style, config=my_config)  #x_label必须斜着
chart.title = 'Most-starred Python Projects on Github'
chart.x_labels = names

chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')

#研究第一个仓库
repo_dict = repo_dicts[0]
print("\nKeys:", len(repo_dict))
for key in sorted(repo_dict.keys()):
    print(key)

print("\nSelected information about each repository:")
for repo_dict in repo_dicts:
    print('Name:', repo_dict['name'])
Ejemplo n.º 4
0
        100 * together / individually
    ))

absolute_graph = pygal.Line(x_label_rotation = 20)
absolute_graph.title = 'Projects with features by date'
absolute_graph.x_labels = [format_time(bucket['start']) for bucket in time_buckets]
absolute_graph.add('Totals', [bucket['count'] for bucket in time_buckets])
for feature in features.items():
    absolute_graph.add(
        feature[1]['description'], 
        [bucket['feature_count'][feature[0]] for bucket in time_buckets]
    )
absolute_graph.render_to_file('features_absolute.svg')

percent_graph = pygal.Line(x_label_rotation = 20)
percent_graph.title = 'Projects with features by date (in %)'
percent_graph.x_labels = [format_time(bucket['start']) for bucket in time_buckets]
for feature in features.items():
    percent_graph.add(
        feature[1]['description'], 
        [(int(100 * (bucket['feature_count'][feature[0]] / bucket['count'])) if bucket['count'] > 0 else None) for bucket in time_buckets]
    )
percent_graph.render_to_file('features_percent.svg')

feature_histogram = pygal.Bar()
feature_histogram.title = 'Histogram of features per project'
feature_histogram.x_labels = map(str, range(6))
feature_histogram.add('Feature count', feature_counts)
feature_histogram.render_to_file('feature_histogram.svg')

Ejemplo n.º 5
0
def earthEngine(poi, outputLocation):
    ee.Initialize()

    #Change projection to WGS1984
    wgs = arcpy.SpatialReference(4326)
    arcpy.Project_management(
        poi, os.path.join(arcpy.env.scratchFolder, "POI_layer_wgs.shp"), wgs)
    poi_reproj = os.path.join(arcpy.env.scratchFolder, "POI_layer_wgs.shp")

    #Create GEE object for point of interest
    desc = arcpy.Describe(poi_reproj)
    xmin = desc.extent.XMin
    ymin = desc.extent.YMin
    poiObject = ee.Geometry.Point([xmin, ymin])

    #The CHIRPS data only spans from 50 degrees S to 50 degrees N,
    #so exit earthEngine function if POI is placed outside of range
    if ymin > 49.999 or ymin < -49.999:
        arcpy.AddMessage(
            "Point was placed outside geographic range of CHIRPS rainfall data (50 degrees South-50 degrees North). Pick a point between 50 deg S and 50 deg N to return rainfall information."
        )
        return None

    #CHIRPS image collection
    chirps = ee.ImageCollection('UCSB-CHG/CHIRPS/DAILY')

    #Set the time period over which images will be captured.
    #Only rainfall from the past year will be reported.
    now = datetime.datetime.now()
    endYr = now.year
    endMo = now.month
    endDy = now.day
    stYr = endYr - 1
    stMo = endMo
    stDy = endDy
    #Create variables that will be used to iterate through each day of the year
    years = range(stYr, endYr + 1)
    endMoRange = endMo + 13
    months = range(endMo, endMoRange)
    #Set date in EE format
    startdate = ee.Date.fromYMD(stYr, stMo, 1)
    enddate = ee.Date.fromYMD(endYr, endMo, 1)
    #Filter CHIRPS by day
    Pchirps = chirps.filterDate(
        startdate, enddate).sort('system:time_start').select('precipitation')

    #Method to calculate monthly precipitation sum
    def calcMonthlySum(imageCollection):
        mylist = ee.List([])
        for m in months:
            if m <= 12:
                mo = m
                yr = years[0]
                w = imageCollection.filter(
                    ee.Filter.calendarRange(yr, yr, 'year')).filter(
                        ee.Filter.calendarRange(mo, mo, 'month')).sum()
                mylist = mylist.add(
                    w.set('system:time_start',
                          str(mo) + '/' + str(yr)))
            else:
                mo = m - 12
                yr = years[1]
                w = imageCollection.filter(
                    ee.Filter.calendarRange(yr, yr, 'year')).filter(
                        ee.Filter.calendarRange(mo, mo, 'month')).sum()
                mylist = mylist.add(
                    w.set('system:time_start',
                          str(mo) + '/' + str(yr)))
        return ee.ImageCollection.fromImages(mylist)

    #Call function to calculate monthly rainfall
    monthlyChirps = ee.ImageCollection(calcMonthlySum(Pchirps))

    #Limit output to the point of interest
    monthlyChirps2 = monthlyChirps.getRegion(poiObject, 24000,
                                             "epsg:4326").getInfo()

    #Create pandas dataframe to plot
    df = pd.DataFrame(monthlyChirps2, columns=monthlyChirps2[0])
    df2 = df[1:]
    df2[['id']] = df2[['id']].apply(pd.to_numeric)
    collapseDF = df2.groupby('id').agg({
        'precipitation': np.sum,
        'time': 'first'
    })

    #Plot the Precipitation Series from the dataframe
    precipSeries = collapseDF["precipitation"]
    blue = pygal.style.Style(colors=('blue', ))
    bar_chart = pygal.Bar(title=u"Monthly Precipitation",
                          x_title="Date",
                          y_title="Millimeters",
                          style=blue)

    bar_chart.add("Precipitation", precipSeries)

    timeSeries = collapseDF["time"]
    timeList = timeSeries.tolist()
    bar_chart.x_labels = timeList

    bar_chart.render_to_file(os.path.join(outputLocation, 'Rainfall.svg'))
 def __init__(self, database):
     self.chart = pygal.Bar()
     self.db = database
Ejemplo n.º 7
0
#Import modules
Ejemplo n.º 8
0
custom_style = Style(background='transparent',
                     plot_background='#ffffff',
                     foreground='#1b1b1b',
                     foreground_strong='#1b1b1b',
                     foreground_subtle='#1b1b1b',
                     opacity='.4',
                     opacity_hover='.6',
                     colors=('#1b1b1b', '#733380', '#22ff33'))

iterations = 1000
rw = RandomWalk(iterations)
rw.fill_walk()

# Visualize data with pygals's bar chart
hist = pygal.Bar(fill=True,
                 interpolate='cubic',
                 style=custom_style,
                 max_scale=100)

hist.title = f'Visualization of {str(iterations)} random movement iterations.'
hist.x_title = 'Iterations'
hist.y_title = 'Distance'

hist.x_labels = [
    label if label % 500 == 0 else '' for label in range(iterations + 1)
]

hist.add('X-Distance', rw.x_values)
hist.add('Y-Distance', rw.y_values)
hist.render_to_file('./generating_data/images/svg/bar.svg')
Ejemplo n.º 9
0
def bitly():

    #trabajar desde una base de datos
    db = MongoClient(
        'mongodb://Scraper%2Fops:R3vim3x5o5%2F%[email protected]:27017/admin'
    ).XLamudi
    db2 = MongoClient(
        'mongodb://*****:*****@35.227.93.9:27017/admin'
    ).commserver
    collection = db['bitly']
    enlaces = [x for x in collection.find({})]
    collection2 = db2['deliveredmsgs']
    collection3 = db2['deliveredmails']
    sms = [y for y in collection2.find({})]
    email = [z for z in collection3.find({})]
    tokenbitly = 'e51c52061b3675fd00e523dfa557bd5efd21558e'  #token para api
    url = 'https://api-ssl.bitly.com/v3/user/popular_links?access_token={}'
    r = json.loads(
        (requests.get(url.format(tokenbitly)).content).decode('utf-8'))
    historial = r['data']['popular_links']
    links_populares = []
    for i in historial:
        for k in enlaces:
            if i['link'] == k['link_corto']:
                links_populares.append({
                    'enlace':
                    i['link'],
                    'clicks':
                    i['clicks'],
                    'enlace_real':
                    k['link_largo'],
                    'tipo':
                    k['campaña'],
                    "camp_id":
                    k["camp_id"],
                    "enviados":
                    k["enviados"],
                    "Fecha":
                    str(k["fecha_creacion"].year) + '/' +
                    str(k["fecha_creacion"].month) + '/' +
                    str(k["fecha_creacion"].day)
                })
    total_campsms = [x for x in collection2.distinct('camp_id')]
    total_campema = [x for x in collection3.distinct('camp_id')]
    total_campanasms = []
    for i in links_populares:
        for j in [x for x in collection2.distinct('camp_id')]:
            if j == i['camp_id'] and i['tipo'] == 'sms':
                total_campanasms.append({
                    'enlace':
                    i['enlace'],
                    'camp_id':
                    j,
                    'entregados':
                    collection2.find({
                        "camp_id": j
                    }).count()
                })
    for i in links_populares:
        for j in total_campanasms:
            if i['enlace'] == j['enlace']:
                i['entregados'] = j['entregados']
    total_campanaema = []
    for i in links_populares:
        for j in [x for x in collection3.distinct('camp_id')]:
            if j == i['camp_id'] and i['tipo'] == 'email':
                total_campanaema.append({
                    'enlace':
                    i['enlace'],
                    'camp_id':
                    j,
                    'entregados':
                    collection3.find({
                        "camp_id": j
                    }).count()
                })
    for i in links_populares:
        for j in total_campanaema:
            if i['enlace'] == j['enlace']:
                i['entregados'] = j['entregados']

    chart = pygal.Bar()
    custom_style = Style(colors=('#E80080', '#404040', '#9BC850', '#E80080',
                                 '#404040'))

    chart = pygal.Bar(margin=40)
    chart = pygal.Bar(width=180)
    chart = pygal.Bar(height=280)
    chart.title = 'total interacciones por enlace campaña sms-email'

    for i in links_populares:
        print(i)
        chart.add(
            str([i["camp_id"]]) + i['tipo'] + ' ' + 'enviados:' +
            str(i['enviados']) + ' ' + 'entregados:' + str([i['entregados']]) +
            str(int((i['entregados'] * 100) / i['enviados'])) + '%' + ' ' +
            'interaccion:' + str(int(
                (i['clicks'] * 100) / i['entregados'])) + '%',
            [{
                'value': i['clicks'],
                'label': 'clicks'
            }])

    chart.render_to_file('static/images/bar_chart.svg')
    img_url = 'static/images/bar_chart.svg?cache=' + str(time.time())

    return render_template('app.html', image_url=img_url)
Ejemplo n.º 10
0
#!/usr/bin/env python

import datetime
import gspread
import pygal

import config

gc = gspread.login(config.login, config.password)
wks = gc.open(config.sheet_name).sheet1

names2reps = []
for i in range(config.starting_row, config.ending_row+1):
    names2reps.append((wks.cell(i, 1).value, int(wks.cell(i, 2).value)))

title = datetime.datetime.now().strftime('Last update: %d %b @ %H:%M')
bar_chart = pygal.Bar(title=title, style=pygal.style.DarkSolarizedStyle)

for name, reps in names2reps:
    bar_chart.add(name, [reps])

bar_chart.render_to_file(config.svg_path)
Ejemplo n.º 11
0
from die import Die
import pygal

die = Die()
res = []
for i in range(1, 1000):
    single_res = die.roll()
    res.append(single_res)

print(res)

freqs = []
for v in range(1, die.side + 1):
    single_freq = res.count(v)
    freqs.append(single_freq)

print(freqs)

histogram = pygal.Bar()
histogram.title = 'results of rolling the die'
histogram.x_labels = ['1', '2', '3', '4', '5', '6']
histogram.x_title = 'result'
histogram.y_title = 'frequncy of results'

histogram.add('Die6', freqs)
histogram.render_to_file('die_visual4.svg')
Ejemplo n.º 12
0
def statistics():

    up_active = len(
        patient_detail.query.filter_by(state="Uttar Pradesh",
                                       status="Active").all())
    up_recovered = len(
        patient_detail.query.filter_by(state="Uttar Pradesh",
                                       status="Recovered").all())
    up_deceased = len(
        patient_detail.query.filter_by(state="Uttar Pradesh",
                                       status="Deceased").all())
    mp_active = len(
        patient_detail.query.filter_by(state="Madhya Pradesh",
                                       status="Active").all())
    mp_recovered = len(
        patient_detail.query.filter_by(state="Madhya Pradesh",
                                       status="Recovered").all())
    mp_deceased = len(
        patient_detail.query.filter_by(state="Madhya Pradesh",
                                       status="Deceased").all())
    maha_active = len(
        patient_detail.query.filter_by(state="Maharashtra",
                                       status="Active").all())
    maha_recovered = len(
        patient_detail.query.filter_by(state="Maharashtra",
                                       status="Recovered").all())
    maha_deceased = len(
        patient_detail.query.filter_by(state="Maharashtra",
                                       status="Deceased").all())
    guj_active = len(
        patient_detail.query.filter_by(state="Gujarat", status="Active").all())
    guj_recovered = len(
        patient_detail.query.filter_by(state="Gujarat",
                                       status="Recovered").all())
    guj_deceased = len(
        patient_detail.query.filter_by(state="Gujarat",
                                       status="Deceased").all())
    del_active = len(
        patient_detail.query.filter_by(state="Delhi", status="Active").all())
    del_recovered = len(
        patient_detail.query.filter_by(state="Delhi",
                                       status="Recovered").all())
    del_deceased = len(
        patient_detail.query.filter_by(state="Delhi", status="Deceased").all())

    line_chart = pygal.Bar()
    line_chart.title = 'Covid-19 cases in different states'
    line_chart.x_labels = [
        'Uttar Pradesh', 'Madhya Pradesh', 'Maharashtra', 'Gujarat', 'Delhi'
    ]
    line_chart.add('Active',
                   [up_active, mp_active, maha_active, guj_active, del_active])
    line_chart.add('Recovered', [
        up_recovered, mp_recovered, maha_recovered, guj_recovered,
        del_recovered
    ])
    line_chart.add(
        'Deceased',
        [up_deceased, mp_deceased, maha_deceased, guj_deceased, del_deceased])
    chart_data = line_chart.render_data_uri()

    stats = patient_detail.query.all()
    return render_template('statistics.html',
                           stats=stats,
                           chart_data=chart_data)
Ejemplo n.º 13
0
import pygal
chart = pygal.Bar()
chart.add('First', [{
    'value': 2,
    'label': 'This is the first',
    'xlink': 'http://en.wikipedia.org/wiki/First'
}])
print(chart.render(is_unicode=True))
Ejemplo n.º 14
0
def cc():
    pl = data.getpid()
    # pid = 49
    # l1,l2,l3 = data.getdata(pid) # '''l1 未解决按指派对象,l2 已解决按结局方案,l3 已解决按解决者'''

    titleList = [
        '未解决 - 严重程度', '未解决 - 开发人员', '已解决 - 解决方案', '新增 - 严重程度', '新增 - 测试人员'
    ]
    chartList = []
    tabelList = []
    lineList = []
    X = 49
    P = pl[0]
    if request.method == 'POST':
        # print(request.form)
        # if request.form['select'] in [p['name'] for p in pl]:
        for p in pl:
            if request.form['select'] == p['name']:
                X = p['id']
                P = p
                # print(X)
        for item in data.getdata(X):
            bar_chart = pygal.Bar(legend_at_bottom=True)
            for i in item:
                bar_chart.add(str(i['la']), i['num'], rounded_bars=4)
            tabelList.append(
                bar_chart.render_table(style=True, transpose=False))
            chartList.append(bar_chart.render_data_uri())
        # 曲线展示
        for testlist in data.getdataline(X):
            line_chart = pygal.Line(legend_at_bottom=True, x_label_rotation=20)
            newlist = []
            LL = []
            for item in testlist:
                newlist.append([i for i in item.values()])
            severity = list(set([i['lb'] for i in testlist]))
            # print(severity)
            date = sorted(list(set([i['la'] for i in testlist])))
            # print(date)
            for s in severity:
                for d in date:
                    t = 0
                    for item in newlist:
                        if (item[1] == s) & (item[0] == d):
                            t = item[2]
                            break
                    LL.append(t)
            line_chart.x_labels = date
            i = 0
            j = len(date)
            for s in severity:
                line_chart.add('%s' % s, LL[i:j])
                del LL[i:j]
            lineList.append(line_chart.render_data_uri())

    else:
        # 列表展示
        for item in data.getdata(X):
            bar_chart = pygal.Bar(legend_at_bottom=True)
            for i in item:
                bar_chart.add(str(i['la']), i['num'], rounded_bars=4)
            tabelList.append(
                bar_chart.render_table(style=True, transpose=False))
            chartList.append(bar_chart.render_data_uri())
        # 曲线展示
        for testlist in data.getdataline(X):
            line_chart = pygal.Line(legend_at_bottom=True, x_label_rotation=20)
            newlist = []
            LL = []
            for item in testlist:
                newlist.append([i for i in item.values()])
            severity = list(set([i['lb'] for i in testlist]))
            # print(severity)
            date = sorted(list(set([i['la'] for i in testlist])))
            # print(date)
            for s in severity:
                for d in date:
                    t = 0
                    for item in newlist:
                        if (item[1] == s) & (item[0] == d):
                            t = item[2]
                            break
                    LL.append(t)
            line_chart.x_labels = date
            i = 0
            j = len(date)
            for s in severity:
                line_chart.add('%s' % s, LL[i:j])
                del LL[i:j]
            # tabelList.append(line_chart.render_table(
            #     style=True, transpose=False))
            lineList.append(line_chart.render_data_uri())

    # return render_template('test.html', chart=chartList, title=titleList, table=tabelList, line=lineList, pid=pl, x=X, p=P)
    return render_template('test.html',
                           chart=chartList + lineList,
                           title=titleList,
                           table=tabelList,
                           pid=pl,
                           x=X,
                           p=P)
Ejemplo n.º 15
0
def poltpage():
    polt = pygal.Bar()
    polt.add('A', (1, 3, 3, 7))
    polt.add('B', (1, 6, 6, 4))
    return render_template("polt.html", chart=polt)
Ejemplo n.º 16
0
                    if pop_dict['Country_Code'] == country_code:
                        # 使用该国GDP总值除以人口数量,得到人均GDP
                        country_mean_gdps[i][year] = round(
                            gpd_dict['Value'] /
                            pop_dict['Population_in_%d' % year])
# 使用list列表依次保存美国、日本、俄罗斯、加拿大的人均GDP值
country_mean_gdp_list = [[], [], [], []]
# 构建时间数据
x_data = range(2001, 2017)
for i in range(len(country_mean_gdp_list)):
    for year in x_data:
        country_mean_gdp_list[i].append(country_mean_gdps[i][year])
# 定义国家名称列表
countries = ['美国', '日本', '俄罗斯', '加拿大']
# 创建pygal.Bar对象(柱状图)
bar = pygal.Bar()
# 采用循环添加代表条柱的数据
for i in range(len(countries)):
    bar.add(countries[i], country_mean_gdp_list[i])
bar.width = 1100
# 设置X轴的刻度值
bar.x_labels = x_data
bar.title = '2001到2016年各国人均GDP对比'
# 设置X、Y轴的标题
bar.x_title = '年份'
bar.y_title = '人均GDP(美元)'
# 设置X轴的刻度值旋转45度
bar.x_label_rotation = 45
# 设置将图例放在底部
bar.legend_at_bottom = True
# 指定将数据图输出到SVG文件中
Ejemplo n.º 17
0
import pygal

bar_chart = pygal.Bar()

bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.render_to_file('bar_chart.svg')
bar_chart.render()
Ejemplo n.º 18
0
            'label': repo_dict['description'],
            'xlink': repo_dict['html_url'],
        }
    else:
        plot_dict = {
            'value': repo_dict['stargazers_count'],
            'label': 'None',
            'xlink': repo_dict['html_url'],
        }
    plot_dicts.append(plot_dict)

# 可视化
my_style = LS('#333366', base_style=LCS)

my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15  # 将较长的项目名缩短为15个字符(如果你将鼠标指向屏幕上被截短的项目名,将显示完整的项目名)
my_config.show_y_guides = False  # 以隐藏图表中的水平线
my_config.width = 1000  # 自定义宽度,让图表更充分地利用浏览器中的可用空间。

chart = pygal.Bar(my_config, style=my_style)  # 隐藏了图例:show_legend=False
chart.title = 'Most-Starred Python Projects on Github'
chart.x_labels = names

# chart.add("", stars)
chart.add("lalalalalaalalal", plot_dicts)
chart.render_to_file("python_repos_java.svg")
print("There are", runway_12000_to_15000, "runways between 12000-15000")
print("There are", runway_15000_to_18000, "runways between 15000-18000")

#starting v6.0
#graph for lengths against times repeating

import pygal

#List of runways from above
runway_0_to_3000 = 20
runway_3000_to_6000 = 120
runway_6000_to_9000 = 358
runway_9000_to_12000 = 435
runway_12000_to_15000 = 124
runway_15000_to_18000 = 4

#adding to graph
runway_chart = pygal.Bar()
runway_chart.x_title = "Repeating Runway lengths"
runway_chart.y_title = "Runway Lengths in ft "
runway_chart.add('0-3000', runway_0_to_3000)
runway_chart.add('3000-6000', runway_3000_to_6000)
runway_chart.add('6000-9000', runway_6000_to_9000)
runway_chart.add('9000-12000', runway_9000_to_12000)
runway_chart.add('12000-15000', runway_12000_to_15000)
runway_chart.add('15000-18000', runway_15000_to_18000)

#updating to graph
runway_chart.render_to_file('Repeating lengths.svg')

exit()
Ejemplo n.º 20
0
def stats():
    if g.user:
        conn = sqlite3.connect('voters.db')
        c = conn.cursor()

        # START DATA ANALYSIS FOR VOTER GENDERS
        c.execute("SELECT count(*) as maleCount FROM basic_info WHERE basic_info_value ='Male'")
        maleCount = c.fetchone()
        c.execute("SELECT count(*) as femaleCount FROM basic_info WHERE basic_info_value ='Female'")
        femaleCount = c.fetchone()
        totalCount = maleCount + femaleCount

        pie_chart = pygal.Pie()
        pie_chart.title = 'Catanduanes Voters by Gender %'
        pie_chart.add('Male', maleCount)
        pie_chart.add('Female', femaleCount)
        pie_chart.add('Total Voters', totalCount)
        pieGender = pie_chart.render(is_unicode=True)
        # END DATA ANALYSIS FOR VOTER GENDERS

        # START DATA ANALYSIS FOR VOTER EDUCATION
        c.execute("SELECT count(*) as csuCount FROM education WHERE school = 'Catanduanes State University'")
        csuCount = c.fetchone()
        c.execute("SELECT count(*) as otherCount FROM education WHERE school != 'Catanduanes State University'")
        otherCount = c.fetchone()

        line_chart = pygal.HorizontalBar()
        line_chart.title = 'Catanduanes Voters by Education %'
        line_chart.add('Catanduanes State University', csuCount)
        line_chart.add('Others', otherCount)
        lineEduc = line_chart.render(is_unicode=True)
        # END DATA ANALYSIS FOR VOTER EDUCATION

        # START DATA ANALYSIS FOR VOTER AGE
        c.execute("SELECT basic_info_value FROM basic_info WHERE basic_info_value < date('now') - 18")
        ageCount = c.fetchall()

        def calculate_age(dtob):
            today = date.today()
            return today.year - dtob.year - ((today.month, today.day) < (dtob.month, dtob.day))

        ageList = {18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 0, 25: 0, 26: 0, 27: 0, 28: 0, 29: 0, 'other': 0}

        i = 0
        while i < len(ageCount):
            birthday = ageCount[i][0]
            date_format = '%Y/%m/%d'
            try:
                tbirthday = datetime.strptime(birthday, date_format)

                ageNow = calculate_age(date(tbirthday.year, tbirthday.month, tbirthday.day))

                for x in range(18, 29):
                    if ageNow == x:
                        ageList[x] += 1
                    else:
                        ageList[x] += 0
            except:
                pass

            i += 1


        line_chart = pygal.Bar()
        line_chart.title = 'Catanduanes Voters by age %'
        line_chart.x_labels = map(str, range(18, 36))
        line_chart.add('Voters', [ageList[18], ageList[19], ageList[20], ageList[21], ageList[22], ageList[23], ageList[24], ageList[25], ageList[26], ageList[27], ageList[28], ageList[29]])
        lineAge = line_chart.render(is_unicode=True)
        # END DATA ANALYSIS FOR VOTER AGE

        return render_template('stats.html', pieGender=pieGender, lineEduc=lineEduc, lineAge=lineAge, ageNow=ageNow)
    return redirect(url_for('login'))
Ejemplo n.º 21
0
# Feature Importance:
#Build and Train a Random Forest with 100 estimators
forest = RandomForestRegressor(n_estimators=100)
forest = forest.fit(X, y)

#Extract the feature column names and feature importances for the columns
column_list = df_feat.columns.values.tolist()
importances = forest.feature_importances_

#Zip the column names and importances togther and then sort them
col_imp = list(zip(column_list, importances))
sorted_col_imp = sorted(col_imp, key=lambda i: i[1], reverse=True)

#Create a pygal bar chart to plot the feature importances
bc = pygal.Bar(width=500, height=300, explicit_size=True)
bc.title = 'Forex Feature Importances'
for i in range(len(importances)):
    bc.add(sorted_col_imp[i][0], sorted_col_imp[i][1])
bc.render_in_browser()

# Train/Test Split:
#Set the percentage for training data
pct_train = .8

#Get the X,Y train/test sets
X_train = X[0:int(len(X) * pct_train)]
y_train = y[0:int(len(y) * pct_train)]
X_test = X[int(len(X) * pct_train):]
y_test = y[int(len(y) * pct_train):]