Jeremiah_

covid-19

May 14th, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.50 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed May 13 17:44:05 2020
  4.  
  5. @author: jerem
  6. """
  7.  
  8. def add_age_range(data):
  9.     age_range_list = []
  10.     is_nan = lambda x : x != x
  11.     for i in range(len(data)):
  12.         if is_nan(data['Idade'][i]):
  13.             age_range_list.append('Não Informado')
  14.         elif data['Idade'][i] < 10:
  15.             age_range_list.append('0 a 9 anos')
  16.         elif data['Idade'][i] < 20:
  17.             age_range_list.append('10 a 19 anos')
  18.         elif data['Idade'][i] < 30:
  19.             age_range_list.append('20 a 29 anos')
  20.         elif data['Idade'][i] < 40:
  21.             age_range_list.append('30 a 39 anos')
  22.         elif data['Idade'][i] < 50:
  23.             age_range_list.append('40 a 49 anos')
  24.         elif data['Idade'][i] < 60:
  25.             age_range_list.append('50 a 59 anos')
  26.         elif data['Idade'][i] < 70:
  27.             age_range_list.append('60 a 69 anos')
  28.         elif data['Idade'][i] < 80:
  29.             age_range_list.append('70 a 79 anos')
  30.         elif data['Idade'][i] >= 80:
  31.             age_range_list.append('80 anos ou mais')
  32.     data['Faixa Etária'] = age_range_list
  33.  
  34. def get_data(path='D:/Documents/Github/covid-19/todos_os_casos.csv', county='Garrafão do Norte'):
  35.    
  36.     sex = {'Homem':'Masculino', 'Mulher':'Feminino'}
  37.    
  38.     if path != None and county != None:
  39.       raw_data = pd.read_csv(path, index_col=False)
  40.       ct_data = raw_data[raw_data['Município'] == county]
  41.       #ct_data = ct_data.replace(sex)
  42.       ct_data= ct_data.reset_index()
  43.       add_age_range(ct_data)
  44.       return ct_data
  45.     else:
  46.         print('No path or county name passed!')
  47.  
  48.  
  49.      
  50.  
  51. #%%
  52.  
  53. def pyr_pop(data):
  54.     global county_name
  55.     my_text = 'Fonte dos dados: SESPA\ncovid-19.pa.gov.br\nFeito por Jeremias Abreu\n'+dt_string
  56.    
  57.     sex = list(data['Sexo'].unique())
  58.    
  59.     sex1 = data[data['Sexo'] == sex[0]].reset_index()
  60.     sex2 = data[data['Sexo'] == sex[1]].reset_index()
  61.    
  62.     order_of_bars = ['0 a 9 anos', '10 a 19 anos', '20 a 29 anos',
  63.                  '30 a 39 anos', '40 a 49 anos', '50 a 59 anos',
  64.                  '60 a 69 anos', '70 a 79 anos', '80 anos ou mais',
  65.                  'Não Informado']
  66.    
  67.     c1 = dict(Counter(sex1['Faixa Etária']))
  68.     c2 = dict(Counter(sex2['Faixa Etária']))
  69.    
  70.    
  71.     sex_df = pd.DataFrame()
  72.    
  73.     sex_df['age range'] = list(c1.keys())
  74.     sex_df['freq'] = list(c1.values())
  75.     sex_df['sex'] = [sex[0] for i in range(len(c1))]
  76.    
  77.     for age, freq, sex in zip(list(c2.keys()), list(c2.values()), [sex[1] for i in range(len(c1))]):
  78.         sex_df = sex_df.append({'age range': age, 'freq':freq, 'sex':sex}, ignore_index=True)
  79.    
  80.     plt.figure(figsize=(15,10))
  81.    
  82.     ax = sns.barplot(y='age range', x='freq', hue='sex', data=sex_df,
  83.                      order=order_of_bars, palette='Spectral')
  84.     m1 = max(list(c1.values()))
  85.     m2 = max(list(c2.values()))
  86.     y_pos_text = max(m1, m2) + 1
  87.     plt.xlabel('Número de Casos Confirmados', fontsize=30)
  88.     plt.ylabel('Faixa Etária', fontsize=30)
  89.     plt.yticks(fontsize=25)
  90.     plt.xticks(fontsize=25)
  91.     plt.title('Distribuição etária dos casos confirmados em '+county_name, fontsize=40, pad=20, loc='center')
  92.     plt.legend(loc='lower right', fontsize=40)
  93.     plt.grid()
  94.     plt.text(y_pos_text, 9, my_text, fontsize=30)
  95.     plt.savefig('D:/Documents/Github/covid-19/figures/distribuicao-etaria-'+ \
  96.                 county_name[:5]+'.png', dpi=100, bbox_inches='tight')
  97.     plt.show()
  98. #%%
  99.  
  100. def pie(data):
  101.     global dt_string
  102.     my_text = 'Fonte dos dados: SESPA\ncovid-19.pa.gov.br\nFeito por Jeremias Abreu\n'+dt_string
  103.     pie_data = {'Homem':len(data[data['Sexo'] == 'Homem']),
  104.                 'Mulher':len(data[data['Sexo'] == 'Mulher'])}
  105.     fix, ax = plt.subplots()
  106.     wedges, text, autotexts = ax.pie(list(pie_data.values()), labels=list(pie_data.keys()),
  107.             autopct='%1.1f%%', shadow=True, startangle=90, explode=[0,0.1],
  108.             colors=['tab:blue', 'tab:orange'])
  109.     ax.axis('equal')
  110.     plt.setp(autotexts, size=30, weight='bold')
  111.     plt.setp(text, size=30, weight='bold')
  112.     ax.set_title(r'Casos Confirmados Por Sexo em '+ \
  113.                  county_name + r' (%)', fontsize=30)
  114.     ax.text(1.15, -0.95, my_text,
  115.             fontsize=20)
  116.     plt.savefig('D:/Documents/Github/covid-19/figures/pie-sex-'+ \
  117.                 county_name[:5]+'.png', dpi=100, bbox_inches='tight')
  118.     plt.show()
  119.  
  120. #%%
  121.  
  122.  
  123. def statistics(data):
  124.     pass
  125.  
  126.  
  127.  
  128.  
  129.  
  130. if __name__ == '__main__':
  131.     import pandas as pd
  132.     import matplotlib.pyplot as plt
  133.     import seaborn as sns
  134.     import os
  135.     import numpy as np
  136.     from collections import Counter
  137.     from datetime import datetime
  138.  
  139.     now = datetime.now()
  140.    
  141.     dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
  142.    
  143.     print(os.getcwd())
  144.     os.chdir(r'D:\Documents\Github\covid-19')
  145.    
  146. # =============================================================================
  147. #     large = 22; med = 16; small = 12
  148. #     params = {'axes.titlesize': large,
  149. #               'legend.fontsize': med,
  150. #               'figure.figsize': (16, 10),
  151. #               'axes.labelsize': med,
  152. #               'axes.titlesize': med,
  153. #               'xtick.labelsize': med,
  154. #               'ytick.labelsize': med,
  155. #               'figure.titlesize': large}
  156. #     plt.rcParams.update(params)
  157. # =============================================================================
  158.     plt.style.use('seaborn-whitegrid')
  159.     sns.set_style("white")
  160.    
  161.     county_name = 'Capitão Poço'
Add Comment
Please, Sign In to add comment