In [1]:
import pandas as pd
import plotly.express as px
from IPython.display import display, HTML
def hide_code_toggle():
display(HTML('''
<style>
.code-toggle {
position: fixed;
top: 20px;
left: 20px;
z-index: 1000;
padding: 10px 17px;
background: #1570FF; /* Bright blue color */
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
box-shadow: 0 2px 6px rgba(0,0,0,0.2);
transition: all 0.3s ease;
}
.code-toggle:hover {
background: #1976D2;
box-shadow: 0 4px 8px rgba(0,0,0,0.3);
transform: translateY(-1px);
}
.code-toggle:active {
transform: translateY(1px);
}
.code-container {
margin: 10px 0;
transition: all 0.3s ease;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Create toggle button
var toggleButton = $('<button class="code-toggle">â–¼ Toggle Code</button>');
$('body').prepend(toggleButton);
// Wrap all code blocks in containers
$('pre').each(function() {
$(this).wrap('<div class="code-container"></div>');
});
// Set initial state
var codeVisible = true;
// Toggle functionality
toggleButton.click(function() {
codeVisible = !codeVisible;
$('.code-container').slideToggle(300);
$(this).html(codeVisible ? 'â–¼ Hide Code' : 'â–² Show Code');
$(this).toggleClass('code-hidden', !codeVisible);
});
});
</script>
'''))
hide_code_toggle()
# Load the dataset
file_path = r"C:\Users\11\Desktop\Python\Python Project\Trade_China_2000-2023\trade_data_updated.xlsx"
total = pd.read_excel(file_path)
# Convert column names to strings
total.columns = total.columns.astype(str)
# ===========================================
# USER INPUTS (Customize these)
# ===========================================
TARGET_COUNTRY = "China" # Country to analyze
TRADE_TYPE = "Export" # "Import" or "Export"
TARGET_YEAR = "2023" # Year to highlight
YEARS_TO_DISPLAY = [str(year) for year in range(2014, 2024)] # 2014-2023
TOP_N = 10 # Number of top partners to show
# ===========================================
def plot_top_trading_partners(data, trade_type, years, top_n, target_year):
"""
Generate a bar chart of top trading partners with yearly breakdown.
"""
# Filter data for the specified trade type (Import/Export)
trade_data = data[data["Unnamed: 0"] == trade_type].copy()
# Validate years exist in dataset
missing_years = [year for year in years if year not in trade_data.columns]
if missing_years:
raise ValueError(f"Missing data for years: {missing_years}")
# Sort countries by trade value in target year to get top partners
sorted_data = trade_data.sort_values(by=target_year, ascending=False).head(top_n)
top_countries = sorted_data["Country"].tolist()
# Melt data to long format for Plotly
melted_data = pd.melt(
sorted_data,
id_vars=["Country"],
value_vars=years,
var_name="Year",
value_name="Trade Value (US$)"
)
# Create the bar chart
fig = px.bar(
melted_data,
x="Country",
y="Trade Value (US$)",
color="Year",
color_discrete_sequence=px.colors.sequential.RdBu,
text="Trade Value (US$)",
title=f"Top {top_n} {TRADE_TYPE} Partners of {TARGET_COUNTRY} (2014-2023)",
labels={"Trade Value (US$)": "Trade Value (In Millions$)"},
hover_data=["Country", "Year"],
category_orders={"Year": years} # Force chronological order
)
# Format values and layout
fig.update_layout(
yaxis=dict(tickprefix="$", tickformat=",.0f"),
xaxis=dict(title="Counties", categoryorder='total descending'),
hoverlabel=dict(bgcolor="white", font_size=12),
template="plotly_white",
legend=dict(title="Year", orientation="h", yanchor="bottom", y=1.02),
font=dict(family="verdana"),
margin=dict(b=100) # Prevent bottom cutoff for country names
)
# Format text and bars
fig.update_traces(
texttemplate="%{text:$,.0f}",
textposition="outside",
marker_line_color="black",
marker_line_width=0.5
)
return fig
# Generate the plot
fig = plot_top_trading_partners(
data=total,
trade_type=TRADE_TYPE,
years=YEARS_TO_DISPLAY,
top_n=TOP_N,
target_year=TARGET_YEAR
)
# Show the plot
fig.show()
# ===========================================
# GENERATE IMPORT PLOT (Added code)
# ===========================================
# Override the TRADE_TYPE to "Import"
TRADE_TYPE = "Import"
# Generate the import plot using the same function
fig_import = plot_top_trading_partners(
data=total,
trade_type=TRADE_TYPE,
years=YEARS_TO_DISPLAY,
top_n=TOP_N,
target_year=TARGET_YEAR
)
# Show the import plot
fig_import.show()