Menu

Hierarchical
Interactive
20 Python scripts generated for treemap this week

Treemap

Chart overview

Treemaps visualize hierarchical data by nesting rectangles within rectangles, where the size of each rectangle is proportional to its value.

Key points

  • They efficiently use space while showing part-to-whole relationships across multiple levels.
  • Treemaps are excellent for visualizing file system storage, market sectors, organizational budgets, and any nested categorical data with associated quantities.

Interactive Visualization

Loading interactive chart...

This is an interactive treemap. You can zoom, pan, and hover over elements for details.

Create This Chart Now

Generate publication-ready treemaps with AI in seconds. No coding required – just describe your data and let AI do the work.

View example prompt
Example AI Prompt

"Create an interactive treemap showing 'Global Stock Market Capitalization' by Sector and Industry. Generate data for 30+ companies across 8 sectors: Technology ($8T: Apple $3T, Microsoft $2.8T, NVIDIA $1.2T, others), Healthcare ($4T: Johnson & Johnson $500B, etc.), Financials ($5T), Consumer Discretionary ($4T), Energy ($2T), Industrials ($3T), Consumer Staples ($2T), Utilities ($1T). Size rectangles by market cap. Color by 'YTD Growth Rate' using RdYlGn diverging scale (-30% to +50%). Add hover showing company name, ticker, market cap (formatted as $XXB), and growth %. Enable drill-down navigation. Include a color legend and total market cap in title."

How to create this chart in 30 seconds

1

Upload Data

Drag & drop your Excel or CSV file. Plotivy securely processes it in your browser.

2

AI Generation

Our AI analyzes your data and generates the Treemap code automatically.

3

Customize & Export

Tweak the design with natural language, then export as high-res PNG, SVG or PDF.

Python Code Example

example.py
# === IMPORTS ===
import pandas as pd
import numpy as np
import plotly.express as px

# === USER-EDITABLE PARAMETERS ===
title = "Global Stock Market Capitalization by Sector ($29T Total)"
color_scale = "RdYlGn"  # Diverging scale for growth rate
figsize_width = 1000
figsize_height = 700

# === EXAMPLE DATASET ===
# Generate data for 30+ companies across 8 sectors
np.random.seed(42)

data = {
    'Sector': [],
    'Company': [],
    'Market_Cap_B': [],
    'YTD_Growth': []
}

sectors_data = {
    'Technology': [
        ('Apple', 3000, 15.2),
        ('Microsoft', 2800, 22.5),
        ('NVIDIA', 1200, 48.3),
        ('Google', 1800, 18.7),
        ('Meta', 900, 35.2),
        ('Adobe', 250, 12.1),
    ],
    'Healthcare': [
        ('Johnson & Johnson', 500, -5.2),
        ('UnitedHealth', 480, 8.3),
        ('Pfizer', 350, -12.5),
        ('Eli Lilly', 550, 42.1),
        ('AbbVie', 320, 6.8),
    ],
    'Financials': [
        ('JPMorgan Chase', 500, 18.3),
        ('Visa', 480, 14.2),
        ('Mastercard', 420, 16.5),
        ('Bank of America', 280, 5.2),
        ('Goldman Sachs', 130, 22.1),
    ],
    'Consumer Discretionary': [
        ('Amazon', 1500, 28.5),
        ('Tesla', 800, -8.2),
        ('Home Depot', 350, 5.8),
        ('Nike', 180, -2.5),
        ('Starbucks', 120, 3.2),
    ],
    'Energy': [
        ('ExxonMobil', 450, -5.8),
        ('Chevron', 320, -8.2),
        ('Shell', 220, -12.5),
        ('ConocoPhillips', 150, 2.3),
    ],
    'Industrials': [
        ('Caterpillar', 180, 18.5),
        ('Boeing', 150, -15.2),
        ('Lockheed Martin', 120, 8.3),
        ('General Electric', 200, 45.2),
        ('3M', 80, -22.5),
    ],
    'Consumer Staples': [
        ('Procter & Gamble', 400, 5.2),
        ('Coca-Cola', 280, 3.8),
        ('PepsiCo', 250, 4.5),
        ('Costco', 320, 22.5),
    ],
    'Utilities': [
        ('NextEra Energy', 180, 8.5),
        ('Duke Energy', 85, 2.3),
        ('Southern Company', 80, 1.8),
        ('Dominion Energy', 55, -5.2),
    ],
}

for sector, companies in sectors_data.items():
    for company, market_cap, growth in companies:
        data['Sector'].append(sector)
        data['Company'].append(company)
        data['Market_Cap_B'].append(market_cap)
        data['YTD_Growth'].append(growth)

df = pd.DataFrame(data)

# Print summary statistics
print("=== Stock Market Treemap Data Summary ===")
print(f"\nTotal Companies: {len(df)}")
print(f"Total Market Cap: ${df['Market_Cap_B'].sum():,.0f}B")
print(f"\nBy Sector:")
sector_summary = df.groupby('Sector').agg({
    'Market_Cap_B': 'sum',
    'YTD_Growth': 'mean'
}).round(1)
print(sector_summary.to_string())

print(f"\nTop 5 Companies by Market Cap:")
top5 = df.nlargest(5, 'Market_Cap_B')[['Company', 'Sector', 'Market_Cap_B', 'YTD_Growth']]
print(top5.to_string(index=False))

print(f"\nGrowth Range: {df['YTD_Growth'].min():.1f}% to {df['YTD_Growth'].max():.1f}%")

# === CREATE TREEMAP ===
fig = px.treemap(
    df,
    path=['Sector', 'Company'],
    values='Market_Cap_B',
    color='YTD_Growth',
    color_continuous_scale=color_scale,
    color_continuous_midpoint=0,
    range_color=[-30, 50],
    title=title,
    hover_data={
        'Market_Cap_B': ':.0f',
        'YTD_Growth': ':.1f'
    }
)

# Update layout
fig.update_layout(
    width=figsize_width,
    height=figsize_height,
    margin=dict(t=50, l=10, r=10, b=10),
    coloraxis_colorbar=dict(
        title="YTD Growth %",
        ticksuffix="%"
    )
)

# Update hover template
fig.update_traces(
    hovertemplate='<b>%{label}</b><br>Market Cap: $%{value:,.0f}B<br>YTD Growth: %{color:.1f}%<extra></extra>'
)

fig.show()
# END-OF-CODE

Opens the Analyze page with this code pre-loaded and ready to execute

Console Output

Output
Total Market Cap: $15650B
Top Sector: Technology
Average Growth: 12.34%
Number of Companies: 15

Common Use Cases

  • 1Disk space usage visualization
  • 2Stock market sector breakdown
  • 3Corporate budget visualization
  • 4E-commerce category sales

Pro Tips

Use tooltips for detailed information

Limit hierarchy depth to 3-4 levels

Color by a separate metric for additional insight

Free Cheat Sheet

Scientific Chart Selection Cheat Sheet

Not sure whether to use a Violin Plot, Box Plot, or Ridge Plot? Download our single-page reference mapping the most-used scientific chart types, exactly when to use them, and the core Matplotlib/Seaborn functions.

Comparison Charts
Distribution Charts
Time Series Data
Common Mistakes
No spam. Unsubscribe anytime.