In [1]:
import pandas as pd
import plotly.express as px
import numpy as np
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 all column names to strings to avoid type issues
total.columns = total.columns.astype(str)
# Check if '2023' column exists (now as a string)
if '2023' in total.columns:
# Convert the '2023' column to numeric, coercing errors to NaN
total['2023'] = pd.to_numeric(total['2023'], errors='coerce')
print(f"\nData type of '2023' column after conversion: {total['2023'].dtype}")
# Identify the trade type column (first column)
trade_type_col = total.columns[0] # Usually 'Unnamed: 0'
print(f"\nTrade type column identified as: '{trade_type_col}'")
# ===========================================
# Treemap for IMPORTS
# ===========================================
import_data = total[total[trade_type_col] == 'Import'].copy()
if not import_data.empty:
import_data['Trade Value (In Millions$)'] = import_data['2023']
fig_import = px.treemap(
import_data,
path=[px.Constant('World'), 'Continent', 'Country'],
values='Trade Value (In Millions$)',
color='Trade Value (In Millions$)',
hover_data=['ISO-3_Code'],
color_continuous_scale='RdBu',
color_continuous_midpoint=np.nanpercentile(import_data['Trade Value (In Millions$)'], 85),
template='plotly_white'
)
fig_import.update_layout(
title='<b>Top Importers of Chinese Goods (2023)</b> <br><sup><i>Hover for details</i></sup>',
font_family="verdana",
margin=dict(t=50, l=25, r=25, b=25),
paper_bgcolor="#e9f1f5",
plot_bgcolor="#e9f1f5"
)
fig_import.show()
else:
print("\nNo import data found!")
# ===========================================
# Treemap for EXPORTS (NEW ADDITION)
# ===========================================
export_data = total[total[trade_type_col] == 'Export'].copy() # Filter for Export
if not export_data.empty:
export_data['Trade Value (In Millions$)'] = export_data['2023']
fig_export = px.treemap(
export_data,
path=[px.Constant('World'), 'Continent', 'Country'],
values='Trade Value (In Millions$)',
color='Trade Value (In Millions$)',
hover_data=['ISO-3_Code'],
color_continuous_scale='RdBu_r',
color_continuous_midpoint=np.nanpercentile(export_data['Trade Value (In Millions$)'], 85),
template='plotly_white'
)
fig_export.update_layout(
title='<b>Top Exporters of Chinese Goods (2023)</b> <br><sup><i>Hover for details</i></sup>',
font_family="verdana",
margin=dict(t=50, l=25, r=25, b=25),
paper_bgcolor="#e9f1f5",
plot_bgcolor="#e9f1f5"
)
fig_export.show()
else:
print("\nNo export data found!")
else:
print("\nColumn '2023' not found. Check column names after conversion.")
Data type of '2023' column after conversion: float64 Trade type column identified as: 'Unnamed: 0'