Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Wed May 13 17:44:05 2020
- @author: jerem
- """
- def add_age_range(data):
- age_range_list = []
- is_nan = lambda x : x != x
- for i in range(len(data)):
- if is_nan(data['Idade'][i]):
- age_range_list.append('Não Informado')
- elif data['Idade'][i] < 10:
- age_range_list.append('0 a 9 anos')
- elif data['Idade'][i] < 20:
- age_range_list.append('10 a 19 anos')
- elif data['Idade'][i] < 30:
- age_range_list.append('20 a 29 anos')
- elif data['Idade'][i] < 40:
- age_range_list.append('30 a 39 anos')
- elif data['Idade'][i] < 50:
- age_range_list.append('40 a 49 anos')
- elif data['Idade'][i] < 60:
- age_range_list.append('50 a 59 anos')
- elif data['Idade'][i] < 70:
- age_range_list.append('60 a 69 anos')
- elif data['Idade'][i] < 80:
- age_range_list.append('70 a 79 anos')
- elif data['Idade'][i] >= 80:
- age_range_list.append('80 anos ou mais')
- data['Faixa Etária'] = age_range_list
- def get_data(path='D:/Documents/Github/covid-19/todos_os_casos.csv', county='Garrafão do Norte'):
- sex = {'Homem':'Masculino', 'Mulher':'Feminino'}
- if path != None and county != None:
- raw_data = pd.read_csv(path, index_col=False)
- ct_data = raw_data[raw_data['Município'] == county]
- #ct_data = ct_data.replace(sex)
- ct_data= ct_data.reset_index()
- add_age_range(ct_data)
- return ct_data
- else:
- print('No path or county name passed!')
- #%%
- def pyr_pop(data):
- global county_name
- my_text = 'Fonte dos dados: SESPA\ncovid-19.pa.gov.br\nFeito por Jeremias Abreu\n'+dt_string
- sex = list(data['Sexo'].unique())
- sex1 = data[data['Sexo'] == sex[0]].reset_index()
- sex2 = data[data['Sexo'] == sex[1]].reset_index()
- order_of_bars = ['0 a 9 anos', '10 a 19 anos', '20 a 29 anos',
- '30 a 39 anos', '40 a 49 anos', '50 a 59 anos',
- '60 a 69 anos', '70 a 79 anos', '80 anos ou mais',
- 'Não Informado']
- c1 = dict(Counter(sex1['Faixa Etária']))
- c2 = dict(Counter(sex2['Faixa Etária']))
- sex_df = pd.DataFrame()
- sex_df['age range'] = list(c1.keys())
- sex_df['freq'] = list(c1.values())
- sex_df['sex'] = [sex[0] for i in range(len(c1))]
- for age, freq, sex in zip(list(c2.keys()), list(c2.values()), [sex[1] for i in range(len(c1))]):
- sex_df = sex_df.append({'age range': age, 'freq':freq, 'sex':sex}, ignore_index=True)
- plt.figure(figsize=(15,10))
- ax = sns.barplot(y='age range', x='freq', hue='sex', data=sex_df,
- order=order_of_bars, palette='Spectral')
- m1 = max(list(c1.values()))
- m2 = max(list(c2.values()))
- y_pos_text = max(m1, m2) + 1
- plt.xlabel('Número de Casos Confirmados', fontsize=30)
- plt.ylabel('Faixa Etária', fontsize=30)
- plt.yticks(fontsize=25)
- plt.xticks(fontsize=25)
- plt.title('Distribuição etária dos casos confirmados em '+county_name, fontsize=40, pad=20, loc='center')
- plt.legend(loc='lower right', fontsize=40)
- plt.grid()
- plt.text(y_pos_text, 9, my_text, fontsize=30)
- plt.savefig('D:/Documents/Github/covid-19/figures/distribuicao-etaria-'+ \
- county_name[:5]+'.png', dpi=100, bbox_inches='tight')
- plt.show()
- #%%
- def pie(data):
- global dt_string
- my_text = 'Fonte dos dados: SESPA\ncovid-19.pa.gov.br\nFeito por Jeremias Abreu\n'+dt_string
- pie_data = {'Homem':len(data[data['Sexo'] == 'Homem']),
- 'Mulher':len(data[data['Sexo'] == 'Mulher'])}
- fix, ax = plt.subplots()
- wedges, text, autotexts = ax.pie(list(pie_data.values()), labels=list(pie_data.keys()),
- autopct='%1.1f%%', shadow=True, startangle=90, explode=[0,0.1],
- colors=['tab:blue', 'tab:orange'])
- ax.axis('equal')
- plt.setp(autotexts, size=30, weight='bold')
- plt.setp(text, size=30, weight='bold')
- ax.set_title(r'Casos Confirmados Por Sexo em '+ \
- county_name + r' (%)', fontsize=30)
- ax.text(1.15, -0.95, my_text,
- fontsize=20)
- plt.savefig('D:/Documents/Github/covid-19/figures/pie-sex-'+ \
- county_name[:5]+'.png', dpi=100, bbox_inches='tight')
- plt.show()
- #%%
- def statistics(data):
- pass
- if __name__ == '__main__':
- import pandas as pd
- import matplotlib.pyplot as plt
- import seaborn as sns
- import os
- import numpy as np
- from collections import Counter
- from datetime import datetime
- now = datetime.now()
- dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
- print(os.getcwd())
- os.chdir(r'D:\Documents\Github\covid-19')
- # =============================================================================
- # large = 22; med = 16; small = 12
- # params = {'axes.titlesize': large,
- # 'legend.fontsize': med,
- # 'figure.figsize': (16, 10),
- # 'axes.labelsize': med,
- # 'axes.titlesize': med,
- # 'xtick.labelsize': med,
- # 'ytick.labelsize': med,
- # 'figure.titlesize': large}
- # plt.rcParams.update(params)
- # =============================================================================
- plt.style.use('seaborn-whitegrid')
- sns.set_style("white")
- county_name = 'Capitão Poço'
Add Comment
Please, Sign In to add comment