What is Data Visualization?
Data visualization is the process of representing data using charts, graphs, and plots so that patterns, trends, comparisons, and relationships can be understood quickly.
Matplotlib
A flexible Python library for creating line charts, bar charts, pie charts, scatter plots, and many other visualizations.
Seaborn
A statistical visualization library built on top of Matplotlib that makes many analytical charts easier.
Pandas
Provides convenient plotting capabilities directly from DataFrames and Series.
Business Insights
Visualizations help identify sales trends, product performance, customer behavior, and other patterns.
Install the main libraries used for Python data visualization.
pip install matplotlib pandas seaborn
In many Python environments, Pandas and Matplotlib may already be installed.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
pd is commonly used for Pandas,
plt for Matplotlib, and sns
for Seaborn.
Suppose an online store wants to visualize its monthly sales.
import pandas as pd
sales = pd.DataFrame({
"Month": [
"January", "February", "March",
"April", "May", "June"
],
"Sales": [
120000, 145000, 132000,
168000, 175000, 190000
]
})
print(sales)
A line chart is useful for showing trends over time.
plt.plot(
sales["Month"],
sales["Sales"],
marker="o"
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
plt.plot(
sales["Month"],
sales["Sales"],
marker="o"
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid(True)
plt.show()
A grid can make values easier to compare visually.
Bar charts are useful for comparing different categories.
products = ["Laptop", "Phone", "Tablet", "Headphones"]
sales = [250000, 180000, 120000, 75000]
plt.bar(products, sales)
plt.title("Product Sales")
plt.xlabel("Product")
plt.ylabel("Sales")
plt.show()
Horizontal bars can be easier to read when category names are long.
products = [
"Laptop",
"Smartphone",
"Tablet",
"Wireless Headphones"
]
sales = [250000, 180000, 120000, 75000]
plt.barh(products, sales)
plt.title("Product Sales")
plt.xlabel("Sales")
plt.ylabel("Product")
plt.show()
products = ["Laptop", "Phone", "Tablet"]
sales = [250000, 180000, 120000]
bars = plt.bar(products, sales)
for bar in bars:
plt.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height(),
str(bar.get_height()),
ha="center",
va="bottom"
)
plt.title("Product Sales")
plt.ylabel("Sales")
plt.show()
Pie charts show how categories contribute to a whole.
products = [
"Laptop",
"Phone",
"Tablet",
"Headphones"
]
sales = [250000, 180000, 120000, 75000]
plt.pie(
sales,
labels=products,
autopct="%1.1f%%"
)
plt.title("Sales Distribution")
plt.show()
Scatter plots are useful for understanding relationships between two numerical variables.
advertising = [10, 20, 30, 40, 50, 60]
sales = [100, 150, 180, 230, 280, 320]
plt.scatter(advertising, sales)
plt.title("Advertising vs Sales")
plt.xlabel("Advertising Spend")
plt.ylabel("Sales")
plt.show()
Histograms show how numerical values are distributed.
order_values = [
1200, 1500, 1800, 2200, 2500,
2700, 3100, 3200, 3500, 3900,
4200, 4500, 4800, 5000
]
plt.hist(order_values, bins=5)
plt.title("Order Value Distribution")
plt.xlabel("Order Value")
plt.ylabel("Number of Orders")
plt.show()
plt.figure(figsize=(10, 5))
plt.plot(
sales["Month"],
sales["Sales"],
marker="o"
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
figsize controls the width and height of the
visualization.
plt.plot(
sales["Month"],
sales["Sales"],
marker="o",
linestyle="--",
linewidth=2
)
plt.title("Monthly Sales")
plt.show()
plt.plot(
sales["Month"],
sales["Sales"],
marker="o",
label="Sales"
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.show()
Multiple lines are useful when comparing two related trends.
months = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun"
]
online_sales = [
100000, 120000, 135000,
150000, 175000, 195000
]
store_sales = [
140000, 145000, 150000,
155000, 160000, 165000
]
plt.plot(
months,
online_sales,
marker="o",
label="Online"
)
plt.plot(
months,
store_sales,
marker="o",
label="Store"
)
plt.title("Online vs Store Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.show()
Pandas can create charts directly from DataFrames.
sales.plot(
x="Month",
y="Sales",
kind="line",
marker="o"
)
plt.title("Monthly Sales")
plt.show()
A finance team wants to understand the company's monthly revenue trend.
import pandas as pd
import matplotlib.pyplot as plt
revenue = pd.DataFrame({
"Month": [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun"
],
"Revenue": [
450000, 480000, 510000,
495000, 550000, 590000
]
})
plt.figure(figsize=(10, 5))
plt.plot(
revenue["Month"],
revenue["Revenue"],
marker="o"
)
plt.title("Monthly Revenue")
plt.xlabel("Month")
plt.ylabel("Revenue")
plt.grid(True)
plt.show()
An e-commerce manager wants to compare product performance.
products = pd.DataFrame({
"Product": [
"Laptop",
"Phone",
"Tablet",
"Monitor",
"Headphones"
],
"Sales": [
450000,
380000,
210000,
175000,
95000
]
})
plt.figure(figsize=(10, 5))
plt.bar(
products["Product"],
products["Sales"]
)
plt.title("Product Sales")
plt.xlabel("Product")
plt.ylabel("Sales")
plt.xticks(rotation=20)
plt.show()
city_sales = pd.DataFrame({
"City": [
"Pune",
"Mumbai",
"Delhi",
"Bangalore",
"Chennai"
],
"Sales": [
320000,
450000,
390000,
520000,
280000
]
})
plt.figure(figsize=(9, 5))
plt.barh(
city_sales["City"],
city_sales["Sales"]
)
plt.title("Sales by City")
plt.xlabel("Sales")
plt.ylabel("City")
plt.show()
customers = pd.DataFrame({
"Age": [
21, 24, 25, 27, 29,
31, 32, 34, 36, 38,
41, 43, 45, 47, 52
]
})
plt.hist(
customers["Age"],
bins=5
)
plt.title("Customer Age Distribution")
plt.xlabel("Age")
plt.ylabel("Number of Customers")
plt.show()
A marketing team wants to investigate whether advertising expenditure is associated with sales.
marketing = pd.DataFrame({
"Advertising": [
10000, 15000, 20000,
25000, 30000, 35000,
40000
],
"Sales": [
85000, 110000, 135000,
160000, 185000, 220000,
250000
]
})
plt.scatter(
marketing["Advertising"],
marketing["Sales"]
)
plt.title("Advertising vs Sales")
plt.xlabel("Advertising Spend")
plt.ylabel("Sales")
plt.show()
employees = pd.DataFrame({
"Department": [
"IT",
"HR",
"Finance",
"Sales",
"Marketing"
],
"AverageSalary": [
85000,
60000,
75000,
70000,
68000
]
})
plt.bar(
employees["Department"],
employees["AverageSalary"]
)
plt.title("Average Salary by Department")
plt.xlabel("Department")
plt.ylabel("Average Salary")
plt.show()
A warehouse wants to visualize current stock levels.
inventory = pd.DataFrame({
"Product": [
"Laptop",
"Phone",
"Tablet",
"Monitor",
"Mouse"
],
"Stock": [
25,
8,
40,
6,
75
]
})
plt.bar(
inventory["Product"],
inventory["Stock"]
)
plt.axhline(
y=10,
linestyle="--",
label="Reorder Level"
)
plt.title("Inventory Levels")
plt.xlabel("Product")
plt.ylabel("Stock")
plt.legend()
plt.show()
import seaborn as sns
import matplotlib.pyplot as plt
sns.barplot(
data=products,
x="Product",
y="Sales"
)
plt.title("Product Sales")
plt.xticks(rotation=20)
plt.show()
Seaborn provides convenient statistical visualization functions and works naturally with Pandas DataFrames.
Box plots are useful for understanding distributions, medians, quartiles, and potential outliers.
import seaborn as sns
import matplotlib.pyplot as plt
sns.boxplot(
data=customers,
y="Age"
)
plt.title("Customer Age Distribution")
plt.show()
sns.histplot(
data=customers,
x="Age",
bins=5
)
plt.title("Customer Age Distribution")
plt.show()
sns.scatterplot(
data=marketing,
x="Advertising",
y="Sales"
)
plt.title("Advertising vs Sales")
plt.show()
Seaborn can display a fitted regression line to help visually examine a relationship between numerical variables.
sns.regplot(
data=marketing,
x="Advertising",
y="Sales"
)
plt.title("Advertising vs Sales")
plt.show()
Heatmaps are useful for displaying relationships or values across a matrix.
import seaborn as sns
import matplotlib.pyplot as plt
data = pd.DataFrame({
"Product": ["Laptop", "Phone", "Tablet"],
"Pune": [120, 150, 90],
"Mumbai": [180, 200, 120],
"Delhi": [150, 170, 100]
})
heatmap_data = data.set_index("Product")
sns.heatmap(
heatmap_data,
annot=True,
fmt="d"
)
plt.title("Product Sales by City")
plt.show()
A correlation heatmap can help summarize relationships between numerical columns.
numeric_data = pd.DataFrame({
"Advertising": [10, 20, 30, 40, 50],
"WebsiteVisitors": [100, 180, 250, 330, 420],
"Sales": [80, 140, 200, 270, 350]
})
correlation = numeric_data.corr()
sns.heatmap(
correlation,
annot=True
)
plt.title("Correlation Matrix")
plt.show()
Subplots allow multiple related visualizations to be presented together.
fig, axes = plt.subplots(
1,
2,
figsize=(12, 5)
)
axes[0].plot(
sales["Month"],
sales["Sales"],
marker="o"
)
axes[0].set_title("Monthly Sales")
axes[1].bar(
products["Product"],
products["Sales"]
)
axes[1].set_title("Product Sales")
plt.tight_layout()
plt.show()
Charts can be saved for reports, presentations, dashboards, or business documents.
plt.plot(
sales["Month"],
sales["Sales"],
marker="o"
)
plt.title("Monthly Sales")
plt.savefig(
"monthly_sales.png",
dpi=300,
bbox_inches="tight"
)
plt.show()
For financial reports, axis labels can be formatted so that values are easier to understand.
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
sales = [120000, 145000, 132000, 168000, 190000]
months = ["Jan", "Feb", "Mar", "Apr", "May"]
plt.plot(
months,
sales,
marker="o"
)
plt.gca().yaxis.set_major_formatter(
FuncFormatter(lambda x, pos: f"₹{x:,.0f}")
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
An e-commerce company wants to create several visual summaries from its order data.
import pandas as pd
import matplotlib.pyplot as plt
orders = pd.DataFrame({
"Month": [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun"
],
"Orders": [
120, 150, 175,
160, 210, 240
],
"Revenue": [
240000, 300000, 350000,
320000, 420000, 480000
]
})
fig, axes = plt.subplots(
1,
2,
figsize=(12, 5)
)
axes[0].plot(
orders["Month"],
orders["Revenue"],
marker="o"
)
axes[0].set_title("Monthly Revenue")
axes[0].set_xlabel("Month")
axes[0].set_ylabel("Revenue")
axes[1].bar(
orders["Month"],
orders["Orders"]
)
axes[1].set_title("Monthly Orders")
axes[1].set_xlabel("Month")
axes[1].set_ylabel("Orders")
plt.tight_layout()
plt.show()
employees = pd.DataFrame({
"Employee": [
"Amit",
"Priya",
"Rahul",
"Sneha",
"Vikas"
],
"Sales": [
120000,
150000,
98000,
175000,
135000
]
})
plt.figure(figsize=(9, 5))
plt.bar(
employees["Employee"],
employees["Sales"]
)
plt.title("Employee Sales Performance")
plt.xlabel("Employee")
plt.ylabel("Sales")
plt.show()
A website owner wants to visualize daily visitors.
days = [
"Mon", "Tue", "Wed",
"Thu", "Fri", "Sat", "Sun"
]
visitors = [
1200, 1350, 1500,
1480, 1800, 2400, 2200
]
plt.plot(
days,
visitors,
marker="o"
)
plt.title("Weekly Website Traffic")
plt.xlabel("Day")
plt.ylabel("Visitors")
plt.grid(True)
plt.show()
months = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun"
]
profit = [
50000, 62000, 58000,
75000, 82000, 95000
]
plt.bar(
months,
profit
)
plt.title("Monthly Profit")
plt.xlabel("Month")
plt.ylabel("Profit")
plt.show()
Line Chart
Best for trends over time, such as monthly sales or daily website traffic.
Bar Chart
Best for comparing categories such as product sales or department performance.
Pie Chart
Best for showing parts of a meaningful whole when there are only a few categories.
Scatter Plot
Best for investigating relationships between two numerical variables.
Histogram
Best for understanding the distribution of numerical data.
Heatmap
Useful for matrices, correlation analysis, and comparing values across two dimensions.
| Business Question | Recommended Chart |
|---|---|
| How are sales changing over time? | Line Chart |
| Which product sells the most? | Bar Chart |
| What percentage does each category contribute? | Pie Chart |
| Are advertising and sales related? | Scatter Plot |
| How are customer ages distributed? | Histogram |
| How do numerical variables relate to each other? | Heatmap |
A company wants to compare multiple product categories across several months.
months = [
"Jan", "Feb", "Mar",
"Apr", "May"
]
electronics = [
120000, 140000, 155000,
170000, 190000
]
clothing = [
90000, 100000, 110000,
125000, 135000
]
home = [
70000, 85000, 80000,
95000, 105000
]
plt.plot(
months,
electronics,
marker="o",
label="Electronics"
)
plt.plot(
months,
clothing,
marker="o",
label="Clothing"
)
plt.plot(
months,
home,
marker="o",
label="Home"
)
plt.title("Category Sales Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.grid(True)
plt.show()
In a real dashboard, these metrics would be calculated directly from the underlying business dataset rather than manually entered.
fig, axes = plt.subplots(
2,
2,
figsize=(12, 8)
)
# Revenue trend
axes[0, 0].plot(
revenue["Month"],
revenue["Revenue"],
marker="o"
)
axes[0, 0].set_title("Revenue Trend")
# Product comparison
axes[0, 1].bar(
products["Product"],
products["Sales"]
)
axes[0, 1].set_title("Product Sales")
axes[0, 1].tick_params(axis="x", rotation=20)
# Customer age distribution
axes[1, 0].hist(
customers["Age"],
bins=5
)
axes[1, 0].set_title("Customer Age")
# Advertising relationship
axes[1, 1].scatter(
marketing["Advertising"],
marketing["Sales"]
)
axes[1, 1].set_title("Advertising vs Sales")
plt.tight_layout()
plt.show()
The following example demonstrates a complete workflow using a real-world style sales dataset.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sales = pd.DataFrame({
"Product": [
"Laptop", "Phone", "Laptop",
"Tablet", "Phone", "Monitor",
"Tablet", "Phone"
],
"City": [
"Pune", "Mumbai", "Delhi",
"Pune", "Mumbai", "Delhi",
"Pune", "Delhi"
],
"Quantity": [
2, 4, 1, 5,
3, 2, 4, 5
],
"Price": [
60000, 30000, 60000, 25000,
30000, 20000, 25000, 30000
]
})
# Calculate sales
sales["Revenue"] = (
sales["Quantity"] *
sales["Price"]
)
# Product summary
product_summary = sales.groupby(
"Product"
)["Revenue"].sum().reset_index()
# City summary
city_summary = sales.groupby(
"City"
)["Revenue"].sum().reset_index()
# Create dashboard
fig, axes = plt.subplots(
1,
2,
figsize=(13, 5)
)
# Product chart
sns.barplot(
data=product_summary,
x="Product",
y="Revenue",
ax=axes[0]
)
axes[0].set_title("Revenue by Product")
axes[0].tick_params(axis="x", rotation=20)
# City chart
sns.barplot(
data=city_summary,
x="City",
y="Revenue",
ax=axes[1]
)
axes[1].set_title("Revenue by City")
plt.tight_layout()
plt.show()
Annotations can highlight important values or events.
months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [120000, 145000, 132000, 168000, 190000]
plt.plot(
months,
sales,
marker="o"
)
max_sales = max(sales)
max_month = months[sales.index(max_sales)]
plt.annotate(
"Highest Sales",
xy=(max_month, max_sales),
xytext=(max_month, max_sales + 15000),
arrowprops=dict(arrowstyle="->")
)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
- Collect the relevant data.
- Clean and validate the data.
- Understand the variables and their data types.
- Identify the business question.
- Select an appropriate visualization.
- Create the chart.
- Add meaningful titles and labels.
- Check the visualization for misleading presentation.
- Interpret the result in context.
- Use the insight to support reporting or decisions.
- Start with a clear business or analytical question.
- Use the simplest chart that communicates the result clearly.
- Choose line charts for ordered trends and time series.
- Use bar charts for category comparisons.
- Use scatter plots for relationships between numerical variables.
- Use histograms for distributions.
- Use pie charts only when part-to-whole comparison is meaningful.
- Use meaningful titles and axis labels.
- Keep charts readable and avoid unnecessary clutter.
- Always interpret charts using the context of the underlying data.
- Check for missing values and outliers before visualization.
- Do not imply causation from a visual association alone.
- Save important visualizations at an appropriate resolution.
| Library | Main Use | Common Functions |
|---|---|---|
| Matplotlib | General-purpose plotting | plot(), bar(), scatter() |
| Seaborn | Statistical visualization | barplot(), boxplot(), heatmap() |
| Pandas | Quick DataFrame visualization | df.plot() |
This final example combines Pandas, Matplotlib, and Seaborn to create a small business visualization workflow.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# -----------------------------
# 1. Create sales data
# -----------------------------
sales = pd.DataFrame({
"Month": [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun"
],
"Orders": [
120, 150, 175,
190, 220, 250
],
"Revenue": [
240000, 300000, 350000,
390000, 450000, 520000
]
})
# -----------------------------
# 2. Create product data
# -----------------------------
products = pd.DataFrame({
"Product": [
"Laptop",
"Phone",
"Tablet",
"Monitor",
"Headphones"
],
"Revenue": [
450000,
380000,
220000,
170000,
90000
]
})
# -----------------------------
# 3. Create city data
# -----------------------------
cities = pd.DataFrame({
"City": [
"Pune",
"Mumbai",
"Delhi",
"Bangalore",
"Chennai"
],
"Revenue": [
320000,
450000,
390000,
520000,
280000
]
})
# -----------------------------
# 4. Create dashboard
# -----------------------------
fig, axes = plt.subplots(
2,
2,
figsize=(14, 9)
)
# Monthly revenue
axes[0, 0].plot(
sales["Month"],
sales["Revenue"],
marker="o"
)
axes[0, 0].set_title(
"Monthly Revenue"
)
axes[0, 0].set_xlabel("Month")
axes[0, 0].set_ylabel("Revenue")
axes[0, 0].grid(True)
# Monthly orders
axes[0, 1].bar(
sales["Month"],
sales["Orders"]
)
axes[0, 1].set_title(
"Monthly Orders"
)
axes[0, 1].set_xlabel("Month")
axes[0, 1].set_ylabel("Orders")
# Product revenue
sns.barplot(
data=products,
x="Product",
y="Revenue",
ax=axes[1, 0]
)
axes[1, 0].set_title(
"Revenue by Product"
)
axes[1, 0].tick_params(
axis="x",
rotation=20
)
# City revenue
sns.barplot(
data=cities,
x="City",
y="Revenue",
ax=axes[1, 1]
)
axes[1, 1].set_title(
"Revenue by City"
)
axes[1, 1].tick_params(
axis="x",
rotation=20
)
plt.tight_layout()
plt.savefig(
"ecommerce_dashboard.png",
dpi=300,
bbox_inches="tight"
)
plt.show()
- Understand the data before creating charts.
- Define the question that the visualization should answer.
- Choose the chart type according to the data and question.
- Use line charts for trends and ordered data.
- Use bar charts for category comparisons.
- Use scatter plots for numerical relationships.
- Use histograms for distributions.
- Use heatmaps for matrices and correlation summaries.
- Use clear titles and axis labels.
- Keep visualizations simple and readable.
- Do not distort comparisons with inappropriate scales.
- Always inspect the underlying data before interpreting a chart.
- Remember that correlation or visual association does not automatically imply causation.
- Use visualizations to communicate evidence and patterns clearly.
Python Data Visualization • Real-Time Examples • Data Analysis Learning