コード例 #1
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')
コード例 #2
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')
dataframe = pd.read_csv(JOURNAL_PUP)

# Select two columns and remove any rows containing NAN values
dataframe = dataframe[['\ufeff"Country Name"', '2013']].dropna()

# Convert country names to Pygals country codes
dataframe['\ufeff"Country Name"'] = dataframe['\ufeff"Country Name"'].map(
    get_country_code)
dataframe = dataframe[dataframe['\ufeff"Country Name"'].notnull()]

# Divide the dataframe into groups
pubs_low = dataframe[dataframe['2013'] < 100]
pubs_med = dataframe[(dataframe['2013'] >= 100) & (dataframe['2013'] < 1000)]
pubs_high = dataframe[dataframe['2013'] >= 1000]

# Convert Dataframes back to dictionaries, because Pygal expects data to be
# in a dictionary.
pubs_low = dict(zip(pubs_low['\ufeff"Country Name"'], pubs_low['2013']))
pubs_med = dict(zip(pubs_med['\ufeff"Country Name"'], pubs_med['2013']))
pubs_high = dict(zip(pubs_high['\ufeff"Country Name"'], pubs_high['2013']))

# Setup the Pygal map
wm = World(style=LCS)
wm.force_uri_protocol = 'http'
wm.title = 'Publication of Scientific and Technical Journal\nArticles in 2013, by Country\nData from: The World Bank'
wm.add('0-100', pubs_low)
wm.add('100-1,000', pubs_med)
wm.add('> 1,000', pubs_high)

wm.render_to_file('world_journal_publication_pd.svg')
        else:
            print("Error: " + record["Country Name"] + " is invalid")

# store in dictionary to be worked with pygal
# pops_1: population < 10000000
# pops_2: 10000000 <= population <= 1000000000
# pops_3: population > 1000000000
pops_1, pops_2, pops_3 = {}, {}, {}

for record in population_data_2010:
    cc = find_country_code(record["Country Name"])
    population = int(float(record["Value"]))
    if population < 10000000:
        pops_1[cc] = population
    elif population <= 1000000000:
        pops_2[cc] = population
    else:
        pops_3[cc] = population


# plot
world_population_map_style = DarkSolarizedStyle()
world_population_map = World(style=world_population_map_style)
world_population_map.title = 'World Population Map'

world_population_map.add('< 10m', pops_1)
world_population_map.add('10m - 1bn', pops_2)
world_population_map.add('>1bn', pops_3)

world_population_map.render_to_file('World Population Map (styling).svg')
コード例 #5
0
from pygal.maps.world import World
from pygal.style import LightColorizedStyle as LCS, RotateStyle as RS
from countries import get_country_code
filename = 'world_gdp_json.json'
filename_output = "world_gdp.svg"
with open(filename) as f:
	world_gdp_file = json.load(f)
#print 2010 population of each country
world_gdp = {} #a dictionary to hold country_code - gdp
for data_row in world_gdp_file:
	#print(data_row)
	if(data_row['Year'] == 2000):
		country_name = data_row['Country Name']
		#print(country_name)
		country_code = get_country_code(country_name)
		#country_code = data_row['Country Code'] #standardize country code for each country
		#print(country_code)
		gdp = int(float(data_row['Value'])) 		#we need to convert string into float first after that int() function can remove decimal
		#print(gdp)
		if country_code:
			world_gdp[country_code] = gdp
			#print(country_name + " " + country_code + " " + gdp)
print(world_gdp)
style_obj = RS('#FF0000', base_style = LCS) #return an object of style
wm = World(style = style_obj)
wm.title = 'World GDP 2000 by Country'
wm.add('2000', world_gdp)
wm.render_to_file("world_gdp_map.svg")
#open pygal file with Safari
safari = app("Safari")
safari.make(new = k.document, with_properties={k.URL:"file:///Users/tungvo/Desktop/Portfolio/data_visualization/world_gdp_map.svg"})
コード例 #6
0
 def map_data(self, user_selection):
     #This object will be used to call one method from the support class.
     support = Support()
     data = pd.read_csv('Kaggle.csv')
     #These two lists will hold all of my data for what the user wants to
     #look at.
     data_list = []
     state_list = []
     info = data[user_selection]
     state = data['State']
     #I am now looping through the data and then appending that information
     #into the list that I created above.
     for i in info:
         data_list.append(i)
     for s in state:
         state_list.append(s)
     #Function to convert country names to 2 letter abbreviations. See country_name_convert function in the
     #support.py file to see how it works. It is the only piece of code that I got all from stack overflow.
     country_codes = support.country_name_convert(state_list)
     #Another list is created to hold all of the country abbreviations which have been converted to lowercase.
     new_countrylist = []
     #I have to convert all of the country codes to lowercase-only way the wm.add method seems to work.
     for country in country_codes:
         lowercase_country = country.lower()
         new_countrylist.append(lowercase_country)
     #The wm.add method needs a dictionary to work with. Here, I create a dictionary which holds the country abbrevation
     #and the data for what the user wants to look at.
     country_dictionary = {}
     count = 0
     while count < len(country_codes):
         country_dictionary[new_countrylist[count]] = data_list[count]
         count += 1
     data_1, data_2, data_3, data_4, data_5 = {}, {}, {}, {}, {}
     #I need to break up the data points into five different intervals.
     #To do this I need to find the max and min of the data_list
     max_value = max(data_list)
     min_value = min(data_list)
     #Once I have the max and min I can find the length
     length = max_value - min_value
     #I then divide the length by 5 for the number of dictionaries that I
     #have created above: data_1, data_2 etc.
     parts = length / 5
     #I use a for loop to place the data into the right intervals
     for state, information in country_dictionary.items():
         if information <= parts:
             data_1[state] = information
         elif information > parts and information <= parts * 2:
             data_2[state] = information
         elif information > parts * 2 and information <= parts * 3:
             data_3[state] = information
         elif information > parts * 3 and information <= parts * 4:
             data_4[state] = information
         else:
             data_5[state] = information
     print('''
     Please note to look at the data, you have to open up the SVG map in
     Chrome. The file should be entitled map.svg. The program will return to
     the main menu so you must open up the file manually.
     ''')
     input('Press enter to continue ')
     #This code here is what will actually make the SVG maps for the data that
     #the user wants to look at.
     wm_style = RotateStyle('#336699')
     wm = World(style=wm_style)
     wm.title = "Map of " + user_selection + ' Data'
     wm.add(str(0) + '-' + str(parts), data_1)
     wm.add(str(parts) + '-' + str(parts * 2), data_2)
     wm.add(str(parts * 2) + '-' + str(parts * 3), data_3)
     wm.add(str(parts * 3) + '-' + str(parts * 4), data_4)
     wm.add(str(parts * 4) + '-' + str(parts * 5), data_5)
     wm.render_to_file('map.svg')
コード例 #7
0
cc_populations = {}

for pop_dict in pop_data:
    country_name = pop_dict['Country Name']
    population = pop_dict['Value']
    code = get_country_code(country_name)
    if code:
        cc_population[code] = population

pop_lvl_1 = {}
pop_lvl_2 = {}
pop_lvl_3 = {}

for code, pop in cc_populations.items():
    if pop < 10000000:
        pop_lvl_1[code] = pop
    elif pop < 1000000000:
        pop_lvl_2[code] = pop
    else:
        pop_lvl_3[code] = pop

worldmap_chart = World()
worldmap_chart.title = '2016 World Population by Country'
worldmap_chart.add('0-10M', pop_lvl_1)
worldmap_chart.add('10M - 1B',pop_lvl_2)
worldmap_chart.add('1Bn+', pop_lvl_3)
worldmap_chart.render_in_browser()


コード例 #8
0
from pygal.maps.world import World
import refined_dic

usable_dic = refined_dic.get_refined_dic()
map = World()
map.title = 'Population distribution across countries of world'
map.add('Data for 2010', usable_dic)
map.render_to_file('map.svg')
コード例 #9
0
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:  # if the country has an international code, then they will appear.
            country_population[code] = population

# Grouping the populations

c_code_1, c_code_2, c_code_3 = {}, {}, {}
for c_country, pop in country_population.items():
    if pop < 10000000:
        c_code_1[c_country] = pop
    elif pop < 1000000000:
        c_code_2[c_country] = pop
    else:
        c_code_3[c_country] = pop

# Use RotateStyle and LightColorizedStyle to customize your graph map
world_map_style = RS("#00ffff", base_style=LCS)

world_map = World(style=world_map_style)
world_map.title = (
    "World Population in 2010 , by Country [Python Crash Course]")
world_map.add("10 Million", c_code_1)
world_map.add("10 Mil - 1 Bn", c_code_2)
world_map.add(">1 Billion", c_code_3)

world_map.render_to_file("Final_Graph.svg")
コード例 #10
0
# Print the 2010 population for each country
for pop_dict in pop_data:  # 2nd line
    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_populations[code] = population
        else:
            print(country_name)

# Group the countries into 3 population levels.

cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}  # 1st line
for cc, pop in cc_populations.items():
    if pop < 10000000:
        cc_pops_1[cc] = pop
    elif pop < 1000000000:
        cc_pops_2[cc] = pop
    else:
        cc_pops_3[cc] = pop

wm_style = RotateStyle('#336699')  # 2nd line
wm = World(style=wm_style)  # 3rd line
wm.title = 'World Populations in 2010, by Country'
wm.add('0-10m', cc_pops_1)  # 4th line
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)

wm.render_to_file('world_population.svg')
コード例 #11
0
    if obj['Year'] == '2010':
        # Discrepancies should be skipped over or handled case by case
        code = rev_COUNTRIES.get(obj['Country Name'], None)
        if code is None:
            continue
        population = int(float(obj['Value']))
        cc_populations[code] = population

print(cc_populations)

# Group countries into 3 population levels
cc_pop1, cc_pop2, cc_pop3 = {}, {}, {}
part1 = 5 * 10**6
part2 = 25 * 10**6
for key, pop in cc_populations.items():
    if pop < part1:
        cc_pop1[key] = pop
    elif pop < part2:
        cc_pop2[key] = pop
    else:
        cc_pop3[key] = pop

# Create world map with pygal
print(len(cc_pop1), len(cc_pop2), len(cc_pop3))
wm = World(style=RS('#17A589', base_style=LCS))
wm.title = 'World Population in 2010, by Country'
wm.add('0-5m', cc_pop1)
wm.add('5m-25m', cc_pop2)
wm.add('25m+', cc_pop3)
wm.render_to_file('world_pop.svg')
コード例 #12
0
ファイル: americas.py プロジェクト: enlambdment/my_pcc
from pygal.maps.world import World

wm = World()  # make an instance of the World class
wm.title = 'North, Central, and South America'  # set the map's 'title' attrib.

# each call to 'add' sets up a new color for the set of countries
# that it is invoked on, and adds that color to a key on the left of the graph.
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')
            population_data_2010.append(record)
        else:
            print("Error: " + record["Country Name"] + " is invalid")

# store in dictionary to be worked with pygal
# pops_1: population < 10000000
# pops_2: 10000000 <= population <= 1000000000
# pops_3: population > 1000000000
pops_1, pops_2, pops_3 = {}, {}, {}

for record in population_data_2010:
    cc = find_country_code(record["Country Name"])
    population = int(float(record["Value"]))
    if population < 10000000:
        pops_1[cc] = population
    elif population <= 1000000000:
        pops_2[cc] = population
    else:
        pops_3[cc] = population

# plot
world_population_map = World()
world_population_map.title = 'World Population Map'

world_population_map.add('< 10m', pops_1)
world_population_map.add('10m - 1bn', pops_2)
world_population_map.add('>1bn', pops_3)

world_population_map.render_to_file(
    'World Population Map (grouping countries by population).svg')
コード例 #14
0
def get_country_code(country_name):
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    return None


cc_populations = {}

for pop_dict in pop_data:
    country_name = pop_dict["Country Name"]
    population = pop_dict["Value"]
    code = get_country_code(country_name)
    if code:
        cc_populations[code] = population

cc_pop_lvl_1, cc_pop_lvl_2, cc_pop_lvl_3 = {}, {}, {}
for code, pop in cc_populations.items():
    if pop < 10000000:
        cc_pop_lvl_1[code] = pop
    elif pop < 1000000000:
        cc_pop_lvl_2[code] = pop
    else:
        cc_pop_lvl_3[code] = pop

worldmap_chart = World(style=LGS)
worldmap_chart.title = "2016 World Population by Country"
worldmap_chart.add("0-10m", cc_pop_lvl_1)
worldmap_chart.add("10m - 1bn", cc_pop_lvl_2)
worldmap_chart.add("1bn+", cc_pop_lvl_3)
worldmap_chart.render_in_browser()
コード例 #15
0
    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_populations[code] = population
        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 < 10000000:
        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_style = RotateStyle("#336699")
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")
コード例 #16
0
def render_svg_img(img_name, countries_info):
    wm = World()
    wm.title = 'Corona Cases Until 15-6-2020'
    wm.add("Corona Cases", countries_info)
    wm.render_to_file(f"{img_name}.svg")
コード例 #17
0
from pygal.maps.world import World

wm = World()
wm.force_uri_protocol = 'http'
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')
コード例 #18
0
        # if code is not None, add the data to the dictionary
        # print(countryName + ": " + '{:,}'.format(gdpValue))
        if code:
            ccGdp[code] = gdpValue

# to distinguish the countries from each other, we will have to put them in
# separate dictionaries to plot them separately
ccGdp1, ccGdp2, ccGdp3 = {}, {}, {}

# showing results in milliards is IMO better to see the real difference
# between the countries
for code, val in ccGdp.items():
    if val < 500000000000:
        ccGdp1[code] = round(val / 1000000000)
    elif val < 5000000000000:
        ccGdp2[code] = round(val / 1000000000)
    else:
        ccGdp3[code] = round(val / 1000000000)
'''print("over 5,000 mld countries: " + str(len(ccGdp3)))
print("500 - 5,000 mld countries: " + str(len(ccGdp2)))
print("below 500 mld countries: " + str(len(ccGdp1)))'''

# Create a map and fill it with data
wm = World(style=CleanStyle)
wm.title = "Countries GDP, 2016"
wm.add('over 5,000 mld', ccGdp3)
wm.add("500 - 5,000 mld", ccGdp2)
wm.add("below 500 mld", ccGdp1)

wm.render_to_file('world_gdp.svg')