text_html_output_1.png
import matplotlib.pyplot as plt

import pandas as pd

import seaborn as sns

df_medal = pd.read_csv('../input/beijing-2022-olympics/medals.csv')
df_total_medals = pd.read_csv('../input/beijing-2022-olympics/medals_total.csv')
df_events = pd.read_csv('../input/beijing-2022-olympics/events.csv')
df_athletes = pd.read_csv('../input/beijing-2022-olympics/athletes.csv')
s_athletes = pd.read_excel('../input/2021-olympics-in-tokyo/Athletes.xlsx')

d_start = pd.to_datetime(df_events['time'][0])
d_end = pd.to_datetime(df_events['time'][len(df_events) - 1])
days = d_end - d_start
df_og = pd.DataFrame()
competition = ['Summer', 'Winter']
nb_discipline = []
nb_country = []
nb_athlete = []
nb_discipline.append(len(s_athletes['Discipline'].unique()))
nb_discipline.append(len(df_medal['discipline'].unique()))
nb_country.append(len(s_athletes['NOC'].unique()))
nb_country.append(len(df_athletes['country'].unique()))
nb_athlete.append(len(s_athletes['Name'].unique()))
nb_athlete.append(len(df_athletes['name'].unique()))
df_og['competition'] = competition
df_og['disciplines'] = nb_discipline
df_og['countries'] = nb_country
df_og['athletes'] = nb_athlete
df_og
df_og.style.set_caption('Summer vs Winter')

cols = ['medal_type', 'event', 'country', 'discipline']
df_medal = df_medal[cols]
countries = df_total_medals['Country']
nb_d = []
df_medal.drop_duplicates()
for country in countries:
    temp = df_medal.drop_duplicates()[df_medal.drop_duplicates()['country'] == country]
    temp_2 = temp['discipline']
    temp_2 = temp_2.drop_duplicates()
    nb_d.append(len(temp_2))
df_total_medals['Discipline'] = nb_d

columns = ['Order', 'Country', 'Bronze', 'Silver', 'Gold', 'Total', 'Order by Total', 'Country Code', 'Discipline']
df_total_medals = df_total_medals.reindex(columns=columns)

# Medals barplot
df_total_medals = df_total_medals.sort_index(ascending=False)

# figure prep
plt.rcParams['figure.dpi'] = 200 # figure dots per inch
fig = plt.figure(figsize=(3,30), facecolor='#f6f5f5')
gs = fig.add_gridspec(1, 1)
gs.update(wspace=1.5, hspace=0.05)

background_color = "#f6f5f5"
sns.set_palette(['#D8392B','#CD7F32','#C0C0C0','#FFD700'])
ax0 = fig.add_subplot(gs[0, 0])

for s in ["right", "top"]:
    ax0.spines[s].set_visible(False)
    
ax0.set_facecolor(background_color)

#things to plot on the figure
ax0_sns = df_total_medals.plot(x='Country',y=['Discipline','Bronze','Silver','Gold'],kind='barh',ax=ax0,zorder=2,width=0.8)
ax0_sns.set_xlabel('Medals Count',fontsize=4, weight='bold')
ax0_sns.set_ylabel('Team Name',fontsize=4, weight='bold')

ax0_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE', linewidth=0.4)
ax0_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE', linewidth=0.4)

ax0_sns.tick_params(labelsize=3, width=0.5, length=1.5)
ax0_sns.legend(['Discipline','Bronze', 'Silver','Gold'], ncol=4, facecolor='#D8D8D8'\
               ,edgecolor=background_color, fontsize=3, bbox_to_anchor=(1, 1.005), loc='upper right')

for p in ax0_sns.patches:
        value = f'{p.get_width():.0f}' 
        if value == '0':
            pass
        else:
            x = p.get_x() + p.get_width() + 1
            y = p.get_y() + p.get_height() / 2
            ax0.text(x, y, value, ha='left', va='center', fontsize=3)

Xstart, Xend = ax0.get_xlim()
Ystart, Yend = ax0.get_ylim()

ax0_sns.text(Xend-1, Yend+0.3, f'Medals Table', fontsize=6, weight='bold',ha='right')

plt.show()

athletes = pd.read_csv('../input/beijing-2022-olympics/athletes.csv')
athletes = athletes.rename(columns={'discipline': 'Discipline', 'country': 'Country'})
cols = ['gender', 'Discipline']
gender = athletes[cols]

gender['M'] = 0
gender['F'] = 0
i = 0
while i < len(gender['gender']):
    if gender['gender'][i] == 'Male':
        gender['M'][i] = 1
    else:
        gender['F'][i] = 1
    i += 1
gender['Male'] = gender.groupby('Discipline')['M'].transform('sum')
gender['Female'] = gender.groupby('Discipline')['F'].transform('sum')
del gender['gender']
del gender['M']
del gender['F']
gender = gender.drop_duplicates()
gender = gender.iloc[:-1, :]
gender['Total'] = gender['Male'] + gender['Female']
total_male = int(gender['Male'].sum())
total_female = int(gender['Female'].sum())

gender.sort_values(by='Total',inplace=True)

# Gender barplot
plt.rcParams['figure.dpi'] = 300

fig = plt.figure(figsize=(2,5), facecolor='#f6f5f5')
gs = fig.add_gridspec(1, 1)
gs.update(wspace=1.5, hspace=0.05)

background_color = "#f6f5f5"
sns.set_palette(['#87ceeb','#ff355d'])
ax0 = fig.add_subplot(gs[0, 0])

for s in ["right", "top"]:
    ax0.spines[s].set_visible(False)
    
ax0.set_facecolor(background_color)

ax0_sns = gender.plot(x='Discipline',y=['Male','Female'],kind='barh',ax=ax0,zorder=2,width=0.8) ##plotttt of bars
ax0_sns.set_xlabel('Genders Count',fontsize=4, weight='bold',)
ax0_sns.set_ylabel('Discipline',fontsize=4, weight='bold')

ax0_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE', linewidth=0.4)
ax0_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE', linewidth=0.4)

ax0_sns.tick_params(labelsize=3, width=0.5, length=1.5) # w and l of petit trait de mesure de l'axe x et y

ax0_sns.legend(['Male', 'Female'], ncol=2, facecolor='#D8D8D8', edgecolor=background_color, fontsize=3, bbox_to_anchor=(1, 1.03), loc='upper right')

for p in ax0_sns.patches:
            value = f'{p.get_width():.0f}'
            if value == '0':
                pass
            else:
                x = p.get_x() + p.get_width() + 20
                y = p.get_y() + p.get_height() / 2 
                ax0.text(x, y, value, ha='left', va='center', fontsize=3, 
                        bbox=dict(facecolor='none', edgecolor='black', boxstyle='round', linewidth=0.3))

ax0_sns.text(300,16, f'Gender Plot', fontsize=6, weight='bold',ha='right')
ax0.text(480, 15.5,f'Entries by Discipline and number of females and males taking part in it',fontsize=3,ha='right')

plt.show()

cols = ['Country', 'Discipline']
athletes = athletes[cols]

y = athletes.Country.value_counts().index
x = athletes.Country.value_counts().values
plt.rcParams['figure.dpi'] = 300
fig = plt.figure(figsize=(2, 48), facecolor='#f6f5f5')
gs = fig.add_gridspec(1, 1)
gs.update(wspace=1.5, hspace=0.05)
background_color = '#f6f5f5'
sns.set_palette(['#bca6cf'] * 1200)
ax0 = fig.add_subplot(gs[0, 0])
for s in ['right', 'top']:
    ax0.spines[s].set_visible(False)
ax0.set_facecolor(background_color)
ax0_sns = sns.barplot(data=athletes, y=y, x=x, zorder=2)
ax0_sns.set_xlabel('No of Athletes', fontsize=4, weight='bold')
ax0_sns.set_ylabel('Countries', fontsize=4, weight='bold')
ax0_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE', linewidth=0.4)
ax0_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE', linewidth=0.4)
ax0_sns.tick_params(labelsize=3, width=0.5, length=1.5)
for p in ax0_sns.patches:
    value = f'{p.get_width():.0f}'
    x = p.get_x() + p.get_width() + 20
    y = p.get_y() + p.get_height() / 2
    ax0.text(x, y, value, ha='left', va='center', fontsize=3, bbox=dict(facecolor='none', edgecolor='black', boxstyle='round', linewidth=0.3))
ax0_sns.text(150, -1.6, f'Athletes Plot', fontsize=6, weight='bold', ha='right')
ax0.text(175, -1.3, f'Contains details about the participating Athletes', fontsize=3, ha='right')
plt.show()