datapartnership / lebanon-economic-monitor

Understanding Lebanon's Economy through Alternative Data
https://datapartnership.org/lebanon-economic-monitor/
Mozilla Public License 2.0
0 stars 2 forks source link

Issue on page /notebooks/aviation-trends/aviation.html #58

Open Jagbakpe opened 6 months ago

Jagbakpe commented 6 months ago

### Suggested comments

Creates a figure with 1 row and 2 columns of subplots, setting the figure size

fig, axs = plt.subplots(1, 2, figsize=(15, 5))

Sets font family for the entire plot

plt.rcParams["font.family"] = "Georgia"

Plots the total ask (total number of seats available) on the first subplot

axs[0].bar(x=inbound_flights_mena_monthly_ask['date'], # X values (dates) height=inbound_flights_mena_monthly_ask['total_ask'], # Heights of bars (total ask) width=20) # Width of bars

Plots the total payload (total weight of cargo) on the second subplot

axs[1].bar(x=inbound_flights_mena_monthly_ask['date'], # X values (dates) height=inbound_flights_mena_monthly_ask['total_payload'], # Heights of bars (total payload) width=20) # Width of bars

Loops through each subplot

for ax in axs:

Hide the right and top spines (axis lines)

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

# Only shows ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

# Adds gridlines to both major and minor ticks
ax.grid(which='both', linestyle='--', linewidth=0.5, color='gray', alpha=0.7)

# Sets titles for each subplot
axs[0].set_title('Average payload on Inbound Flights to Lebanon', font='Georgia', fontsize=12)
axs[1].set_title('Average Available Seat Kilometres on Inbound Flights to Lebanon', font='Georgia', fontsize=12)

# Sets x-label for each subplot
ax.set_xlabel('Month')

# Sets y-label for each subplot
axs[0].set_ylabel('Average payload (kg)')
axs[1].set_ylabel('Average Available Seat Kilometres')

Adds a subtitle to the first subplot

subtitle = 'Source: Global Aviation Dashboard (World Bank)' axs[0].text(0, -0.15, subtitle, ha='left', va='center', transform=axs[0].transAxes, fontsize=10, color='black', weight='normal')

Creates a figure with 2 rows and 1 column of subplots, setting the figure size

fig, axs = plt.subplots(2, 1, figsize=(10, 10))

Sets font family for the entire plot

plt.rcParams["font.family"] = "Georgia"

Plots the total number of seats on inbound flights monthly on the first subplot

axs[0].bar(x=inbound_flights_mena_monthly_all['date'], # X values (dates) height=inbound_flights_mena_monthly_all['total_seats'], # Heights of bars (total seats) width=20) # Width of bars

Plots the total number of seats on inbound flights yearly on the second subplot

axs[1].bar(x=inbound_flights_mena_yearly_all['date'], # X values (years) height=inbound_flights_mena_yearly_all['total_seats'], # Heights of bars (total seats) width=30) # Width of bars

Loops through each subplot

for ax in axs:

Hides the right and top spines (axis lines)

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

# Only shows ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

# Adds gridlines to both major and minor ticks
ax.grid(which='both', linestyle='--', linewidth=0.5, color='gray', alpha=0.7)

# Sets title for the first subplot
axs[0].set_title('Number of Seats on Inbound Flights to Lebanon (Monthly)', font='Georgia', fontsize=12)
# Sets title for the second subplot
axs[1].set_title('Number of Seats on Inbound Flights to Lebanon (Yearly)', font='Georgia', fontsize=12)

# Sets x-label for each subplot
ax.set_xlabel('Month' if ax == axs[0] else 'Year')

# Sets y-label for each subplot
ax.set_ylabel('Number of seats (in thousands)')

Adds a subtitle to the second subplot

subtitle = 'Source: Global Aviation Dashboard (World Bank)' axs[1].text(0, -0.15, subtitle, ha='left', va='center', transform=axs[1].transAxes, fontsize=10, color='black', weight='normal')

Imports necessary libraries

import numpy as np import matplotlib.patches as mpatches

df: DataFrame containing data about top categories and seats

sorted_df: DataFrame sorted by date and total seats in descending order

df = top_categories_seats sorted_df = df.sort_values(by=['date', 'total_seats'], ascending=[True, False])

Gets unique years

years = sorted_df['date'].unique()

Creats a figure and axis object

fig, ax = plt.subplots(figsize=(8, 6)) bar_width = 0.5 # Width of the bars colors = ['#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#42d4f4', '#f032e6', '#bfef45', '#fabed4'] # List of colors for the bars

Plots each category for each year

for i, year in enumerate(years): bottom = np.zeros(len(years)) # Initializes the bottom values for stacked bars sorted_df = df[df['date'] == year].sort_values(by='total_seats', ascending=False) # Sorts the data for the current year

# Gets unique categories for the current year
categories = sorted_df['origin_country'].unique()

# Plots each category for the current year
for j, category in enumerate(categories):
    # Gets the total seats for the current category and year
    value = sorted_df[(sorted_df['date'] == year) & (sorted_df['origin_country'] == category)]['total_seats'].sum()
    if value > 0:
        # Plots a bar for the current category and year, with stacking
        ax.bar(year, value, bar_width, bottom=bottom[i], color=country_color_map[category], label=category if i == 0 else "")
        bottom[i] += value  # Updates the bottom value for stacking

Sets axis labels

ax.set_xlabel('Year') ax.set_ylabel('Number of seats (in thousands)')

Creates legend patches for each country

legend_patches = [mpatches.Patch(color=color, label=country) for country, color in country_color_map.items()]

Adds legend to the plot

ax.legend(handles=legend_patches, loc='upper center', frameon=False, bbox_to_anchor=(1.15, 1))

Customizes plot aesthetics

ax.spines['right'].set_visible(False) # Hides the right spine ax.spines['top'].set_visible(False) # Hides the top spine ax.yaxis.set_ticks_position('left') # Shows ticks only on the left spine ax.xaxis.set_ticks_position('bottom') # Shows ticks only on the bottom spine ax.grid(which='both', linestyle='--', linewidth=0.5, color='gray', alpha=0.7) # Add gridlines

Sets plot title and rotation for x-axis ticks

ax.set_title('Top 5 countries with number of inbound flight seats') plt.xticks(rotation=0)

Adds a subtitle to the plot

subtitle = 'Source: Global Aviation Dashboard (World Bank)' ax.text(0, -0.15, subtitle, ha='left', va='center', transform=ax.transAxes, fontsize=10, color='black', weight='normal')

g4brielvs commented 5 months ago

@Jagbakpe Thank you for contributing. Would you consider opening a pull request with your proposed changes? See CONTRIBUTING.