Exemple #1
0
def world_map_test():
    map_style = RotateStyle('#44ff77')
    map = World(style=map_style,
                value_formatter=lambda x: '{}'.format(x) + u'国家')
    map.title = 'world map scope'
    country_list = []
    chinese_name = {
        'United States': u'大美利坚',
        'United Kingdom': u'大英帝国',
        'France': u'法兰西',
        'Italy': u'意大利',
        'Japan': u'东瀛',
        'Germany': u'德意志',
        'Canada': u'加拿大'
    }

    detail_dict = {}
    print(type(chinese_name))
    for code, name in COUNTRIES.items():
        if name in ('United States', 'United Kingdom', 'France', 'Italy',
                    'Japan', 'Germany', 'Canada'):
            country_list.append(code)
            detail_dict[code] = chinese_name[name]
            print(code)
        #if name == 'Russian Federation':
        #    unique=code
    for x in detail_dict.items():
        map.add(u'G7国家', )
    #map.add(u'G8国家',country_list+[unique])
    map.render_to_file('/Users/qmp/Desktop/map1.svg')
Exemple #2
0
def one_country_map():
    '''一国地图'''
    wm_o = World()
    wm_o.force_uri_protocol = 'http'
    wm_o.title = '世界地图(中国)'
    wm_o.add('China', {'中国': 'cn'})
    wm_o.render_to_file('country_map.svg')
def test_worldmap_i18n_clear():
    set_countries(_COUNTRIES, True)
    wmap = World()
    wmap.add('countries', dict(fr=12))
    set_countries({'fr': 'Frankreich'}, clear=True)
    q = wmap.render_pyquery()
    assert len(
        q('.country.color-0')
    ) == 1
    assert 'Frankreich' in q('.country.fr').text()
Exemple #4
0
def world_country_map():
    '''世界各国地图'''
    wm_c = World()
    wm_c.force_uri_protocol = 'http'
    wm_c.title = '世界地图'
    for code, name in COUNTRIES.items():
        # print(name, code)
        wm_c.add(name, code)
    wm_c.add('Yemen', {'ye': 'Yemen'})
    wm_c.render_to_file('world_map.svg')
def test_worldmap():
    set_countries(_COUNTRIES, True)
    datas = {}
    for i, ctry in enumerate(COUNTRIES):
        datas[ctry] = i

    wmap = World()
    wmap.add('countries', datas)
    q = wmap.render_pyquery()
    assert len(
        q('.country.color-0')
    ) == len(COUNTRIES)
    assert 'France' in q('.country.fr').text()
Exemple #6
0
def csv_data_handle():
    with open(
            '/Users/qmp/Downloads/API_TX.VAL.TECH.MF.ZS_DS2_en_csv_v2/API_TX.VAL.TECH.MF.ZS_DS2_en_csv_v2.csv'
    ) as f:
        reader = csv.reader(f)
        #print(next(reader))
        map_style = RotateStyle('#4455ee', base_style=LightStyle)
        map = World()
        info_dict = {}
        for x in reader:
            if len(x) == 62:
                print(x[0], x[1], x[-2])
                code = counrty_list_show(x[0])
                info_dict[code] = float((x[-2])) if x[-2] != '' else None
        map.title = 'High-technology exports (% of manufactured exports)'
        map.add('', info_dict)
        map.render_to_file('/Users/qmp/Desktop/High_Tech_map.svg')
Exemple #7
0
def result():
    if request.method == 'POST' or request.method == 'GET':
        engine = sqlite3.connect('csv_test10.db')
        result = request.form['q']
        query = qu_op(result)
        b = query.split(' ')
        yr = []
        for i in b:
            if 'year' in i:
                yr.append(i[5:len(i)])
        df = pd.read_sql_query(query, engine)
        print(df)

        if df.loc[0, 'graph'] == '2':
            bar_chart = pygal.Bar(width=800,
                                  height=600,
                                  legend_at_bottom=True,
                                  human_readable=True,
                                  background='white',
                                  title=df.columns.values[1].capitalize() +
                                  ' across months in ' + yr[0],
                                  x_title='Months',
                                  y_title=df.columns.values[1].capitalize())
            for index, row in df.iterrows():
                bar_chart.add(row[2], row[1])
            final = bar_chart.render_data_uri()

        #df = df.sort_values('sales',ascending=False)

        elif df.loc[0, 'graph'] == '1':
            country_dict = {}
            wm = World(show_legend=False)
            wm.title = df.columns.values[2].capitalize(
            ) + " across Top Countries in " + yr[0]
            for i in range(len(df)):
                for code, name in COUNTRIES.items():
                    if name.lower() == df.iloc[i, 1].lower():
                        country_dict[code] = df.iloc[i, 2]
            wm.add("Country:", country_dict)
            final = wm.render_data_uri()

        return render_template('result.html', result=final)
Exemple #8
0
def plot_global_sex_ratio():
    below_20 = country_ratios.loc[country_ratios["Sex"] <= 0.20]
    below_20 = below_20.reset_index()
    below_40 = country_ratios.loc[country_ratios["Sex"] <= 0.40].loc[
        country_ratios["Sex"] > 0.20]
    below_40 = below_40.reset_index()
    below_60 = country_ratios.loc[country_ratios["Sex"] > 0.40].loc[
        country_ratios["Sex"] <= 0.60]
    below_60 = below_60.reset_index()
    below_80 = country_ratios.loc[country_ratios["Sex"] > 0.60].loc[
        country_ratios["Sex"] <= 0.80]
    below_80 = below_80.reset_index()
    above_80 = country_ratios.loc[country_ratios["Sex"] > 0.80]
    above_80 = above_80.reset_index()
    worldmap_chart = World()
    worldmap_chart.title = 'Countrywise Particpation Percentages of Females'
    worldmap_chart.add("0%-20%", [
        'af', 'dz', 'au', 'ar', 'am', 'be', 'bj', 'bz', 'cz', 'bw', 'bn', 'cl',
        'dk', 'dj', 'eg', 'er', 'fi', 'gh', 'ht', 'in', 'ir', 'iq', 'sa', 'kw',
        'ly', 'lr', 'lb', 'lu', 'my', 'ma', 'mw', 'mc', 'mr', 'ni', 'om', 'pk',
        'py', 'ph', 'pt', 'pr', 'zw', 'de', 'rs', 'sh', 'sm', 'so', 'sd', 'ch',
        'sz', 'sy', 'tz', 'tg', 'tn', 'tr', 'ae', 'ug', 'uy', 'vn', 'ye', 'mk',
        'zm'
    ])
    worldmap_chart.add('20%-40%', [
        'al', 'ad', 'au', 'at', 'az', 'bi', 'bo', 'br', 'bh', 'bg', 'bf', 'cf',
        'kh', 'ca', 'cg', 'td', 'cm', 'cd', 'co', 'cr', 'hr', 'cu', 'cy', 'cz',
        'do', 'ec', 'sv', 'es', 'ee', 'et', 'ru', 'fr', 'de', 'ga', 'gm', 'gb',
        'gw', 'ge', 'gq', 'gr', 'gn', 'gu', 'gy', 'cn', 'hn', 'hu', 'id', 'ie',
        'is', 'il', 'it', 'jo', 'jp', 'kz', 'ke', 'kg', 'kr', 'la', 'lv', 'ls',
        'li', 'lt', 'md', 'mv', 'mx', 'mn', 'mk', 'ml', 'mt', 'me', 'mz', 'mu',
        'mm', 'na', 'nl', 'np', 'ng', 'ne', 'no', 'nz', 'pa', 'pe', 'ps', 'pg',
        'pl', 'ro', 'za', 'rw', 'sc', 'sg', 'sl', 'si', 'rs', 'lk', 'sd', 'st',
        'sr', 'sk', 'se', 'cz', 'th', 'tj', 'tw', 'ru', 'us', 'uz', 've', 'zw'
    ])
    worldmap_chart.add('40%-60%', [
        'ao', 'bt', 'by', 'cn', 'cv', 'jm', 'mg', 'kp', 'ru', 'tm', 'tl', 'ua',
        'vn'
    ])
    worldmap_chart.add('60%-80%', [])
    worldmap_chart.add('80%-100%', [])
    worldmap_chart.render_in_browser()
Exemple #9
0
def json_data_handle():
    gdp_style = RotateStyle('#5555ff')
    map = World(style=gdp_style)
    package = Package('/Users/qmp/Downloads/gdp.zip')
    resources = package.descriptor['resources']
    resourceList = [resources[x]['name'] for x in range(0, len(resources))]
    #print(resourceList)
    data = package.resources[0].read()
    show_dict = {}
    for x in data:
        if x[2] == 2016:
            code = counrty_list_show(x[0])
            #print(code,x)
            gdp = long(x[-1])
            print(gdp)
            show_dict[code] = gdp
    print(show_dict)
    map.title = u'2016世界所有经济体GDP'
    map.add(u'经济体', show_dict)
    map.render_to_file('/Users/qmp/Desktop/map_gdp.svg')
Exemple #10
0
def main():
    # Get dict of code to population at year 2010 for plotting
    world_pop_2010 = build_pop_dict("population_data.json", 2010)

    # Divide dict into three smaller dicts corresponding to population levels (low, medium, high)
    low_pop_2010, medium_pop_2010, high_pop_2010 = {}, {}, {}
    for code, pop in world_pop_2010.items():
        if pop < 10000000:
            low_pop_2010[code] = pop
        elif pop < 1000000000:
            medium_pop_2010[code] = pop
        else:
            high_pop_2010[code] = pop

    # Create pygal maps plotting object
    map_style = ps.DarkSolarizedStyle

    wm = World(style=map_style)
    wm.title = 'World populations'

    # Add the shading for countries in each population level
    wm.add('0-10m', low_pop_2010)
    wm.add('10m-1b', medium_pop_2010)
    wm.add('>1b', high_pop_2010)

    # Render graph to svg file
    wm.render_to_file('world.svg')
Exemple #11
0
def world_population():
    filename = "population_data.json"
    with open(filename) as f:
        pop_data = json.load(f)

    cc_pop = {}
    for pop_dict in pop_data:
        if pop_dict['Year'] == '2010':
            country_name = pop_dict['Country Name']
            population = int(float(pop_dict['Value']))
            code = get_country_code(country_name)
            if code:
                cc_pop[code] = population

    #grouping countries into 3 pop levels
    cc_pops1, cc_pops2, cc_pops3 = {}, {}, {}
    for cc, pop in cc_pop.items():
        if pop < 10000000:
            cc_pops1[cc] = pop
        elif pop < 1000000000:
            cc_pops2[cc] = pop
        else:
            cc_pops3[cc] = pop

    print(len(cc_pops1), len(cc_pops2), len(cc_pops3))

    #building a world map
    wm_style = RotateStyle("#336699", base_style=LightColorizedStyle)
    wm = World(style=wm_style)
    wm.title = "World Population in 2010, by Country"
    wm.add('0-10m', cc_pops1)
    wm.add('10m-1bn', cc_pops2)
    wm.add('>1bn', cc_pops3)

    wm.render_to_file('world_population.svg')
Exemple #12
0
    def clickedBtn(self):
        try:
            global capitala
            capitala = self.label_capitala.text()
            if capitala:
                path = easygui.filesavebox(msg="",
                                           title="Salvati datele",
                                           default=selected_country + ".txt",
                                           filetypes=None)

                # salvare date in fisier txt
                file = open(path, "w")
                file.write("Tara: " + tara + "\n")
                file.write("Continent: " + continent + "\n")
                file.write("Capitala: " + capitala + "\n")
                file.write("Populatie: " + populatie + "\n")
                file.write("Suprafata: " + suprafata + "\n")
                file.write("Moneda: " + moneda + "\n")
                file.write("Ora GMT: " + timezone + "\n")
                file.write("Provincii: " + str(provincii) + "\n")
                file.write(
                    "All data: " +
                    json.dumps(countries.get_all_info_for_country(tara)) +
                    "\n")
                file.close()

                # desenam harta lumii si o salvam

                worldmap_chart = World()
                worldmap_chart.title = tara
                worldmap_chart.add(
                    'Tara aleasa',
                    [countries.get_country_code_from_country(tara)])
                path = path[:len(path) - 4]
                print(path)
                worldmap_chart.render_to_file(path + ".svg")
            else:
                self.prompt_message("Trebuie sa selectati o tara!", "Eroare")
        except Exception as ex:
            print(ex)
Exemple #13
0
def generate_worldmap(df_nation_counts):
    """displays a worldmap coded with the pygal-library in HTML format (interactive Chart)
    
        Parameters: Nations Count Dataframe

        Returns: HTML worldmap

       """ 
    total_dict = df_nation_counts.set_index('Nation').to_dict('dict').get('Anzahl Gesuche')
    dict_1_5000 = dict(filter(lambda elem: elem[1] <= 5000, total_dict.items()))
    dict_5000_20000 = dict(filter(lambda elem: (elem[1] > 5000 and elem[1] <= 20000), total_dict.items()))
    dict_20000_plus = dict(filter(lambda elem: (elem[1] > 20000), total_dict.items()))
    
    base_html = """
    <!DOCTYPE html>
    <html>
      <head>
      <script type="text/javascript" src="https://kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js"></script>
      <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/pygal-tooltips.js"></script>
      </head>
      <body>
        <figure>
          {rendered_chart}
        </figure>
      </body>
    </html>
    """
    #styles
    custom_style = Style(
        colors=('#e4ed80', '#7dccbc', '#63192e'),
        tooltip_font_size=8,
        legend_font_size=7,
        title_font_size=10,
        background='#ffffff')

    #define chart
    worldmap_chart = World(style=custom_style)
    worldmap_chart.title = 'Anzahl Asylgesuche nach Nation'
    worldmap_chart.add('1-5000 Gesuche', dict_1_5000)
    worldmap_chart.add('5000-20000 Gesuche', dict_5000_20000)
    worldmap_chart.add('20000+ Gesuche', dict_20000_plus)

    #render
    rendered_chart = worldmap_chart.render(is_unicode=True)
    plot_html = base_html.format(rendered_chart=rendered_chart)
    return display(HTML(plot_html))
Exemple #14
0
class PWorldMap(object):
    '''
    classdocs
    '''
    def __init__(self, title):
        '''
        Constructor
        '''
        self.wmap = World()
        self.wmap.title = title

    def sample(self):
        self.wmap.add('F countries', ['fr', 'fi'])
        self.wmap.add('M countries', [
            'ma', 'mc', 'md', 'me', 'mg', 'mk', 'ml', 'mm', 'mn', 'mo', 'mr',
            'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz'
        ])
        self.wmap.add('U countries', ['ua', 'ug', 'us', 'uy', 'uz'])
        self.wmap.add('North America', {
            'ca': 84949494949,
            'mx': 494794164,
            'us': 99794616
        })

    def render(self, filename=None):
        '''
        render the map
        see http://www.pygal.org/en/stable/documentation/output.html
        '''
        if filename is None:
            self.wmap.render_in_browser()
        else:
            if filename.endswith(".png"):
                self.wmap.render_to_png(filename)
            else:
                self.wmap.render_to_file(filename)
Exemple #15
0
def render_world_map(gdpinfo, plot_countries, year, map_file):
    """
    Inputs:
      gdpinfo        - A GDP information dictionary
      plot_countries - Dictionary whose keys are plot library country codes
                       and values are the corresponding country name
      year           - String year to create GDP mapping for
      map_file       - Name of output file to create

    Output:
      Returns None.

    Action:
      Creates a world map plot of the GDP data for the given year and
      writes it to a file named by map_file.
    """
    worldmap_chart = World()
    worldmap_chart.title = 'GDP by Country (Log Scale) for ' + year
    gdp_dict, missing_data, missing_data_year = build_map_dict_by_name(gdpinfo, plot_countries, year)
    worldmap_chart.add('GDP for '+year, gdp_dict)
    worldmap_chart.add('Missing '+year+' data', missing_data_year)
    worldmap_chart.add('No record', missing_data)
    worldmap_chart.render_to_file(map_file)
Exemple #16
0
# See how many countries are in each level.
print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))
"""
Essa saída mostra que há 85 países com menos de 10 milhões de pessoas,
69 países com população entre 10 milhões e 1 bilhão de pessoas e dois
países extremos com mais de 1 bilhão.
"""
from pygal.style import LightColorizedStyle as LG
dc = {'ca'}
wm_style2 = LG
wm_style = RS('#336699', base_style=LCS)
#wm = pygal.Worldmap(style=wm_style) #NÃO FUNCIONA MAIS ATUALMENTE.
#wm = wm(style=wm_style) #GAMBIARRA QUE EU FIZ, MAS TAMBÉM NÃO SURTIU O EFEITO ESPERADO.
wm = WD(style=wm_style2)
#wm.force_uri_protocol = 'http'
wm.title = 'World Population in 2010, by Country'
#Aqui Iluminou a America Do Norte toda. O problema é que; estes .adds NÃO estão recebendo Estes dicionarios 'cc_pops_2'
#wm.add('0 a 10', ['ca', 'mx', 'us'])
wm.add('0-10m', cc_pops_1)  #Se eu colocar a Var 'dc = {'ca'}' .Funciona. Mas cc_pops NÃO.
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)

wm.render_to_file('Pagina_519_20_População Mundial.svg')

"""
Não Obtive os mesmos Resultados dos mostrados no Livro, pois, o método de Import
mostrado no livro esta ultrapassado. E o metodo atual não obtive a mesma reação.
"""
#Soluções dos Exercicios:
#https://ehmatthes.github.io/pcc/solutions/chapter_16.html
Exemple #17
0
            code = get_country_code(country_name)
            if code:
                tmp = {code: export_value_index}
                tx_dic.update(tmp)
            else:
                print("Błąd - " + country_name)
    #print(tx_dic)

# Podzielenie państw na trzy grupy według wielkości indexu
tx_dic_100, tx_dic_300, tx_dic_more = {}, {}, {}
for cc, pop in tx_dic.items():
    if pop < 100:
        tx_dic_100[cc] = pop
    elif pop < 300:
        tx_dic_300[cc] = pop
    else:
        tx_dic_more[cc] = pop

# Przygotowanie wykresu

wm_style = RS('#336699', base_style=LCS)
wm = World(style=wm_style)

wm.force_url_protocol = 'http'
wm.title = 'Export value index w 2017 roku. (dane dla poszczególnych państw)'
wm.add('< 100', tx_dic_100)
wm.add('100 < 300', tx_dic_300)
wm.add('< 300', tx_dic_more)

wm.render_to_file('Export_value_index_2017.svg')
filename = 'gdp_json.json'
with open(filename) as f:
    gdp_data = json.load(f)

cc_gdps = {}
for gdp_dict in gdp_data:
    if gdp_dict['Year'] == 2010:
        country_name = gdp_dict['Country Name']
        gdp = int(gdp_dict['Value'])
        code = get_country_code(country_name)
        if code:
            cc_gdps[code] = gdp
#根据gdp数值对国家进行分组
cc_gdps_1, cc_gdps_2, cc_gdps_3 = {}, {}, {}
for cc, gdp in cc_gdps.items():
    if gdp < 10000000000:
        cc_gdps_1[cc] = gdp
    elif gdp < 1000000000000:
        cc_gdps_2[cc] = gdp
    else:
        cc_gdps_3[cc] = gdp
#绘制世界地图
wm = World()
wm.title = 'World GDP in 2010'
wm.add('0-10bn', cc_gdps_1)
wm.add('10bn-1000bn', cc_gdps_2)
wm.add('>1000bn', cc_gdps_3)

wm.render_to_file('World_GDP.svg')
Exemple #19
0
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     NorthAmericaPopulation
   Description :
   Author :        Liangz
   Date:          2018/10/26
-------------------------------------------------
   Change Activity:
                   2018/10/26:
-------------------------------------------------
"""
__author__ = 'Liangz'

from pygal_maps_world.maps import World

world_map = World()

world_map.title = 'Populations Of Countries In North America'
world_map.add('North America', {
    'ca': 34126000,
    'us': 309349000,
    'mx': 113423000
})

world_map.render_to_file('NA_population.svg')
Exemple #20
0
from pygal_maps_world.maps import World

wm = World()
wm.title = 'Americas'

wm.add('North America', ['ca', 'mx', 'us'])
wm.add('Central America', ['bz', 'cr', 'gt', 'hn', 'ni', 'pa', 'sv'])
wm.add('South America', [
    'ar', 'bo', 'br', 'cl', 'co', 'ec', 'gf', 'gy', 'pe', 'py', 'sr', 'uy',
    've'
])

wm.render_to_file('americas.svg')
from pygal_maps_world.maps import World

wm = World()
wm.title = 'North, Central and South America'

wm.add('North America', ['ca', 'mx', 'us'])
wm.add('Central America', ['bz', 'cr', 'gt', 'hn', 'ni', 'pa', 'sv'])
wm.add('South America', ['ar', 'bo', 'br', 'cl', 'co', 'ec', 'gf', 'gy', 'pe',
                         'py', 'sr', 'uy', 've'])

wm.render_to_file('americas.svg')
Exemple #22
0
import pandas as pd

from pygal.style import *
from pygal_maps_world.maps import World
from country_codes import get_country_code

csv = pd.read_csv("co2_emissions.csv", keep_default_na=False, skiprows=4)
csv['code'] = csv['Country Name'].apply(get_country_code)
# 需要把CO2排放量转换为数字格式
csv['digit_2013'] = pd.to_numeric(csv['2013'])

# 把CO2排放量分3个层次
# 并把国家码和对应的2013年CO2排放量取出来放在字典中
co2_1, co2_2, co2_3 = {}, {}, {}
for code, co2 in zip(csv['code'], csv['digit_2013']):
    if co2 <= 5:
        co2_1[code] = co2
    elif co2 <= 10:
        co2_2[code] = co2
    else:
        co2_3[code] = co2

wm = World(fill=True, style=RedBlueStyle)
wm.title = "World's CO2 emissions at 2013"
wm.add("CO2 <= 5", co2_1)
wm.add("CO2 <= 10", co2_2)
wm.add("CO2 > 10", co2_3)
wm.render_to_file("practice_16-7.svg")
Exemple #23
0
from pygal_maps_world.maps import World

wm = World()
wm.force_url_protocol = 'http'
wm.title = 'Wielkość populacji w krajach Ameryki Północnej'
wm.add('Ameryka Północna', {'ca': 34126000, 'us': 309349000, 'mx': 113423000})
wm.render_to_file('na_populations.svg')

Exemple #24
0
from pygal_maps_world.maps import World

wm = World()
wm.title = '北美洲国家人口分布'
wm.add("北美", {'ca': 34126000, 'us': 309349000, 'mx': 113423000})
wm.render_to_file('na_populations.svg')
        population = int(float(pop_dict['Value']))
        code = get_country_code(country_name)
        if code:
            # print(code + ':' + str(population))
            whole_population[code] = population
        # else:
        #     print('Error - ' + country_name)

# 根据人口数量将所有的国家分成三组
world_population_1, world_population_2, world_population_3 = {}, {}, {}
for world_code, population in whole_population.items():
    if population < 10000000:
        world_population_1[world_code] = population
    elif population < 1000000000:
        world_population_2[world_code] = population
    else:
        world_population_3[world_code] = population

# 看看每组分别包含多少个国家
print(len(world_population_1), len(world_population_2),
      len(world_population_3))

world_map_style = RotateStyle('#336699', base_style=LightColorizedStyle)
# world_map_style = LightColorizedStyle
world_map = World(style=world_map_style)
world_map.title = 'World Population In 2010, By Country'
world_map.add('0 - 10M', world_population_1)
world_map.add('10M - 1BN', world_population_2)
world_map.add('>1BN', world_population_3)
world_map.render_to_file('threelevel_light_style.svg')
        else:
            print('ERROR - ' + country_name)

# Group the countries into 3 population levels.
cc_pops_1 = {}
cc_pops_2 = {}
cc_pops_3 = {}

for cc, pop in cc_populations.items():
    if pop < 100000000:
        cc_pops_1[cc] = pop
    elif pop < 1000000000:
        cc_pops_2[cc] = pop
    else:
        cc_pops_3[cc] = pop

# See how many countries are in each level.
print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))

# wm = World()
wm_style = RotateStyle('#336699', base_style=LightColorizedStyle)
wm = World(style=wm_style)

wm.title = 'World Population in 2010, by Country'
# wm.add('2010', cc_populations)
wm.add('0-10m', cc_pops_1)
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)

wm.render_to_file('world_population.svg')
for pop_dict in pop_data:
    #print(pop_dict)
    if int(pop_dict['Year']) == 2010:
        country_name = pop_dict['Country Name']
        population = int(pop_dict['Value'])
        code = get_country_code(country_name)
        if code:
            cc_populations[code] = population
            #print(code + ": " + str(population))
        else:
            print('ERROR - ' + country_name)
#根据人口数量将所有的国家分成三组
cc_pops_1,cc_pops_2,cc_pops_3 = {},{},{}
for cc, pop in cc_populations.items():
    if pop < 100000000:
        cc_pops_1[cc] = pop
    elif pop < 100000000:
        cc_pops_2[cc] = pop
    else:
        cc_pops_3[cc] = pop
#看看每组包含了多少个国家
wm = World()
print(len(cc_pops_1),len(cc_pops_2),len(cc_pops_3))
wm_style = RS('#336699', base_style=NS)
wm = World(style = wm_style)
wm.title = 'World Population in 2010, by Country'
wm.add('0-10m', cc_pops_1)
wm.add('10m-1bn',cc_pops_2)
wm.add('>1bn', cc_pops_3)
wm.render_to_file('world_population.svg')
Exemple #28
0
#         print(valorConvertido)
#         valorConvertido += 1
#         print(valorConvertido)

# mapaMundi = World()
# mapaMundi.title = 'Norte, Central e Sul'
# mapaMundi.add('Norte',['ca','mx','us'])
# mapaMundi.add('Central',['ma', 'mc', 'md', 'me', 'mg','mk', 'ml', 'mm', 'mn', 'mo','mr', 'mt', 'mu', 'mv', 'mw'])
# mapaMundi.add('Sul',['ar','br','cl'])
# mapaMundi.render_in_browser()

# Plotando dados numéricos em um mapa-múndi

mapaMundi = World()
mapaMundi.title = 'Norte, Central e Sul'
mapaMundi.add('Norte', {'ca': 21, 'mx': 22, 'us': 23})
mapaMundi.add(
    'Central', {
        'ma': 42,
        'mc': 33,
        'md': 421,
        'me': 45,
        'mg': 31,
        'mk': 11,
        'ml': 48,
        'mm': 44,
        'mn': 76,
        'mo': 9
    })
mapaMundi.add('Sul', {'ar': 22, 'br': 11, 'cl': 34})
mapaMundi.render_in_browser()
Exemple #29
0
import json
from pygal_maps_world.maps import World
from country_codes import get_country_code
from pygal.style import LightColorizedStyle as LCS, RotateStyle as RS

filename = 'gdp_json.json'
with open(filename) as f:
    pop_data = json.load(f)

gdp = {}
for gdp_dict in pop_data:
    if gdp_dict['Year'] == 2010:
        country_name = gdp_dict['Country Name']
        gdp_val = float(gdp_dict['Value'])
        code = get_country_code(country_name)
        if code:
            gdp[code] = gdp_val

wm_style = RS('#336699', base_style=LCS)
wm = World(style=wm_style)
wm.title = "World GDP in 2010, by Country"
wm.add("GDP", gdp)

wm.render_to_file('world_gdp.svg')
# 为了使颜色分层更加明显
cc_level_1, cc_level_2, cc_level_3,cc_level_4,cc_level_5,cc_level_6,cc_level_7 = {}, {}, {},{}, {}, {},{}
for cc, number1 in cc_movie_number.items():
    if number1 > 3000:
        cc_level_7[cc] = number1
    elif number1 < 3000 and number1 > 2000:
        cc_level_6[cc] = number1
    elif number1 < 2000 and number1 > 900:
        cc_level_5[cc] = number1
    elif number1 < 900 and number1 > 675:
        cc_level_4[cc] = number1
    elif number1 < 675 and number1 > 450:
        cc_level_3[cc] = number1
    elif number1 < 450 and number1 > 225:
        cc_level_2[cc] = number1
    else:
        cc_level_1[cc] = number1

wm_style = RotateStyle(color='#fde0dc', base_style=LightColorizedStyle)
world = World(style=wm_style)
world.title = '近10年世界范围各个地区的电影数量'
world.add('不足225部', cc_level_1)
world.add('225——450部', cc_level_2)
world.add('450——675部', cc_level_3)
world.add('675——900部', cc_level_4)
world.add('900——2000部', cc_level_5)
world.add('2000——3000部', cc_level_6)
world.add('超过3000部', cc_level_7)

world.render_to_file('近10年世界范围各个地区的电影数量.svg')
Exemple #31
0
# 创建一个包含人口数量的字典
cc_populations = {}
for pop_dict in pop_data:   # 遍历每个字典
    if pop_dict['Year'] =='2010':
        country_name = pop_dict['Country Name']
        population = int(float(pop_dict['Value']))  #float将字符串转换为小数
        code = get_country_code(country_name)
        if code:
            cc_populations[code] = population

# 根据人口数量将所有的国家分成三组
cc_pops1,cc_pops2,cc_pops3 = {},{},{}
for cc,pop in cc_populations.items():
    if pop < 10000000:
        cc_pops1[cc] = pop
    elif pop < 1000000000:
        cc_pops2[cc] = pop
    else:
        cc_pops3[cc] = pop


wm_style = RotateStyle('#336699',base_style=LightColorizedStyle)
wm = World(style = wm_style)
wm.title='World Population in 2010, by Country'
wm.add('0-10m', cc_pops1)
wm.add('10m-1bn', cc_pops2)
wm.add('>1bn', cc_pops3)

wm.render_to_file('world_population.svg')
f = open("gdp.json")
gdp = json.load(f)

gdps = {}
# 把所有国家的名称通过get_country_code函数以得到其国别码
# 并把其GDP存入字典
for item in gdp:
    if item["Year"] == "2016":
        code = get_country_code(item["Country Name"])
        if code:
            gdps[code] = int(float(item["Value"])) / 100000000

# 根据GDP数量级别不同把国家分成三组
gdp_1, gdp_2, gdp_3 = {}, {}, {}
for c, g in gdps.items():
    if g < 1000:
        gdp_1[c] = g
    elif g < 10000:
        gdp_2[c] = g
    else:
        gdp_3[c] = g

wm_style = RotateStyle('#336699', base_style=LightColorizedStyle)
wm = World(style=wm_style)
wm.title = "GDP of the Whold World - 2016"
wm.add("0-100bn", gdp_1)
wm.add("100-1000bn", gdp_2)
wm.add("1000-10000bn", gdp_3)

wm.render_to_file("gdps.svg")
from pygal_maps_world.maps import World

wm = World()
wm.title = 'Populations of Countries in North America'

wm.add('North America', {'ca': 34126000, 'us': 309349000, 'mx': 113423000})

wm.render_to_file('na_populations.svg')