1
---
2
name: Data Visualization
3
description: Create effective visualizations using matplotlib and seaborn for exploratory analysis, presenting insights, and communicating findings with business stakeholders
4
---
5
6
# Data Visualization
7
8
## Overview
9
10
Data visualization transforms complex data into clear, compelling visual representations that reveal patterns, trends, and insights for storytelling and decision-making.
11
12
## When to Use
13
14
- Exploratory data analysis and pattern discovery
15
- Communicating insights to stakeholders
16
- Comparing distributions and relationships
17
- Presenting findings in reports and dashboards
18
- Identifying outliers and anomalies visually
19
- Creating publication-ready charts and graphs
20
21
## Visualization Types
22
23
- **Distributions**: Histograms, KDE, violin plots
24
- **Relationships**: Scatter plots, line plots, heatmaps
25
- **Comparisons**: Bar charts, box plots, ridge plots
26
- **Compositions**: Pie charts, stacked bars, treemaps
27
- **Temporal**: Line plots, area charts, time series
28
- **Multivariate**: Pair plots, correlation heatmaps
29
30
## Design Principles
31
32
- Choose appropriate chart type for data
33
- Minimize ink-to-data ratio
34
- Use color purposefully
35
- Label clearly and completely
36
- Maintain consistent scales
37
- Consider accessibility
38
39
## Implementation with Python
40
41
```python
42
import pandas as pd
43
import numpy as np
44
import matplotlib.pyplot as plt
45
import seaborn as sns
46
from matplotlib.gridspec import GridSpec
47
48
# Set style
49
sns.set_style("whitegrid")
50
plt.rcParams['figure.figsize'] = (12, 6)
51
52
# Generate sample data
53
np.random.seed(42)
54
n = 500
55
data = pd.DataFrame({
56
'age': np.random.uniform(20, 70, n),
57
'income': np.random.exponential(50000, n),
58
'education_years': np.random.uniform(12, 20, n),
59
'category': np.random.choice(['A', 'B', 'C'], n),
60
'region': np.random.choice(['North', 'South', 'East', 'West'], n),
61
'satisfaction': np.random.uniform(1, 5, n),
62
'purchased': np.random.choice([0, 1], n),
63
})
64
65
print(data.head())
66
67
# 1. Distribution Plots
68
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
69
70
# Histogram
71
axes[0, 0].hist(data['age'], bins=30, color='skyblue', edgecolor='black')
72
axes[0, 0].set_title('Age Distribution (Histogram)')
73
axes[0, 0].set_xlabel('Age')
74
axes[0, 0].set_ylabel('Frequency')
75
76
# KDE plot
77
data['income'].plot(kind='kde', ax=axes[0, 1], color='green', linewidth=2)
78
axes[0, 1].set_title('Income Distribution (KDE)')
79
axes[0, 1].set_xlabel('Income')
80
81
# Box plot
82
sns.boxplot(data=data, y='satisfaction', x='category', ax=axes[1, 0], palette='Set2')
83
axes[1, 0].set_title('Satisfaction by Category (Box Plot)')
84
85
# Violin plot
86
sns.violinplot(data=data, y='age', x='category', ax=axes[1, 1], palette='Set2')
87
axes[1, 1].set_title('Age by Category (Violin Plot)')
88
89
plt.tight_layout()
90
plt.show()
91
92
# 2. Relationship Plots
93
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
94
95
# Scatter plot
96
axes[0, 0].scatter(data['age'], data['income'], alpha=0.5, s=30)
97
axes[0, 0].set_title('Age vs Income (Scatter Plot)')
98
axes[0, 0].set_xlabel('Age')
99
axes[0, 0].set_ylabel('Income')
100
101
# Scatter with regression line
102
sns.regplot(x='age', y='income', data=data, ax=axes[0, 1], scatter_kws={'alpha': 0.5})
103
axes[0, 1].set_title('Age vs Income (with Regression Line)')
104
105
# Joint plot alternative
106
ax_hex = axes[1, 0]
107
hexbin = ax_hex.hexbin(data['age'], data['income'], gridsize=15, cmap='YlOrRd')
108
ax_hex.set_title('Age vs Income (Hex Bin)')
109
ax_hex.set_xlabel('Age')
110
ax_hex.set_ylabel('Income')
111
112
# Bubble plot
113
scatter = axes[1, 1].scatter(
114
data['age'], data['income'], s=data['satisfaction']*50,
115
c=data['satisfaction'], cmap='viridis', alpha=0.6, edgecolors='black'
116
)
117
axes[1, 1].set_title('Age vs Income (Bubble Plot)')
118
axes[1, 1].set_xlabel('Age')
119
axes[1, 1].set_ylabel('Income')
120
plt.colorbar(scatter, ax=axes[1, 1], label='Satisfaction')
121
122
plt.tight_layout()
123
plt.show()
124
125
# 3. Comparison Plots
126
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
127
128
# Bar plot
129
category_counts = data['category'].value_counts()
130
axes[0, 0].bar(category_counts.index, category_counts.values, color='skyblue', edgecolor='black')
131
axes[0, 0].set_title('Category Distribution (Bar Chart)')
132
axes[0, 0].set_ylabel('Count')
133
134
# Grouped bar plot
135
grouped_data = data.groupby(['category', 'region']).size().unstack()
136
grouped_data.plot(kind='bar', ax=axes[0, 1], edgecolor='black')
137
axes[0, 1].set_title('Category by Region (Grouped Bar)')
138
axes[0, 1].set_ylabel('Count')
139
axes[0, 1].legend(title='Region')
140
141
# Stacked bar plot
142
grouped_data.plot(kind='bar', stacked=True, ax=axes[1, 0], edgecolor='black')
143
axes[1, 0].set_title('Category by Region (Stacked Bar)')
144
axes[1, 0].set_ylabel('Count')
145
146
# Horizontal bar plot
147
region_counts = data['region'].value_counts()
148
axes[1, 1].barh(region_counts.index, region_counts.values, color='lightcoral', edgecolor='black')
149
axes[1, 1].set_title('Region Distribution (Horizontal Bar)')
150
axes[1, 1].set_xlabel('Count')
151
152
plt.tight_layout()
153
plt.show()
154
155
# 4. Correlation and Heatmaps
156
numeric_cols = data[['age', 'income', 'education_years', 'satisfaction']].corr()
157
158
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
159
160
# Correlation heatmap
161
sns.heatmap(numeric_cols, annot=True, fmt='.2f', cmap='coolwarm', center=0,
162
square=True, ax=axes[0], cbar_kws={'label': 'Correlation'})
163
axes[0].set_title('Correlation Matrix Heatmap')
164
165
# Clustermap alternative
166
from scipy.cluster.hierarchy import dendrogram, linkage
167
from scipy.spatial.distance import pdist, squareform
168
169
# Create a simpler heatmap for category averages
170
category_avg = data.groupby('category')[['age', 'income', 'education_years', 'satisfaction']].mean()
171
sns.heatmap(category_avg.T, annot=True, fmt='.1f', cmap='YlGnBu', ax=axes[1],
172
cbar_kws={'label': 'Average Value'})
173
axes[1].set_title('Average Values by Category')
174
175
plt.tight_layout()
176
plt.show()
177
178
# 5. Pair Plot
179
pair_cols = ['age', 'income', 'education_years', 'satisfaction']
180
plt.figure(figsize=(12, 10))
181
pair_plot = sns.pairplot(data[pair_cols], diag_kind='hist', corner=False)
182
pair_plot.fig.suptitle('Pair Plot Matrix', y=1.00)
183
plt.show()
184
185
# 6. Multi-dimensional Visualization
186
fig = plt.figure(figsize=(14, 6))
187
gs = GridSpec(2, 3, figure=fig)
188
189
# Subplots with different aspects
190
ax1 = fig.add_subplot(gs[0, 0])
191
ax1.scatter(data['age'], data['income'], c=data['satisfaction'], cmap='viridis', alpha=0.6)
192
ax1.set_title('Age vs Income (colored by Satisfaction)')
193
ax1.set_xlabel('Age')
194
ax1.set_ylabel('Income')
195
196
ax2 = fig.add_subplot(gs[0, 1])
197
for cat in data['category'].unique():
198
subset = data[data['category'] == cat]
199
ax2.scatter(subset['age'], subset['income'], label=cat, alpha=0.6)
200
ax2.set_title('Age vs Income (by Category)')
201
ax2.set_xlabel('Age')
202
ax2.set_ylabel('Income')
203
ax2.legend()
204
205
ax3 = fig.add_subplot(gs[0, 2])
206
sns.boxplot(data=data, x='region', y='income', ax=ax3, palette='Set2')
207
ax3.set_title('Income Distribution by Region')
208
209
ax4 = fig.add_subplot(gs[1, 0])
210
data.groupby('category')['satisfaction'].mean().plot(kind='bar', ax=ax4, color='skyblue', edgecolor='black')
211
ax4.set_title('Average Satisfaction by Category')
212
ax4.set_ylabel('Satisfaction')
213
ax4.set_xlabel('Category')
214
215
ax5 = fig.add_subplot(gs[1, 1:])
216
region_category = pd.crosstab(data['region'], data['category'])
217
region_category.plot(kind='bar', ax=ax5, edgecolor='black')
218
ax5.set_title('Region vs Category Distribution')
219
ax5.set_ylabel('Count')
220
ax5.set_xlabel('Region')
221
ax5.legend(title='Category')
222
223
plt.tight_layout()
224
plt.show()
225
226
# 7. Time Series Visualization (if temporal data)
227
dates = pd.date_range('2023-01-01', periods=len(data))
228
data['date'] = dates
229
data['cumulative_income'] = data['income'].cumsum()
230
231
fig, axes = plt.subplots(2, 1, figsize=(12, 8))
232
233
# Line plot
234
axes[0].plot(data['date'], data['income'], linewidth=1, alpha=0.7, label='Income')
235
axes[0].fill_between(data['date'], data['income'], alpha=0.3)
236
axes[0].set_title('Income Over Time')
237
axes[0].set_ylabel('Income')
238
axes[0].grid(True, alpha=0.3)
239
axes[0].legend()
240
241
# Area plot
242
axes[1].plot(data['date'], data['cumulative_income'], linewidth=2, color='green')
243
axes[1].fill_between(data['date'], data['cumulative_income'], alpha=0.3, color='green')
244
axes[1].set_title('Cumulative Income Over Time')
245
axes[1].set_ylabel('Cumulative Income')
246
axes[1].set_xlabel('Date')
247
axes[1].grid(True, alpha=0.3)
248
249
plt.tight_layout()
250
plt.show()
251
252
# 8. Composition Visualization
253
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
254
255
# Pie chart
256
category_counts = data['category'].value_counts()
257
colors = ['#ff9999', '#66b3ff', '#99ff99']
258
axes[0].pie(category_counts.values, labels=category_counts.index, autopct='%1.1f%%',
259
colors=colors, startangle=90)
260
axes[0].set_title('Category Distribution (Pie Chart)')
261
262
# Donut chart
263
axes[1].pie(category_counts.values, labels=category_counts.index, autopct='%1.1f%%',
264
colors=colors, startangle=90, wedgeprops=dict(width=0.5, edgecolor='white'))
265
axes[1].set_title('Category Distribution (Donut Chart)')
266
267
plt.tight_layout()
268
plt.show()
269
270
# 9. Dashboard-style Visualization
271
fig = plt.figure(figsize=(16, 10))
272
gs = GridSpec(3, 3, figure=fig, hspace=0.3, wspace=0.3)
273
274
# Key metrics
275
ax_metric = fig.add_subplot(gs[0, :])
276
ax_metric.axis('off')
277
metrics_text = f"""
278
Average Age: {data['age'].mean():.1f} | Average Income: ${data['income'].mean():.0f} |
279
Average Satisfaction: {data['satisfaction'].mean():.2f} | Purchase Rate: {(data['purchased'].mean()*100):.1f}%
280
"""
281
ax_metric.text(0.5, 0.5, metrics_text, ha='center', va='center', fontsize=12,
282
bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.7))
283
284
# Subplots
285
ax1 = fig.add_subplot(gs[1, 0])
286
data['age'].hist(bins=20, ax=ax1, color='skyblue', edgecolor='black')
287
ax1.set_title('Age Distribution')
288
289
ax2 = fig.add_subplot(gs[1, 1])
290
category_counts.plot(kind='bar', ax=ax2, color='lightcoral', edgecolor='black')
291
ax2.set_title('Category Counts')
292
293
ax3 = fig.add_subplot(gs[1, 2])
294
data.groupby('category')['satisfaction'].mean().plot(kind='bar', ax=ax3, color='lightgreen', edgecolor='black')
295
ax3.set_title('Avg Satisfaction by Category')
296
297
ax4 = fig.add_subplot(gs[2, :2])
298
sns.boxplot(data=data, x='region', y='income', ax=ax4, palette='Set2')
299
ax4.set_title('Income by Region')
300
301
ax5 = fig.add_subplot(gs[2, 2])
302
data['satisfaction'].value_counts().sort_index().plot(kind='bar', ax=ax5, color='orange', edgecolor='black')
303
ax5.set_title('Satisfaction Scores')
304
305
plt.suptitle('Data Analytics Dashboard', fontsize=16, fontweight='bold', y=0.995)
306
plt.show()
307
308
print("Visualization examples completed!")
309
```
310
311
## Visualization Best Practices
312
313
- Choose chart type based on data type and question
314
- Use consistent color schemes
315
- Label axes clearly with units
316
- Include title and legend
317
- Avoid 3D charts when 2D suffices
318
- Make fonts large and readable
319
- Consider colorblind-friendly palettes
320
321
## Common Chart Types
322
323
- **Bar charts**: Categorical comparisons
324
- **Line plots**: Trends over time
325
- **Scatter plots**: Relationships between variables
326
- **Histograms**: Distributions
327
- **Heatmaps**: Matrix data
328
- **Box plots**: Distribution with quartiles
329
330
## Deliverables
331
332
- Exploratory visualizations
333
- Publication-ready charts
334
- Interactive dashboard mockups
335
- Statistical plots with annotations
336
- Trend analysis visualizations
337
- Comparative analysis charts
338
- Summary infographics
339