<jupyter_start><jupyter_text>Data<jupyter_code>input_dict = [
    {'country':'Russia', 'hectares':69.5},
    {'country':'Brazil', 'hectares':59.8}, 
    {'country':'Canada', 'hectares':44.1},
    {'country':'USA', 'hectares':42.2},
    {'country':'Indonesia', 'hectares':27.7},
    {'country':'Congo', 'hectares':15.9}, 
    {'country':'China', 'hectares':10.3},
    {'country':'Australia', 'hectares':8.5},
    {'country':'Malaysia', 'hectares':8.4},
    {'country':'Paraguay', 'hectares':6.3},
]
df = pd.DataFrame(input_dict)
df
def get_label_value_list(df, value_column, label_column):
    df_ = df.copy().sort_values(value_column)
    value_list = df_[value_column].to_list()
    label_list = df_[label_column].to_list()
    return value_list, label_list

def fit_label_list(label_list):
    label_list = ['  '+ str(10-i)+'. '+label if i!=0 else str(10-i)+'. '+label 
                                            for i, label in enumerate(label_list) ]
    return label_list

value_list, label_list = get_label_value_list(df, 'hectares', 'country')
label_list = fit_label_list(label_list)

value_list, label_list<jupyter_output><empty_output><jupyter_text>Step 1<jupyter_code>bar_width = 0.6
color = '#357E12'
fig, ax = plt.subplots(figsize=(8, 6), dpi=200)
ax.barh(y=label_list, width=value_list, height=bar_width, color=color)

plt.tight_layout()
# plt.savefig('step1.png')
plt.show()<jupyter_output><empty_output><jupyter_text>Step 2<jupyter_code>bar_width = 0.6
color = '#357E12'
fig, ax = plt.subplots(figsize=(8, 6), dpi=200)
ax.barh(y=label_list, width=value_list, height=bar_width, color=color)

ax.tick_params(labelbottom=False, bottom=False, left=False, labelsize=10)    
ax.spines[['bottom', 'top', 'left', 'right']].set_visible(False)

plt.tight_layout()
# plt.savefig('step2.png')
plt.show()<jupyter_output><empty_output><jupyter_text>Step 3<jupyter_code>bar_width = 0.6
color = '#357E12'
fig, ax = plt.subplots(figsize=(8, 6), dpi=200)
ax.barh(y=label_list, width=value_list, height=bar_width, color=color)

offset = min(value_list)*0.1
for patch, yticklabel in zip(ax.patches, ax.get_yticklabels()):
    ax.text(patch.get_width() + offset,
            patch.get_y()+patch.get_height()/2,
            str(patch.get_width())+' million', 
            va="center", 
            fontsize=10)
    yticklabel.set_ha('left')
    yticklabel.set_position((-0.2, 0))
    
ax.tick_params(labelbottom=False, bottom=False, left=False, labelsize=10)    
ax.spines[['bottom', 'top', 'left', 'right']].set_visible(False)

plt.tight_layout()
# plt.savefig('step3.png')
plt.show()<jupyter_output><empty_output><jupyter_text>Step 4<jupyter_code>cols_1 = 'COUNTRY'
cols_2 = 'HECTARES OF TREE COVER LOST'
text_1 = 'Countries with most tree-cover loss, 2001-2020'
text_2 = 'Of the 10 countries that have lost the most tree cover since 2001, only two of them — Brazil \nand Paraguay — are Amazonian.'

bar_width = 0.6
color = '#357E12'
fig, ax = plt.subplots(figsize=(8, 6), dpi=200)
ax.barh(y=label_list, width=value_list, height=bar_width, color=color)

offset = min(value_list)*0.1
for patch, yticklabel in zip(ax.patches, ax.get_yticklabels()):
    ax.text(patch.get_width() + offset,
            patch.get_y()+patch.get_height()/2,
            str(patch.get_width())+' million', 
            va="center", 
            fontsize=10)
    yticklabel.set_ha('left')
    yticklabel.set_position((-0.2, 0))
    
ax.tick_params(labelbottom=False, bottom=False, left=False, labelsize=10)    
ax.spines[['bottom', 'top', 'left', 'right']].set_visible(False)

ax.annotate(text_2, xy=(0.025, 0.90), xycoords='figure fraction',)
ax.annotate(cols_1, xy=(0.050, 0.84), xycoords='figure fraction', fontweight="bold")
ax.annotate(cols_2, xy=(0.185, 0.84), xycoords='figure fraction', fontweight="bold")

plt.suptitle(text_1, fontsize=14, y=1, x=0.35, fontweight="bold")
plt.tight_layout()
# plt.savefig('step4.png')
plt.show()<jupyter_output><empty_output><jupyter_text>Step 5<jupyter_code>cols_1 = 'COUNTRY'
cols_2 = 'HECTARES OF TREE COVER LOST'
text_1 = 'Countries with most tree-cover loss, 2001-2020'
text_2 = 'Of the 10 countries that have lost the most tree cover since 2001, only two of them — Brazil \nand Paraguay — are Amazonian.'

bar_width = 0.6
color = '#357E12'
fig, ax = plt.subplots(figsize=(8, 6), dpi=200)
ax.barh(y=label_list, width=value_list, height=bar_width, color=color)

offset = min(value_list)*0.1
for patch, yticklabel in zip(ax.patches, ax.get_yticklabels()):
    ax.text(patch.get_width() + offset,
            patch.get_y()+patch.get_height()/2,
            str(patch.get_width())+' million', 
            va="center", 
            fontsize=10)
    yticklabel.set_ha('left')
    yticklabel.set_position((-0.2, 0))
    
ax.tick_params(labelbottom=False, bottom=False, left=False, labelsize=10)    
ax.spines[['bottom', 'top', 'left', 'right']].set_visible(False)

ax.annotate(text_2, xy=(0.025, 0.90), xycoords='figure fraction',)
ax.annotate(cols_1, xy=(0.050, 0.85), xycoords='figure fraction', fontweight="bold")
ax.annotate(cols_2, xy=(0.185, 0.85), xycoords='figure fraction', fontweight="bold")

l1 = lines.Line2D([0.01, 0.99], [0.835, 0.835], color='gray', transform=fig.transFigure, figure=fig, lw=0.5)
fig.lines.extend([l1])

i=0.755
while i>0.1:
    ll = lines.Line2D([0.01, 0.99], [i, i], color='gray', transform=fig.transFigure, figure=fig, lw=0.1)
    i -= 0.0785
    fig.lines.extend([ll])

plt.suptitle(text_1, fontsize=14, y=1, x=0.35, fontweight="bold")
plt.tight_layout()
# plt.savefig('step5.png')
plt.show()<jupyter_output><empty_output><jupyter_text>All Steps together<jupyter_code>def plot_barh(value_list, label_list, column_1, column_2, column_text, save_plot=False):
    text_1 = 'Countries with most tree-cover loss, 2001-2020'
    text_2 = 'Of the 10 countries that have lost the most tree cover since 2001, only two of them — Brazil \nand Paraguay — are Amazonian.'

    bar_width = 0.6
    color = '#357E12'
    fig, ax = plt.subplots(figsize=(8, 6), dpi=200)
    ax.barh(y=label_list, width=value_list, height=bar_width, color=color)

    offset = min(value_list)*0.1
    for patch, yticklabel in zip(ax.patches, ax.get_yticklabels()):
        ax.text(patch.get_width() + offset,
                patch.get_y()+patch.get_height()/2,
                str(patch.get_width())+column_text, 
                va="center", 
                fontsize=10)
        yticklabel.set_ha('left')
        yticklabel.set_position((-0.2, 0))

    ax.tick_params(labelbottom=False, bottom=False, left=False, labelsize=10)    
    ax.spines[['bottom', 'top', 'left', 'right']].set_visible(False)

    ax.annotate(text_2, xy=(0.025, 0.90), xycoords='figure fraction',)
    ax.annotate(column_1, xy=(0.050, 0.85), xycoords='figure fraction', fontweight="bold")
    ax.annotate(column_2, xy=(0.185, 0.85), xycoords='figure fraction', fontweight="bold")

    l1 = lines.Line2D([0.01, 0.99], [0.835, 0.835], color='gray', transform=fig.transFigure, figure=fig, lw=0.5)
    fig.lines.extend([l1])

    i=0.755
    while i>0.1:
        ll = lines.Line2D([0.01, 0.99], [i, i], color='gray', transform=fig.transFigure, figure=fig, lw=0.1)
        i -= 0.0785
        fig.lines.extend([ll])

    plt.suptitle(text_1, fontsize=14, y=1, x=0.35, fontweight="bold")
    plt.tight_layout()
    if save_plot:
        plt.savefig('images/barh_plot.png')
    plt.show()
cols_1 = 'COUNTRY'
cols_2 = 'HECTARES OF TREE COVER LOST'
col_text = ' million'
plot_barh(value_list, label_list, cols_1, cols_2, column_text=col_text, save_plot=True)<jupyter_output><empty_output><jupyter_text>Bonus<jupyter_code>land_area_path = 'data/land_area.csv'
df_land = pd.read_csv(land_area_path, skiprows=4)[['Country Name', '2020']]
replace_country = {
    "United States":"USA",
    "Congo, Dem. Rep.":"Congo",
    "Russian Federation":"Russia",
}
df_land["Country Name"] = df_land["Country Name"].replace(replace_country)
df_land
df_ = df.merge(df_land, left_on='country', right_on='Country Name').copy()\
        .rename(columns={'2020':'square'})
df_ = df_.drop('Country Name', axis=1)
df_['square_ha'] = df_['square']/0.01/1000000
df_['hectares_per_square'] = (df_['hectares']/df_['square_ha']*100).apply(lambda x: round(x, 2))
df_
value_list_b, label_list_b = get_label_value_list(df_, 'hectares_per_square', 'country')
label_list_b = fit_label_list(label_list_b)

value_list_b, label_list_b
cols_1 = 'COUNTRY'
cols_2 = 'PERCENT OF TREE COVER LOSS OF TOTAL AREA'
col_text = ' '
plot_barh(value_list_b, label_list_b, column_1=cols_1, column_2=cols_2, column_text=col_text, save_plot=False)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17067503195073777, 'fraction_numerical': 0.04821656790984083, 'mean_word_length': 4.754010695187166, 'pattern_counts': {'":': 3, '<': 33, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '373602', 'license': 'MIT', 'n_tokens_mistral': 3607, 'n_tokens_neox': 3354, 'n_words': 588, 'path': 'Chapter-2-BarhPlot.ipynb', 'repo_name': 'PetroIvaniuk/homemade-visualization', 'size': '8607'}