
Python
Create sophisticated, interactive visualizations for complex data exploration.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Load dataset
df = sns.load_dataset('iris')
# Distribution plots
sns.histplot(data=df, x='sepal_length', kde=True, hue='species')
sns.kdeplot(data=df, x='sepal_length', hue='species', fill=True)
# Categorical plots
sns.boxplot(data=df, x='species', y='sepal_length')
sns.violinplot(data=df, x='species', y='sepal_length', hue='species')
sns.stripplot(data=df, x='species', y='sepal_length', jitter=True)
# Relational plots
sns.scatterplot(data=df, x='sepal_length', y='sepal_width', hue='species', size='petal_length')
# Pair plots (all combinations)
sns.pairplot(df, hue='species')
# Correlation heatmap
sns.heatmap(df.corr(), annot=True, cmap='coolwarm', center=0)
plt.show()import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
# Load data
df = px.data.gapminder().query("continent == 'Europe'")
# Interactive scatter plot
fig = px.scatter(
df,
x='gdpPercap',
y='lifeExp',
size='pop',
color='country',
hover_name='country',
log_x=True,
animation_frame='year',
animation_group='country',
size_max=60
)
fig.show()
# Interactive line plot
fig = px.line(
df,
x='year',
y='lifeExp',
color='country',
title='Life Expectancy Over Time'
)
fig.show()
# Sunburst chart
df_sales = px.data.medals_wide()
fig = px.sunburst(
df_sales,
values='total',
names=df_sales.index,
title='Sales Hierarchy'
)
fig.show()
# Create custom figure
fig = go.Figure(data=[
go.Scatter(x=[1, 2, 3], y=[10, 15, 13], name='Series 1'),
go.Scatter(x=[1, 2, 3], y=[16, 5, 11], name='Series 2', yaxis='y2')
])
fig.update_layout(
title='Multiple Axes Example',
yaxis=dict(title='Y Axis 1'),
yaxis2=dict(title='Y Axis 2', overlaying='y', side='right')
)
fig.show()import matplotlib.pyplot as plt
import numpy as np
# Create figure with subplots
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Plot 1: Custom styling
ax = axes[0, 0]
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), linewidth=2.5, color='#FF6B6B', label='sin(x)')
ax.fill_between(x, np.sin(x), alpha=0.3, color='#FF6B6B')
ax.set_title('Sine Wave', fontsize=14, fontweight='bold')
ax.set_xlabel('x', fontsize=12)
ax.set_ylabel('y', fontsize=12)
ax.grid(True, alpha=0.3, linestyle='--')
ax.legend(fontsize=10)
# Plot 2: Error bars
ax = axes[0, 1]
x = np.arange(5)
y = np.array([2, 4, 3, 5, 6])
errors = np.array([0.2, 0.3, 0.25, 0.15, 0.3])
ax.errorbar(x, y, yerr=errors, fmt='o', capsize=5, capthick=2)
ax.set_title('Data with Uncertainties', fontsize=14, fontweight='bold')
# Plot 3: Dual axes
ax1 = axes[1, 0]
ax2 = ax1.twinx()
x = np.arange(10)
ax1.bar(x, x**2, alpha=0.7, label='x^2', color='steelblue')
ax2.plot(x, x**3, color='coral', linewidth=2, marker='o', label='x^3')
ax1.set_ylabel('x^2', color='steelblue')
ax2.set_ylabel('x^3', color='coral')
ax1.set_title('Dual Axes Example', fontsize=14, fontweight='bold')
# Plot 4: Annotation
ax = axes[1, 1]
x = np.linspace(0, 10, 100)
y = np.sin(x) * np.exp(-x/10)
ax.plot(x, y, linewidth=2)
ax.annotate(
'Peak',
xy=(np.pi/2, np.sin(np.pi/2) * np.exp(-np.pi/20)),
xytext=(np.pi/2 + 1, 0.5),
arrowprops=dict(arrowstyle='->', color='red'),
fontsize=12,
color='red'
)
ax.set_title('Annotated Plot', fontsize=14, fontweight='bold')
plt.tight_layout()
plt.show()import plotly.subplots as sp
import plotly.graph_objects as go
import pandas as pd
import numpy as np
# Create sample data
dates = pd.date_range('2024-01-01', periods=100)
df = pd.DataFrame({
'date': dates,
'sales': np.cumsum(np.random.randn(100) * 10 + 20),
'costs': np.cumsum(np.random.randn(100) * 8 + 15),
'profit': None
})
df['profit'] = df['sales'] - df['costs']
# Create subplots
fig = sp.make_subplots(
rows=2, cols=2,
subplot_titles=('Sales Trend', 'Profit vs Cost', 'Monthly Distribution', 'Key Metrics'),
specs=[[{}, {}], [{'colspan': 2}, None]]
)
# Sales trend
fig.add_trace(
go.Scatter(x=df['date'], y=df['sales'], name='Sales', mode='lines'),
row=1, col=1
)
# Profit vs Cost
fig.add_trace(
go.Scatter(x=df['date'], y=df['profit'], name='Profit', mode='lines'),
row=1, col=2
)
fig.add_trace(
go.Scatter(x=df['date'], y=df['costs'], name='Costs', mode='lines'),
row=1, col=2
)
# Distribution
fig.add_trace(
go.Histogram(x=df['sales'], name='Sales Distribution', nbinsx=20),
row=2, col=1
)
# Update layout
fig.update_layout(
title_text='Sales Dashboard',
height=800,
showlegend=True
)
fig.show()import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Generate sample data
np.random.seed(42)
df = pd.DataFrame({
'category': np.repeat(['A', 'B', 'C'], 100),
'value': np.concatenate([
np.random.normal(100, 15, 100),
np.random.normal(110, 20, 100),
np.random.normal(95, 18, 100)
]),
'group': np.tile(np.repeat(['Group1', 'Group2'], 50), 3)
})
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Joint plot distribution
ax = axes[0, 0]
sns.histplot(data=df, x='value', hue='category', kde=True, ax=ax)
ax.set_title('Distribution by Category')
# Box plot with points
ax = axes[0, 1]
sns.boxplot(data=df, x='category', y='value', ax=ax)
sns.stripplot(data=df, x='category', y='value', color='red', alpha=0.5, ax=ax)
ax.set_title('Box Plot with Points')
# Violin plot
ax = axes[1, 0]
sns.violinplot(data=df, x='category', y='value', hue='group', split=False, ax=ax)
ax.set_title('Violin Plot')
# Count plot
ax = axes[1, 1]
sns.countplot(data=df, x='category', hue='group', ax=ax)
ax.set_title('Count Plot')
plt.tight_layout()
plt.show()import plotly.express as px
import pandas as pd
# Create sample data
df = pd.DataFrame({
'month': ['Jan', 'Feb', 'Mar'] * 4,
'product': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D'],
'region': ['North', 'North', 'North', 'North', 'North', 'North',
'South', 'South', 'South', 'South', 'South', 'South'],
'sales': [100, 120, 115, 150, 160, 155, 80, 85, 90, 200, 210, 205]
})
# Faceted bar chart
fig = px.bar(
df,
x='month',
y='sales',
color='product',
facet_col='region',
title='Sales by Region and Product'
)
fig.show()
# Seaborn facet grid
g = sns.FacetGrid(df, col='region', hue='product', height=4)
g.map(sns.barplot, 'month', 'sales')
plt.show()Complete the learning path: Challenges | Solutions
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward