An analysis of Ghana’s gold export market and their trading key partners.
Published
Aug 27, 2026
Keywords
wealth-income
Summary
The chart shows the main importers of gold from Ghana, one of the world’s largest producers and exporters.
Code
# Libraries# ================================================import comtradeapicallimport matplotlib.pyplot as pltimport seaborn as snsimport requestsimport matplotlib.image as mpimgimport osfrom io import BytesIOfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox# Data Extraction# ================================================# Convert ISO to codecountry = comtradeapicall.convertCountryIso3ToCode('GHA')[:3]# Create df using parametersdf = comtradeapicall.previewFinalData( typeCode='C', # Goods (C) or Services (S) freqCode='A', # Annual (A) or Monthly (M) clCode='HS', # Indicates the product classification used and which version (HS, SITC) period='2023', # Period reporterCode=country, # Country origin (reporter) cmdCode='7108', # Product code in conjunction with classification code (7108 Gold) flowCode='X', # Exportaciones (X) imports (M) partnerCode=None, # Country destination (partner) partner2Code=None, # The primary partner country or geographic area for the respective trade flow customsCode=None, # A secondary partner country or geographic area for the respective trade flow motCode=None, # The mode of transport used when goods enter or leave the economic territory of a country maxRecords=500, # Limit number of returned records format_output='JSON', # The output format. CSV or JSON aggregateBy=None, # Option for aggregating the query breakdownMode='classic', # Option to select the classic (trade by partner/product) or plus (extended breakdown) mode countOnly=None, # Return the actual number of records if set to True includeDesc=True# Option to include the description or not)# Sort data by valuedf = df.sort_values(by='primaryValue', ascending=False)# Select and rename columnsdf = df[['flowDesc', 'refYear', 'reporterISO', 'reporterDesc', 'partnerISO', 'partnerDesc', 'primaryValue', 'customsDesc', 'motDesc', 'cmdCode', 'cmdDesc']]df.columns = ['flow', 'year','reporter_iso','reporter','partner_iso','partner','value','custom_desc','transport_mode', 'product_code', 'product']# Filter World partnerdf = df[df['partner_iso'] !='W00']# Solving namesdf.loc[df['partner_iso'] =='HKG', 'partner'] ='Hong Kong'df.loc[df['partner_iso'] =='TUR', 'partner'] ='Turkey'df.loc[df['partner_iso'] =='KOR', 'partner'] ='South Korea'df.loc[df['partner_iso'] =='FRO', 'partner'] ='Faroe Islands'print(df)# Data Visualization# ================================================# Font and styleplt.rcParams.update({'font.family': 'sans-serif', 'font.sans-serif': ['Franklin Gothic'], 'font.size': 9})sns.set(style="white", palette="muted")# Create figurefig, ax = plt.subplots(figsize=(10, 6))# Barplotbars = sns.barplot( data=df, y='partner', x='value', color='goldenrod', orient='h')# Add title and subtitlefig.add_artist(plt.Line2D([0.155, 0.155], [0.87, 0.97], linewidth=6, color='#203764', solid_capstyle='butt'))plt.text(0.02, 1.13, f'Ghana Gold Exports', fontsize=16, fontweight='bold', ha='left', transform=plt.gca().transAxes)plt.text(0.02, 1.09, f'Leading gold importers from Ghana in 2024', fontsize=11, color='#262626', ha='left', transform=plt.gca().transAxes)plt.text(0.02, 1.05, f'(exports in $US billions)', fontsize=9, color='#262626', ha='left', transform=plt.gca().transAxes)# Axis labels and gridplt.xlabel('Exports (US$ billions)', fontsize=11, fontweight='bold')plt.ylabel('')plt.xticks( ticks=plt.xticks()[0], labels=[f'{tick /1e9:.1f}'for tick in plt.xticks()[0]], fontsize=9)plt.yticks(fontsize=9)plt.grid(axis='x', linestyle=':', color='gray', alpha=0.7, linewidth=0.5)# Remove spinesax = plt.gca()ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['bottom'].set_linewidth(0.5)ax.spines['left'].set_linewidth(0.5)# Add Year labelformatted_date =2024ax.text(1, 1.15, f'{formatted_date}', transform=ax.transAxes, fontsize=22, ha='right', va='top', fontweight='bold', color='#D3D3D3')# Add value label for each barfor container in bars.containers:for bar in container: width = bar.get_width()# Format labelif width <1e9: label =f'{width /1e6:.1f}M'# Milionselse: label =f'{width /1e9:.2f}B'# Bilions plt.text(width + (0.025e9) *6, bar.get_y() + bar.get_height() /2, label, va='center', ha='left', fontsize=9)# Define flagsflag_urls = {'CHE': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/CH.png','ARE': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/AE.png','ZAF': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/ZA.png','IND': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/IN.png','TUR': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/TR.png','HKG': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/HK.png','KOR': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/KR.png','CHN': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/CN.png','DEU': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/DE.png','FRO': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/FO.png','SGP': 'https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/SG.png'}# Load flagsflags = {country: mpimg.imread(BytesIO(requests.get(url).content)) for country, url in flag_urls.items()}# Add flags with AnnotationBbox and OffsetImagefor partner_iso, bar inzip(df['partner_iso'], bars.patches):if partner_iso in flags: img = flags[partner_iso] imagebox = OffsetImage(img, zoom=0.03) x = bar.get_width() +0.03e9 y = bar.get_y() + bar.get_height()/2 ab = AnnotationBbox(imagebox, (x, y), frameon=False, box_alignment=(0,0.5), pad=0) ax.add_artist(ab)# Add Data Sourceplt.text(0, -0.15, 'Data Source:', transform=plt.gca().transAxes, fontsize=8, fontweight='bold', color='gray')space =" "*23plt.text(0, -0.15, space +'UN Comtrade', transform=plt.gca().transAxes, fontsize=8, color='gray')# Adjust layoutplt.tight_layout()# Save it...download_folder = os.path.join(os.path.expanduser("~"), "Downloads")filename = os.path.join(download_folder, f"FIG_COMT_Ghana_Gold_Exports")plt.savefig(filename, dpi=300, bbox_inches='tight')# Show :)plt.show()