📉 What is Data Visualization in Python?
Data Visualization is the graphical representation of information and statistical data. By utilizing visual elements like charts, graphs, and maps, data visualization tools provide an accessible way to see and understand trends, outliers, and patterns in data.
Python powers advanced visualization pipelines via Matplotlib (flexible 2D plotting) and Seaborn (high-level statistical graphics built on top of Matplotlib).
1. Multi-Series Line Chart (Website Traffic Trends)
Plot multiple trend lines on a single set of axes with custom legends and markers.
Python
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
visitors = [1200, 1500, 1300, 1700, 2100, 2500, 2200]
conversions = [45, 60, 50, 75, 95, 110, 100]
plt.plot(days, visitors, label="Website Visitors", color="blue", marker="o")
plt.plot(days, conversions, label="Conversions", color="green", marker="s")
plt.title("Weekly Traffic vs Conversions")
plt.xlabel("Days of Week")
plt.ylabel("Count")
plt.legend()
plt.grid(True)
plt.show()
Output:
[Visual Window]: Generated multi-series line plot with legends and gridlines.
Real-Time Example 1: Grouped Bar Chart (Departmental Budgets)
Compare multi-category metrics side-by-side using grouped bar charts.
Python
import matplotlib.pyplot as plt
import numpy as np
departments = ["IT", "HR", "Sales", "Marketing"]
q1_budget = [45000, 20000, 60000, 35000]
q2_budget = [50000, 22000, 65000, 40000]
x = np.arange(len(departments))
width = 0.35
plt.bar(x - width/2, q1_budget, width, label="Q1 Budget", color="#367db5")
plt.bar(x + width/2, q2_budget, width, label="Q2 Budget", color="#6c2bd9")
plt.title("Departmental Budget Comparison")
plt.xticks(x, departments)
plt.xlabel("Departments")
plt.ylabel("Budget (₹)")
plt.legend()
plt.show()
Output:
[Visual Window]: Generated grouped bar chart comparing Q1 and Q2 budgets across departments.
Real-Time Example 2: Scatter Plot with Color Mapping
Visualize three-variable relationships (X, Y, and Color Intensity) using scatter plots.
Python
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
experience = np.random.randint(1, 15, 50)
salary = experience * 8000 + np.random.randint(10000, 30000, 50)
performance_score = np.random.randint(50, 100, 50)
plt.scatter(experience, salary, c=performance_score, cmap="viridis", s=80, edgecolors="black")
plt.colorbar(label="Performance Score")
plt.title("Experience vs Salary (Color = Performance)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary (₹)")
plt.grid(True)
plt.show()
Output:
[Visual Window]: Generated scatter plot with viridis color mapping reflecting performance scores.
Real-Time Example 3: Customizing Styles and Themes
Apply professional pre-built styles like
ggplot or seaborn-darkgrid to enhance plot aesthetics.
Python
import matplotlib.pyplot as plt
# Apply ggplot aesthetic style
plt.style.use("ggplot")
x = [1, 2, 3, 4, 5]
y = [10, 25, 30, 45, 60]
plt.plot(x, y, marker="o", color="#16834d", linewidth=3)
plt.title("Styled Plot using ggplot Theme")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
Output:
[Visual Window]: Generated plot rendered with professional ggplot background grid styling.
Real-Time Example 4: Multi-Panel Subplot Grids (2x2 Layout)
Create a multi-panel dashboard grid containing 4 distinct charts using
plt.subplots().
Python
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
# Panel 1: Line Chart
axs[0, 0].plot([1, 2, 3], [4, 5, 6], color="blue")
axs[0, 0].set_title("Line Trend")
# Panel 2: Bar Chart
axs[0, 1].bar(["A", "B", "C"], [10, 25, 15], color="purple")
axs[0, 1].set_title("Category Bars")
# Panel 3: Scatter Plot
axs[1, 0].scatter(np.random.rand(10), np.random.rand(10), color="green")
axs[1, 0].set_title("Scatter Points")
# Panel 4: Histogram
axs[1, 1].hist(np.random.randn(100), bins=10, color="orange", edgecolor="black")
axs[1, 1].set_title("Distribution Histogram")
plt.tight_layout()
plt.show()
Output:
[Visual Window]: Generated a 2x2 multi-panel dashboard figure containing 4 distinct graph types.
Real-Time Example 5: Histogram with KDE Density Curve (Seaborn)
Visualize data distributions alongside smooth kernel density estimation curves using Seaborn.
Python
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# Generate sample dataset
data = np.random.normal(loc=65, scale=10, size=500)
sns.histplot(data, kde=True, color="#4053b5", bins=20)
plt.title("Exam Score Distribution with KDE Curve")
plt.xlabel("Scores")
plt.ylabel("Density Frequency")
plt.show()
Output:
[Visual Window]: Generated Seaborn distribution histogram with a smooth KDE probability density curve.
Real-Time Example 6: Correlation Matrix Heatmap (Seaborn)
Display feature correlation matrices visually using Seaborn heatmaps.
Python
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame(np.random.rand(5, 5), columns=["A", "B", "C", "D", "E"])
corr = df.corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", fmt=".2f")
plt.title("Feature Correlation Matrix Heatmap")
plt.show()
Output:
[Visual Window]: Generated Seaborn correlation heatmap with numerical annotations.
Real-Time Example 7: Box Plot for Outlier Detection
Identify statistical quartiles and outliers across salary distributions using box plots.
Python
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
salaries = np.random.normal(60000, 15000, 100)
salaries = np.append(salaries, [125000, 140000]) # Adding outliers
plt.boxplot(salaries, vert=False, patch_artist=True, boxprops=dict(facecolor="#367db5"))
plt.title("Salary Distribution & Outlier Detection")
plt.xlabel("Salary Amount (₹)")
plt.grid(True)
plt.show()
Output:
[Visual Window]: Generated horizontal box plot highlighting upper salary outliers.
Real-Time Example 8: Categorical Bar Plot with Confidence Intervals (Seaborn)
Compare categorical averages with error confidence bars using Seaborn's
sns.barplot.
Python
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
df = pd.DataFrame({
"Day": ["Sun", "Sun", "Sat", "Sat", "Fri", "Fri"],
"TotalBill": [45, 52, 38, 42, 30, 28],
"Time": ["Dinner", "Lunch", "Dinner", "Lunch", "Dinner", "Lunch"]
})
sns.barplot(x="Day", y="TotalBill", hue="Time", data=df, palette="Blues")
plt.title("Average Bill by Day and Time")
plt.show()
Output:
[Visual Window]: Generated Seaborn categorical bar plot grouped by time hue.
Real-Time Example 9: Exporting High-Resolution Figures to Disk
Save finalized charts to disk in high resolution (300 DPI) using
plt.savefig().
Python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [15, 30, 45, 60, 75]
plt.plot(x, y, marker="o", color="#087f69", linewidth=2.5)
plt.title("Performance Analytics Report")
plt.xlabel("Quarter")
plt.ylabel("Score")
plt.grid(True)
# Save figure in high resolution
plt.savefig("analytics_report.png", dpi=300, bbox_inches="tight")
print("Figure saved successfully as 'analytics_report.png' at 300 DPI.")
plt.close()
Output:
Figure saved successfully as 'analytics_report.png' at 300 DPI.