# CHAPTER 27
1. Chapter Introduction
#
Advanced techniques elevate standard charts into memorable, insight-rich visualizations — animations that show evolution, Sankey diagrams for flows, treemaps for hierarchies, and radar charts for multi-dimensional comparison.
2. Animation with Matplotlib
#
python
{ copied = true; setTimeout(() => copied = false, 2000) })" class="text-slate-400 hover:text-white p-1 rounded hover:bg-slate-800 transition relative flex items-center justify-center" title="Copy code">
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig, ax = plt.subplots (figsize=(10 , 6 ))
ax.set_xlim (0, 12 )
ax.set_ylim (0, 120000 )
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
data = [42000 , 48000 , 52000 , 49000 , 58000 , 63000 , 61000 , 67000 , 71000 , 69000 , 75000 , 82000 ]
colors = ['#42A5F5'] * 12
colors[data.index (max (data))] = '#1565C0'
bars = ax.bar ([], [], color='#42A5F5')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.yaxis.set_major_formatter (plt.FuncFormatter (lambda x, _: f'${x/1000:.0f}K'))
ax.set_title ('Monthly Revenue Animation', fontsize=13, fontweight='bold')
ax.grid (True , axis='y', alpha=0.3)
def animate (i):
ax.cla ()
ax.set_xlim (-0.5 , 11 .5 )
ax.set_ylim (0, 120000 )
c = ['#1565C0' if j <= i and data[j] == max(data[:i+1]) else '#42A5F5' if j <= i else '#E0E0E0'
for j in range (12 )]
b = ax.bar (range (12 ), data, color=c, width=0.7 , edgecolor='white')
ax.set_xticks (range (12 ))
ax.set_xticklabels (months)
ax.yaxis.set_major_formatter (plt.FuncFormatter (lambda x, _: f'${x/1000:.0f}K'))
ax.set_title (f'Monthly Revenue — {months[i]} (${data[i]:,})', fontsize=13, fontweight='bold')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.grid (True , axis='y', alpha=0.3)
ani = animation.FuncAnimation (fig, animate, frames=12 , interval=600 , repeat=True )
ani.save ('revenue_animation.gif', writer='pillow', fps=2) # pip install pillow
plt.show ()
3. Treemap — Hierarchical Data
#
python
{ copied = true; setTimeout(() => copied = false, 2000) })" class="text-slate-400 hover:text-white p-1 rounded hover:bg-slate-800 transition relative flex items-center justify-center" title="Copy code">
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
import plotly.express as px
import pandas as pd
# Product hierarchy data
hierarchy = pd.DataFrame ({
'Category': ['Electronics','Electronics','Electronics','Furniture','Furniture','Clothing','Clothing','Clothing'],
'Product': ['Laptop','Phone','Monitor','Desk','Chair','Jacket','Shirt','Shoes'],
'Revenue': [425000, 318000, 189000, 142000, 98000, 86000, 54000, 72000],
'Margin': [28, 22, 31, 18, 24, 45, 38, 42]
})
fig = px.treemap (hierarchy,
path=[px.Constant ('All Products'), 'Category', 'Product'],
values='Revenue',
color='Margin',
color_continuous_scale='RdYlGn',
color_continuous_midpoint=30 ,
hover_data={'Revenue': ':$,.0f', 'Margin': ':.1f%'},
title='Product Revenue Treemap (Color = Margin %)')
fig.update_layout (template='plotly_white', height=500)
fig.show ()
4. Sankey Diagram — Flow Visualization
#
python
{ copied = true; setTimeout(() => copied = false, 2000) })" class="text-slate-400 hover:text-white p-1 rounded hover:bg-slate-800 transition relative flex items-center justify-center" title="Copy code">
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
import plotly.graph_objects as go
# Customer journey flow
fig = go.Figure (go.Sankey (
node=dict (
pad=20 , thickness=25 , line=dict (color='black', width=0.5),
label=['Website', 'Product Page', 'Cart', 'Checkout', 'Purchase',
'Bounce', 'Abandoned Cart', 'Abandoned Checkout'],
color=['#1565C0','#1976D2','#2196F3','#42A5F5','#4CAF50',
'#EF5350','#FF7043','#FFCA28']
),
link=dict (
source=[0,0,1 ,1 ,2 ,2 ,3 ,3 ], # From node indices
target=[1 ,5 ,2 ,5 ,3 ,6 ,4 ,7 ], # To node indices
value= [45000 ,55000 ,32000 ,13000 ,20000 ,12000 ,15000 ,5000 ],
color= ['rgba(25,118,210,0.4)','rgba(239,83,80,0.3)',
'rgba(33,150,243,0.4)','rgba(239,83,80,0.3)',
'rgba(66,165,245,0.4)','rgba(255,112,67,0.3)',
'rgba(76,175,80,0.4)', 'rgba(255,202,40,0.3)']
)
))
fig.update_layout (title='Customer Journey Flow Analysis', font_size=12,
template='plotly_white', height=450)
fig.show ()
5. Radar/Spider Chart
#
python
{ copied = true; setTimeout(() => copied = false, 2000) })" class="text-slate-400 hover:text-white p-1 rounded hover:bg-slate-800 transition relative flex items-center justify-center" title="Copy code">
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import matplotlib.pyplot as plt
import numpy as np
categories = ['Sales', 'Marketing', 'Tech', 'Finance', 'HR', 'Operations']
N = len (categories)
teams_data = {
'Team Alpha': [85, 70, 92, 78, 65, 88],
'Team Beta': [72, 88, 76, 83, 90, 70],
'Team Gamma': [90, 65, 85, 75, 72, 82]
}
angles = np.linspace (0, 2 * np.pi, N, endpoint=False ).tolist ()
angles += angles[:1 ] # Close the polygon
fig, ax = plt.subplots (figsize=(8 , 8 ), subplot_kw=dict (projection='polar'))
colors = ['#1565C0', '#2E7D32', '#E65100']
for (team, values), color in zip (teams_data.items (), colors):
values_closed = values + values[:1 ]
ax.plot (angles, values_closed, 'o-', linewidth=2, color=color, label=team)
ax.fill (angles, values_closed, alpha=0.1 , color=color)
ax.set_xticks (angles[:-1 ])
ax.set_xticklabels (categories, fontsize=11 )
ax.set_ylim (0, 100 )
ax.set_yticks ([25 , 50 , 75 , 100 ])
ax.set_yticklabels (['25', '50', '75', '100'], fontsize=8)
ax.set_title ('Team Performance Radar', fontsize=14, fontweight='bold', pad=20)
ax.legend (loc='lower right', bbox_to_anchor=(1.3, 0))
plt.tight_layout ()
plt.savefig ('radar_chart.png', dpi=150, bbox_inches='tight')
plt.show ()
6. Common Mistakes
#
Animations without purpose: Animations impress but distract. Only animate when the evolution over time IS the insight.
Treemaps with too many levels: More than 3 hierarchy levels makes treemaps unreadable. Limit to 2-3 path levels.
7. MCQs
#
Question 1
Treemap is best for?
A
Time series
B
Hierarchical part-of-whole data (size + color)
C
Distribution —
Check Answer
Question 2
Sankey diagram shows?
A
Comparison
B
Flow volumes between stages/nodes
C
Distribution —
Check Answer
Question 3
Radar chart is ideal for?
A
Trends
B
Multi-dimensional comparison of entities across same metrics
C
Geography —
Check Answer
Question 4
animation.FuncAnimation() requires?
A
ffmpeg always
B
A figure and update function called each frame
C
Plotly —
Check Answer
Question 5
px.treemap(path=[...]) with multiple items creates?
A
Flat
B
Hierarchical drill-down levels
C
Categories —
Check Answer
Question 6
Sankey source and target are?
A
Colors
B
Node indices (0-based) for link direction
C
Values —
Check Answer
Question 7
subplot_kw=dict(projection='polar') creates?
A
Map
B
Polar/circular coordinate system for radar chart
C
3D —
Check Answer
Question 8
color_continuous_midpoint=30 in treemap?
A
Centers chart
B
Makes 30% margin appear neutral in diverging scale
C
Filters —
Check Answer
Question 9
Animation interval=600 means?
A
600 frames
B
600ms between frames
C
600 seconds total —
Check Answer
Question 10
Radar chart polygon must close with?
A
Extra point
B
Repeating first element (angles+[:1], values+[:1])
C
Return to origin —
Check Answer
8. Interview Questions
#
Q: When would you use a treemap vs a bar chart?
Q: How do you create a Sankey diagram in Python?
9. Summary
#
Advanced charts: animations for temporal evolution (Matplotlib FuncAnimation / Plotly), treemaps for hierarchical part-of-whole (Plotly Express), Sankey diagrams for flow analysis, radar charts for multi-metric comparison. Each serves a specific data structure — match chart to data shape, not visual appeal.
10. Next Chapter Recommendation
#
In
Chapter 28: Data Visualization Interview Preparation , we compile 50 interview questions, coding challenges, and chart critique exercises.