<jupyter_start><jupyter_text>Catch-up session  Outline- Seaborn: moving a legend in a plot- Python functions Primer- Calling and using Python functions- Hard-coding stuff in a python function- Seaborn and matplotlib (Lab3B HA question)- Importing functions in a module<jupyter_code>import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

sns.set(font_scale=1.4)<jupyter_output><empty_output><jupyter_text>Seaborn - moving a legend<jupyter_code>sns.set_theme(style="ticks", palette="pastel")

# Load the example tips dataset
tips = sns.load_dataset("tips")

# Draw a nested boxplot to show bills by day and time
sns.boxplot(x="day", y="total_bill",
            hue="smoker", palette=["m", "g"],
            data=tips)
sns.despine(offset=10, trim=True)
plt.legend(loc='lower right',title='Smoking Status')

# Source: https://seaborn.pydata.org/examples/grouped_boxplot.html<jupyter_output><empty_output><jupyter_text>Put legend outside plot<jupyter_code># Draw a nested boxplot to show bills by day and time
sns.boxplot(x="day", y="total_bill",
            hue="smoker", palette=["m", "g"],
            data=tips)
sns.despine(offset=10, trim=True)
plt.legend(bbox_to_anchor=(0.9,0),
           title='Smoking Status')

# Source: https://seaborn.pydata.org/examples/grouped_boxplot.html
# Legend position Source: https://www.statology.org/seaborn-legend-position/<jupyter_output><empty_output><jupyter_text>Python Functions - Primer- syntax of creating a python function- "how to create your own .py file"- Arguments<jupyter_code># syntax of creating a python function

def magic_firas(num, print_evens = True):
    for i in range(num):
        if print_evens==True and i%2==0:
            print(i)
        elif i%2!=0:
            print(i)

# the function above, replaces all these functions below
# def magic_firas_5():
#     for i in range(5):
#         print(i)
        
# def magic_firas_6():
#     for i in range(6):
#         print(i)
magic_firas(num=20, print_evens = False)
# Remember to use the parameters that you ask for in a function definition

def load_and_process(path,encoding_input='ISO-5592'):
    # pd.read_csv('~/data301/project_repo/data/raw/test.csv') # This is wrong!!! Don't do this!
    pd.read_csv(path, encoding = encoding_input)<jupyter_output><empty_output><jupyter_text>plt.barh from Lab 3Using set() data type, find the all the different regions in df['HA']. In the next step, calculate the count of all cases in each of those regions. Finally, using plt.barh, plot a horizontal bar chart of number of cases based on their regions.Hint: More information and examples can be find in linkHint: Your plot doesn’t have to look exactly like this, but please do explore the possible color palettes. You can specify the colour palette by passing in the keyword like this: palette='colorblind'.<jupyter_code># load the data
df = pd.read_csv('http://www.bccdc.ca/Health-Info-Site/Documents/BCCDC_COVID19_Dashboard_Case_Details.csv')
df.head()
ha = list(df['HA'].unique())
ha
len(df[(df['HA']==ha[0]) & (df['Sex']=='M')])
ha_M = []
ha_F = []

for h in ha:
    print(h)
    ha_M.append(len(df[(df['HA']== h) & (df['Sex']=='M')]))
    ha_F.append(len(df[(df['HA']== h) & (df['Sex']=='F')]))
ha
ha_M
ha_F
y = np.arange(len(ha)) # Locations of health authorities
width = 0.35

fig, ax = plt.subplots()

ax.barh(y - width/2, ha_M,label='M')
ax.barh(y + width/2, ha_F,label='F')
ax.set_yticks(x)
ax.set_yticklabels(ha)
plt.legend()
sns.despine()
plt.title('This is a nice title')
# source: https://matplotlib.org/stable/gallery/lines_bars_and_markers/barchart.html
df['HA'].value_counts().index
fig, ax = plt.subplots(figsize=(6,6)) # how to change the figure size
sns.countplot(data=df,y='HA',hue='Sex', order = sorted(ha))
plt.xlabel('Count of Cases')
plt.ylabel('')
sns.despine()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13901113124514625, 'fraction_numerical': 0.00983691431529899, 'mean_word_length': 4.699115044247788, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '536994', 'license': 'MIT', 'n_tokens_mistral': 1414, 'n_tokens_neox': 1355, 'n_words': 363, 'path': 'notes/week08/Class8B/Class4B-questions.ipynb', 'repo_name': 'ubco-cmps/data301_course', 'size': '3863'}