<jupyter_start><jupyter_text>Bar charts of the number of countries in each '14-day new case rate' group over timeCountries with a population over 5M<jupyter_code>df=pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv')

df_pvt=df.pivot(index='date', columns='iso_code', values='new_cases').fillna(0.)
df_pvt.tail()

#sorted list of countries with a population over 5M
ctries=df[df.date=='2020-10-16'][df.population>=5000000][['iso_code', 'population']].sort_values('population', ascending=False).iso_code.to_list()[1:]
ctries[:10]
df_pvt[ctries].tail()
df_14_day=pd.DataFrame()
for col in df_pvt[ctries].columns:
  df_14_day[col]=df_pvt[col].rolling(window=14).sum()

df_14_day.fillna(0., inplace=True)

for col in df_14_day.columns:
  popn=(df.loc[(df.date=='2020-10-01') & (df.iso_code==col), 'population']/100000).values
  if len(popn) > 0:
    df_14_day[col]=df_14_day[col]/popn
  else:
    print (col)

df_14_day = df_14_day.T
df_14_day.head()
df_14_day.loc['CHN']
# Histogram
fig = plt.figure(figsize=(16,7))
sns.set_context('notebook')
sns.set_style('whitegrid')
sns.histplot(df_14_day['2020-10-18'], bins=[0,20,60,120,240,480,1000])
plt.xticks([20,60,120,240,480,1000])
plt.xlim([0,1000])
plt.tight_layout();
def allocate_to_groups(x):
  if x<20:
    return '<20'
  elif x<60:
    return '20-59.9'
  elif x<120:
   return '60-119.9'
  elif x<240:
    return '120-239.9'
  elif x<480:
    return '240-479.9'
  return '>480'
date=df_14_day.columns[-1]
day_df=pd.DataFrame(df_14_day[date])
day_df['group']=day_df[date].apply(lambda x: allocate_to_groups(x))
day_df[day_df.group=='>480']
day_df.loc['ESP']<jupyter_output><empty_output><jupyter_text>Daily barplots<jupyter_code>for date in df_14_day.columns[[-i-1 for i in range((pd.to_datetime(df_14_day.columns[-1])-pd.to_datetime('2020-04-30')).days)][::-1]]:
#for date in ['2020-05-19']:

  day_df=pd.DataFrame(df_14_day[date])
  day_df['group']=day_df[date].apply(lambda x: allocate_to_groups(x))

  fig, ax = plt.subplots(figsize=(10, 6))
  sns.set_context('talk')
  sns.set_style('whitegrid')
  plot=sns.barplot(x=['<20','20-59.9','60-119.9','120-239.9','240-479.9','>480'], 
                   y=(list(day_df.group.value_counts().values)+[0, 0])[:6], 
                   palette=['lemonchiffon','yellow','orange','sandybrown','brown','red'])
  
  for rect in plot.patches:
    height = rect.get_height().astype(int)
    ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
  ax.annotate('{}'.format(date), xy=(4,103))

  plt.title('Countries in each group of COVID19 new cases rate')
  plt.ylabel('Number of countries')
  plt.xlabel('\n14-day COVID19 case notification rate per 100 000 population')
  plt.ylim(0,110)
  plt.tight_layout()
  plt.savefig('./world_cartogram/pngs_bar/'+date, dpi=150)
  if date==df_14_day.columns[-1]: plt.show()
  plt.close();<jupyter_output><empty_output><jupyter_text>Make 'gif'<jupyter_code>!pip install pygifsicle 
!apt install gifsicle
import os
import imageio
from pygifsicle import optimize
png_dir = '/content/drive/My Drive/TrueCue/world_cartogram/pngs_bar/'
images = []

for file_name in sorted(os.listdir(png_dir)):
    if file_name.endswith('.png'):
        file_path = os.path.join(png_dir, file_name)
        images.append(imageio.imread(file_path))

imageio.mimwrite('./world_cartogram/bar.gif', images, format='.gif', fps=20, loop=1)
optimize('./world_cartogram/bar.gif')<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup