100 Exercises / Python / 100 Python Exercises for Data Analysis
Summarizing and Plotting Annual Sales with Polars and Matplotlib
Summarize annual sensor sales with Polars and Matplotlib. Build charts and a report, and distinguish correlation from causation and price elasticity.
100 Exercises Chapter 10 (No.091-No.100): Aggregation/Visualization/Mini analysis
This is Chapter 10 (No.091–100) of 100 Python Exercises for Data Analysis. This chapter covers aggregation, dates, charts, and correlation using fictional annual industrial-sensor sales data.
About this material These notebooks were used in corporate training by Surikobo or its representative, Hiroshi Wayama, and were adapted for publication with permission. All data are fictional and do not represent actual company or factory results.
Example task
This is year-end work for Mr. M, a corporate planning team of an industrial sensor manufacturer.
Regular work at the end of the year
1. Export all transaction data for 2024 from the sales system as CSV (301 records)
2. Total annual sales by product category (temperature, pressure, flow rate, vibration, current sensors)
3. Create a monthly sales trend graph and report it to the board of directors
4. Check the correlation between unit price and quantity and consider next year's pricing strategy
5. Output all of the above as one analysis report
Use Polars and Matplotlib to summarize 301 records with nine columns by product and month. This final chapter combines the skills introduced throughout the series.
Common situations in the field
| Scene | Task |
|---|---|
| Category aggregation | Manual aggregation of sales by product category using Excel pivot (more than 1 hour each month) |
| Monthly trends | Manually updating monthly sales graphs in Excel (many copy and paste errors) |
| Check the distribution | Understand the dispersion of transaction amounts just by intuition (overlooking outliers) |
| Correlation analysis | Judging by intuition that “It seems that products with high unit prices will not sell in quantity” |
| Report creation | Manage totals, graphs, and comments in separate files (inconsistency) |
This time’s goal: Aggregation with Python → Visualization → Correlation analysis → Report output Build a reproducible annual analysis pipeline in a single notebook.
Common mistakes
- Aggregation: Use
sumfor total sales andmeanfor the mean transaction price. Check what each observation represents before averaging. - Date types and formats: This example extracts months from
Datevalues. Zero-padded year-month strings such as2024-09also sort chronologically; unpadded strings such as2024-9and2024-10do not. - Histogram bins: Too few bins hide features; too many emphasize small fluctuations. Start with the square-root rule or Sturges’ rule , then inspect alternatives.
- Correlation and causation: A negative price–quantity correlation does not show that reducing a price would increase quantity.
- Chart units: Check units and scales. When using two axes for different units, do not infer a relationship just because the plotted lines appear close.
Exercises in this chapter
| No. | Title | Usage in manufacturing industry |
|---|---|---|
| 091 | Aggregation by category using group_by | Aggregation of annual sales by product category and customer type |
| 092 | Aggregating sales by product | Identifying main products by sales ranking by product name |
| 093 | Converting a date column to Datetime type | Type conversion for accurate time series aggregation of year and month |
| 094 | Totaling monthly sales | Understanding monthly sales trends and seasonality |
| 095 | Draw a line graph with matplotlib | Visualize monthly sales trends |
| 096 | Visualize sales by category with a bar graph | Composition ratio by product category and customer type |
| 097 | View the distribution of numbers with a histogram | Detect outliers and bias from the transaction amount and unit price distribution |
| 098 | View the relationship between two variables with a scatter plot | Consider pricing strategies with a scatter plot of unit price vs. quantity |
| 099 | Check the correlation coefficient | Factor analysis using the correlation coefficient matrix between sales KPIs |
| 100 | Load sales data and create an analysis report | Output totals, graphs, and summaries all at once with one script |
Preparing the Python environment
Run cells in order from the top. Outputs are examples; the OS, versions, and file paths vary by environment. The setup cells import libraries and configure random data and plotting.
import platform
import sys
print(f"OS: {platform.platform()}")
print(f"Python: {sys.version.split()[0]}")
OS: macOS-26.5.2-arm64-arm-64bit-Mach-O
Python: 3.14.4
Setup: Imports and display settings (expand)
import numpy as np
import polars as pl
import matplotlib
import matplotlib.pyplot as plt
import csv, os, datetime
matplotlib.rcParams['font.family'] = 'Hiragino Maru Gothic Pro'
%config InlineBackend.figure_format = 'svg'
np.random.seed(42)
print("Library loading completed")
print(f" NumPy : {np.__version__}")
print(f" Polars : {pl.__version__}")
print(f" Matplotlib: {matplotlib.__version__}")
Library loading completed
NumPy : 2.5.1
Polars : 1.42.1
Matplotlib: 3.11.0
Creating the sample data
Assumed scenario: Industrial sensor manufacturer/management planning team
Period: January to December 2024 (total 12 months)
Product: 5 categories (temperature, pressure, flow rate, vibration, current sensor)
Customer: 5 types (automobile, food, semiconductor, medical, general industry)
Output: Annual sales performance CSV (sensor_sales_2024.csv)
Setup: Generate the sample data (expand)
np.random.seed(42)
# Product category settings
PRODUCTS = {
"temperature sensor": {"prefix": "TS", "price_lo": 8_000, "price_hi": 25_000, "base_qty": 50, "weight": 0.28},
"pressure sensor": {"prefix": "PS", "price_lo": 12_000, "price_hi": 45_000, "base_qty": 32, "weight": 0.22},
"flow sensor": {"prefix": "FS", "price_lo": 18_000, "price_hi": 62_000, "base_qty": 24, "weight": 0.18},
"vibration sensor": {"prefix": "VS", "price_lo": 22_000, "price_hi": 80_000, "base_qty": 18, "weight": 0.14},
"current sensor": {"prefix": "CS", "price_lo": 5_000, "price_hi": 18_000, "base_qty": 60, "weight": 0.18},
}
CAT_NAMES = list(PRODUCTS.keys())
CAT_WEIGHTS = [v["weight"] for v in PRODUCTS.values()]
CUST_TYPES = ["automobile", "food", "semiconductor", "medical", "General industry"]
CUST_WEIGHTS = [0.32, 0.22, 0.24, 0.14, 0.08]
# Monthly seasonality (1.0 = average)
SEASONALITY = [0.85, 0.80, 0.95, 1.00, 1.05, 1.10,
0.92, 0.88, 1.10, 1.15, 1.22, 0.98]
records = []
for month in range(1, 13):
s = SEASONALITY[month - 1]
n = max(18, min(38, int(np.random.normal(26, 5))))
for _ in range(n):
cat = np.random.choice(CAT_NAMES, p=CAT_WEIGHTS)
info = PRODUCTS[cat]
model = np.random.choice(["A", "B", "C", "S"])
product_name = f"{info['prefix']}-{model}"
cust_type = np.random.choice(CUST_TYPES, p=CUST_WEIGHTS)
cust_id = f"{cust_type[:2]}-{np.random.randint(1000, 9999):04d}"
# Unit price: Category-specific range × seasonal variation
unit_price = int(np.random.uniform(info['price_lo'], info['price_hi']))
# Quantity: The higher the unit price, the lower the quantity (create an inverse correlation)
price_mid = (info['price_lo'] + info['price_hi']) / 2
qty_factor = 1.5 - (unit_price / price_mid) * 0.5
quantity = max(1, int(np.random.normal(info['base_qty'] * s * qty_factor,
info['base_qty'] * 0.25)))
sales_amount = unit_price * quantity
# Return flag (slightly higher for higher unit prices)
ret_prob = 0.02 + (unit_price - info['price_lo']) / (info['price_hi'] - info['price_lo']) * 0.04
is_returned = 1 if np.random.random() < ret_prob else 0
day = np.random.randint(1, 29)
date_str = f"2024-{month:02d}-{day:02d}"
records.append({
"date": date_str,
"product_category": cat,
"product_name": product_name,
"customer_type": cust_type,
"customer_id": cust_id,
"quantity": quantity,
"unit_price": unit_price,
"sales_amount": sales_amount,
"is_returned": is_returned,
})
CSV_PATH = "sensor_sales_2024.csv"
with open(CSV_PATH, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=records[0].keys())
writer.writeheader()
writer.writerows(records)
print(f"Generation completed: {CSV_PATH}")
print(f" Number of records : {len(records):,} records")
print(f" number of columns : {len(records[0])} columns")
print(f" period : 2024-01-01 ~ 2024-12-28")
print(f" Total sales amount : {sum(r['sales_amount'] for r in records):,} JPY")
print(f" Number of returned items : {sum(r['is_returned'] for r in records)} records")
Generation completed: sensor_sales_2024.csv
Number of records : 301 records
number of columns : 9 columns
period : 2024-01-01 ~ 2024-12-28
Total sales amount : 239,354,914 JPY
Number of returned items : 10 records
No.091: Aggregate by category with group_by
Use in practice
group_by is the core of aggregation operations in the manufacturing industry. “Aggregating annual sales by product category” “Understanding the number of transactions by customer type”
These operations are equivalent to Excel’s pivot table, but
With Python/Polars, this can be achieved with one line of code, and the speed will not decrease even as the amount of data increases.
Main uses in manufacturing industry:
- Monthly count of defects by line and product
- Understand the number of orders and sales amount by customer type
- Aggregation of average cycle time by process
Approach
Basic syntax of group_by:
Syntax example (fragment)
df.group_by("category column").agg([
pl.col("numeric string").sum().alias("Total"),
pl.col("numeric string").mean().alias("average"),
pl.len().alias("Number of cases"),
])
The choice of aggregation function is important. sum (total) is used to understand the overall scale.
mean (average) is used to compare performance per unit. By calculating both simultaneously, you can evaluate scale and efficiency side by side.
Check with Python
# Load CSV (reuse for subsequent exercises)
df_raw = pl.read_csv(CSV_PATH, try_parse_dates=False)
# Summary by product category
cat_summary = (
df_raw.group_by("product_category")
.agg([
pl.col("sales_amount").sum().alias("total_sales"),
pl.col("quantity").sum().alias("total_qty"),
pl.col("unit_price").mean().alias("avg_unit_price"),
pl.len().alias("transaction_count"),
])
.sort("total_sales", descending=True)
)
print("Aggregation by product category:")
print(cat_summary)
print()
# Aggregation by customer type
cust_summary = (
df_raw.group_by("customer_type")
.agg([
pl.col("sales_amount").sum().alias("total_sales"),
pl.len().alias("transaction_count"),
pl.col("is_returned").mean().alias("return_rate"),
])
.sort("total_sales", descending=True)
)
print("Aggregation by customer type:")
print(cust_summary)
Aggregation by product category:
shape: (5, 5)
┌────────────────────┬─────────────┬───────────┬────────────────┬───────────────────┐
│ product_category ┆ total_sales ┆ total_qty ┆ avg_unit_price ┆ transaction_count │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ f64 ┆ u32 │
╞════════════════════╪═════════════╪═══════════╪════════════════╪═══════════════════╡
│ flow sensor ┆ 64369428 ┆ 1658 ┆ 40617.757143 ┆ 70 │
│ temperature sensor ┆ 60772674 ┆ 4166 ┆ 15267.060241 ┆ 83 │
│ vibration sensor ┆ 41410765 ┆ 781 ┆ 55833.916667 ┆ 48 │
│ pressure sensor ┆ 41210887 ┆ 1610 ┆ 27255.176471 ┆ 51 │
│ current sensor ┆ 31591160 ┆ 2833 ┆ 11778.877551 ┆ 49 │
└────────────────────┴─────────────┴───────────┴────────────────┴───────────────────┘
Aggregation by customer type:
shape: (5, 4)
┌──────────────────┬─────────────┬───────────────────┬─────────────┐
│ customer_type ┆ total_sales ┆ transaction_count ┆ return_rate │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ u32 ┆ f64 │
╞══════════════════╪═════════════╪═══════════════════╪═════════════╡
│ automobile ┆ 84512570 ┆ 105 ┆ 0.028571 │
│ semiconductor ┆ 53920928 ┆ 70 ┆ 0.071429 │
│ food ┆ 48413908 ┆ 60 ┆ 0.0 │
│ medical ┆ 36645931 ┆ 47 ┆ 0.021277 │
│ General industry ┆ 15861577 ┆ 19 ┆ 0.052632 │
└──────────────────┴─────────────┴───────────────────┴─────────────┘
Interpreting the results
Compare total sales, mean unit price, quantity, and transaction count in the category summary. Sales and mean price alone do not reveal differences in quantities or transaction counts.
The return rate by customer type is the share of transactions marked as returned. Investigate counts, product mix, and return reasons before interpreting a difference. Combining group_by with sort orders the summary by sales.
No.092: Aggregate sales by product
Use in practice
Summarizing sales by product model shows each model’s share of total sales. This informs inventory and production planning, but decisions to discontinue a model or increase output also need margins, demand, and supply constraints.
Approach
Sort products by sales and calculate the cumulative share of the top products:
Here is the sales amount of the product ranked , and is the number of products. The 80:20 rule is a heuristic for concentration, not a guaranteed result. This example assigns A when the cumulative share after adding a product is at most 70%, B when it is at most 90%, and C otherwise.
Check with Python
# Sales ranking by product name
product_ranking = (
df_raw.group_by("product_name")
.agg([
pl.col("sales_amount").sum().alias("total_sales"),
pl.col("quantity").sum().alias("total_qty"),
pl.col("unit_price").mean().alias("avg_price"),
pl.len().alias("count"),
])
.sort("total_sales", descending=True)
)
# Cumulative sales ratio (preparation for ABC analysis)
total = product_ranking["total_sales"].sum()
cumsum = product_ranking["total_sales"].cum_sum()
product_ranking = product_ranking.with_columns(
(cumsum / total * 100).alias("cumulative_pct")
)
print("Sales ranking by product name (top 10):")
print(product_ranking.head(10))
print()
# ABC classification
a_products = product_ranking.filter(pl.col("cumulative_pct") <= 70)
b_products = product_ranking.filter((pl.col("cumulative_pct") > 70) & (pl.col("cumulative_pct") <= 90))
c_products = product_ranking.filter(pl.col("cumulative_pct") > 90)
print(f"ABC Analysis results:")
print(f" A Rank (cumulative 0~70%) : {len(a_products)} product")
print(f" B Rank (cumulative 70~90%): {len(b_products)} product")
print(f" C Rank (cumulative 90~100%): {len(c_products)} product")
print(f" Total number of products: {len(product_ranking)} product")
Sales ranking by product name (top 10):
shape: (10, 6)
┌──────────────┬─────────────┬───────────┬──────────────┬───────┬────────────────┐
│ product_name ┆ total_sales ┆ total_qty ┆ avg_price ┆ count ┆ cumulative_pct │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ f64 ┆ u32 ┆ f64 │
╞══════════════╪═════════════╪═══════════╪══════════════╪═══════╪════════════════╡
│ TS-A ┆ 20271994 ┆ 1427 ┆ 14894.714286 ┆ 28 ┆ 8.469429 │
│ FS-S ┆ 19761553 ┆ 556 ┆ 37514.227273 ┆ 22 ┆ 16.725601 │
│ FS-A ┆ 19456558 ┆ 461 ┆ 43442.75 ┆ 20 ┆ 24.854349 │
│ TS-S ┆ 16905889 ┆ 1089 ┆ 16451.045455 ┆ 22 ┆ 31.917454 │
│ FS-B ┆ 15942962 ┆ 425 ┆ 39620.166667 ┆ 18 ┆ 38.578258 │
│ VS-C ┆ 12852436 ┆ 278 ┆ 48262.533333 ┆ 15 ┆ 43.947872 │
│ PS-C ┆ 12773479 ┆ 418 ┆ 31347.071429 ┆ 14 ┆ 49.284499 │
│ TS-C ┆ 12341172 ┆ 774 ┆ 16469.6875 ┆ 16 ┆ 54.440513 │
│ VS-A ┆ 11598360 ┆ 216 ┆ 57092.923077 ┆ 13 ┆ 59.286187 │
│ TS-B ┆ 11253619 ┆ 876 ┆ 13216.235294 ┆ 17 ┆ 63.987833 │
└──────────────┴─────────────┴───────────┴──────────────┴───────┴────────────────┘
ABC Analysis results:
A Rank (cumulative 0~70%) : 11 product
B Rank (cumulative 70~90%): 5 product
C Rank (cumulative 90~100%): 4 product
Total number of products: 20 product
Interpreting the results
cum_sum() gives cumulative sales and their share of the total. Under this rule, the product that first pushes the share above 70% is B, so A products need not total exactly 70%. Document both the thresholds and how boundary-crossing products are handled. Do not decide stocking levels or discontinuation from sales rank alone.
No.093: Convert a date column to Date
Use in practice
This example converts date strings to Date, enabling dt operations such as extracting years and months. Strings such as "2024-9" and "2024-10" do not sort chronologically. Consistently formatted, zero-padded year-month strings such as "2024-09" do sort in chronological order.
Approach
Flow of date type conversion in Polars:
| Steps | Operations | Polars Code |
|---|---|---|
| ① String → Date type | Convert with str.to_date | pl.col("date").str.to_date("%Y-%m-%d") |
| ② Extract the year | dt.year | pl.col("date").dt.year() |
| ③ Extract the month | dt.month | pl.col("date").dt.month() |
| ④ Generate year and month string | dt.to_string | pl.col("date").dt.to_string("%Y-%m") |
| ⑤ Sort by date | sort("date") | Sort by date instead of string |
Check with Python
# Convert date column to Date type
df = df_raw.with_columns(
pl.col("date").str.to_date("%Y-%m-%d")
)
# Add year/month/year/month columns
df = df.with_columns([
pl.col("date").dt.year().alias("year"),
pl.col("date").dt.month().alias("month"),
pl.col("date").dt.to_string("%Y-%m").alias("year_month"),
])
print("Schema after date type conversion:")
for col, dtype in df.schema.items():
print(f" {col:22s}: {dtype}")
print()
print("First 3 lines (confirm date column, year, month, year_month):")
print(df.select(["date", "year", "month", "year_month"]).head(3))
print()
# Comparison before and after type conversion
print("Check type conversion:")
print(f" Before conversion: {df_raw['date'].dtype} example: {df_raw['date'][0]}")
print(f" After conversion: {df['date'].dtype} example: {df['date'][0]}")
print()
# Confirm the list of months (sorting is by date, not by string)
months_sorted = df["year_month"].unique().sort()
print("List of years and months (sort confirmation):")
print(months_sorted.to_list())
Schema after date type conversion:
date : Date
product_category : String
product_name : String
customer_type : String
customer_id : String
quantity : Int64
unit_price : Int64
sales_amount : Int64
is_returned : Int64
year : Int32
month : Int8
year_month : String
First 3 lines (confirm date column, year, month, year_month):
shape: (3, 4)
┌────────────┬──────┬───────┬────────────┐
│ date ┆ year ┆ month ┆ year_month │
│ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ i32 ┆ i8 ┆ str │
╞════════════╪══════╪═══════╪════════════╡
│ 2024-01-24 ┆ 2024 ┆ 1 ┆ 2024-01 │
│ 2024-01-28 ┆ 2024 ┆ 1 ┆ 2024-01 │
│ 2024-01-27 ┆ 2024 ┆ 1 ┆ 2024-01 │
└────────────┴──────┴───────┴────────────┘
Check type conversion:
Before conversion: String example: 2024-01-24
After conversion: Date example: 2024-01-24
List of years and months (sort confirmation):
['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06', '2024-07', '2024-08', '2024-09', '2024-10', '2024-11', '2024-12']
Interpreting the results
Converting strings with str.to_date("%Y-%m-%d") enables operations such as dt.year() and dt.month(). The year-month strings produced by dt.to_string("%Y-%m") are zero-padded, so they sort from 2024-01 to 2024-12 even as strings. Later examples use this date-converted df.
No.094: Summarize monthly sales
Use in practice
Monthly sales trends is the KPI most frequently reported at management meetings and board of directors meetings. The starting point for analysis is This month is +5% compared to last month'' or Q4 is +12% compared to the same period last year.”
Monthly tally. Instantly create monthly summary tables with Polars’ group_by + sort.
Approach
In addition to monthly aggregation, by calculating month-on-month growth rate You can understand acceleration and deceleration of trends.
Month-on-month growth rate:
Here, is the monthly sales amount of . Because the manufacturing industry is affected by seasonality (busy season/off season), In addition to month-on-month changes, year-on-year change (YoY) is also important. In this chapter, we will focus on the month-on-month comparison.
Check with Python
# Monthly sales summary
monthly = (
df.group_by("year_month")
.agg([
pl.col("sales_amount").sum().alias("monthly_sales"),
pl.col("quantity").sum().alias("monthly_qty"),
pl.col("unit_price").mean().alias("avg_unit_price"),
pl.len().alias("transaction_count"),
pl.col("is_returned").sum().alias("return_count"),
])
.sort("year_month")
)
# Added month-on-month growth rate
sales_list = monthly["monthly_sales"].to_list()
mom_list = [None] + [
(round((sales_list[i] - sales_list[i-1]) / sales_list[i-1] * 100, 1)
if sales_list[i-1] != 0 else None)
for i in range(1, len(sales_list))
]
monthly = monthly.with_columns(
pl.Series("mom_growth_pct", mom_list, dtype=pl.Float64)
)
print("Monthly sales summary (with growth rate compared to previous month):")
print(monthly)
print()
# Quarterly summary
q_map = {"Q1": [1,2,3], "Q2": [4,5,6], "Q3": [7,8,9], "Q4": [10,11,12]}
print("Total sales by quarter:")
for q, months_in_q in q_map.items():
q_sales = df.filter(pl.col("month").is_in(months_in_q))["sales_amount"].sum()
print(f" {q}: {q_sales:>12,} JPY")
print(f" yearly: {df['sales_amount'].sum():>12,} JPY")
Monthly sales summary (with growth rate compared to previous month):
shape: (12, 7)
┌────────────┬──────────────┬─────────────┬──────────────┬─────────────┬─────────────┬─────────────┐
│ year_month ┆ monthly_sale ┆ monthly_qty ┆ avg_unit_pri ┆ transaction ┆ return_coun ┆ mom_growth_ │
│ --- ┆ s ┆ --- ┆ ce ┆ _count ┆ t ┆ pct │
│ str ┆ --- ┆ i64 ┆ --- ┆ --- ┆ --- ┆ --- │
│ ┆ i64 ┆ ┆ f64 ┆ u32 ┆ i64 ┆ f64 │
╞════════════╪══════════════╪═════════════╪══════════════╪═════════════╪═════════════╪═════════════╡
│ 2024-01 ┆ 19526168 ┆ 862 ┆ 27905.642857 ┆ 28 ┆ 3 ┆ null │
│ 2024-02 ┆ 17564379 ┆ 795 ┆ 28723.214286 ┆ 28 ┆ 1 ┆ -10.0 │
│ 2024-03 ┆ 22823593 ┆ 917 ┆ 33778.551724 ┆ 29 ┆ 0 ┆ 29.9 │
│ 2024-04 ┆ 15582567 ┆ 729 ┆ 28245.157895 ┆ 19 ┆ 0 ┆ -31.7 │
│ 2024-05 ┆ 22778096 ┆ 987 ┆ 30078.125 ┆ 24 ┆ 1 ┆ 46.2 │
│ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … │
│ 2024-08 ┆ 20222658 ┆ 774 ┆ 33197.814815 ┆ 27 ┆ 2 ┆ 13.8 │
│ 2024-09 ┆ 25273346 ┆ 1271 ┆ 25750.896552 ┆ 29 ┆ 1 ┆ 25.0 │
│ 2024-10 ┆ 21004719 ┆ 1095 ┆ 26097.48 ┆ 25 ┆ 0 ┆ -16.9 │
│ 2024-11 ┆ 22322934 ┆ 1083 ┆ 28648.75 ┆ 24 ┆ 0 ┆ 6.3 │
│ 2024-12 ┆ 16845974 ┆ 770 ┆ 28388.434783 ┆ 23 ┆ 0 ┆ -24.5 │
└────────────┴──────────────┴─────────────┴──────────────┴─────────────┴─────────────┴─────────────┘
Total sales by quarter:
Q1: 59,914,140 JPY
Q2: 56,000,968 JPY
Q3: 63,266,179 JPY
Q4: 60,173,627 JPY
yearly: 239,354,914 JPY
Interpreting the results
Monthly summaries show increases and decreases from the previous month. The first month has no previous observation, so its growth rate is null. The usual growth rate is also undefined when the previous month’s sales are zero.
One year of data does not establish a recurring seasonal pattern. Compare multiple years and order conditions to investigate seasonality. This synthetic dataset includes monthly factors chosen during generation.
No.095: Draw a line graph with matplotlib
Use in practice
Line graphs are a great way to visualize trends in time series data. By expressing monthly sales trends in a line graph,
In which month did it sharply increase or decrease sharply?'' Is it going to increase towards Q4?”
This will be communicated to management at a glance. Graphs are better than tables of numbers.
Speed of decision making is greatly increased.
Approach
Important setting items when creating a time series graph:
| Setting | Meaning | Code |
|---|---|---|
marker="o" | Display each data point as a circle | plt.plot(..., marker="o") |
grid=True | Easy to read with grid lines | ax.grid(alpha=0.3) |
xlabel/ylabel | Axis label (specify unit) | ax.set_xlabel("Month") |
title | Graph title | ax.set_title(...) |
tight_layout | Automatically adjust margins | plt.tight_layout() |
In a manufacturing report, adjust the lower limit of the y-axis if you want to emphasize vertical variation, Care must be taken not to excessively exaggerate fluctuations.
Check with Python
months_str = monthly["year_month"].to_list() # ["2024-01", ..., "2024-12"]
sales_vals = monthly["monthly_sales"].to_list()
qty_vals = monthly["monthly_qty"].to_list()
x_idx = list(range(len(months_str)))
fig, axes = plt.subplots(2, 1, figsize=(11, 8), sharex=True)
# ── Upper row: Monthly sales amount trends ──
ax1 = axes[0]
ax1.plot(x_idx, sales_vals, marker="o", linewidth=2, color="#4878CF",
markersize=6, label="Monthly sales amount")
ax1.fill_between(x_idx, sales_vals, alpha=0.12, color="#4878CF")
# Highlight the maximum and minimum months
max_i = sales_vals.index(max(sales_vals))
min_i = sales_vals.index(min(sales_vals))
ax1.scatter([max_i], [sales_vals[max_i]], color="#D65F5F", s=100, zorder=5, label=f"maximum: {months_str[max_i]}")
ax1.scatter([min_i], [sales_vals[min_i]], color="#6ACC65", s=100, zorder=5, label=f"minimum: {months_str[min_i]}")
ax1.set_title("Monthly sales trends in 2024", fontsize=13, pad=12)
ax1.set_ylabel("Sales amount (yen)", fontsize=10)
ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e6:.1f}M"))
ax1.grid(axis="y", alpha=0.3)
ax1.legend(fontsize=9)
# ── Bottom row: Monthly sales volume trends ──
ax2 = axes[1]
ax2.plot(x_idx, qty_vals, marker="s", linewidth=2, color="#6ACC65",
markersize=6, linestyle="--", label="Monthly sales volume")
ax2.set_title("2024 Monthly Sales Volume Trend", fontsize=13, pad=12)
ax2.set_xlabel("Month", fontsize=10)
ax2.set_ylabel("Sales quantity (pieces)", fontsize=10)
ax2.set_xticks(x_idx)
ax2.set_xticklabels([m[5:] for m in months_str], fontsize=9) # "01"~"12"
ax2.grid(axis="y", alpha=0.3)
ax2.legend(fontsize=9)
plt.tight_layout()
plt.savefig("no095_monthly_trend.svg", format="svg", bbox_inches="tight")
plt.show()
print("Saved: no095_monthly_trend.svg")
Saved: no095_monthly_trend.svg
Interpreting the results
The upper chart shows monthly sales, with the largest and smallest months marked. The lower chart shows quantities on the same time axis. If quantity rises without a matching sales increase, examine average prices and product mix. fill_between shades the area, and sharex=True aligns the two plots.
No.096: Visualize sales by category with bar graphs
Use in practice
Bar graphs are great for comparisons between categories. By visualizing sales by product category and customer type in bar graphs, “Which product should we focus our management resources on?” “Which customer segment should we prioritize?” Supports decision-making with numbers and graphs.
Approach
Stacked bar charts are also useful for comparing multiple categories. When sales by customer type are accumulated by product category, You can see a 2D breakdown such as “Which products are selling the most for automobiles?”
Also, if you add numeric labels to the bar chart, Communicate graphs and numbers at the same time: Syntax example (fragment)
for bar in bars:
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(),
f"{bar.get_height():,.0f}", ha='center', va='bottom')
Check with Python
# Total by category
cat_sales = (
df.group_by("product_category")
.agg(pl.col("sales_amount").sum().alias("total_sales"))
.sort("total_sales", descending=True)
)
cust_sales = (
df.group_by("customer_type")
.agg(pl.col("sales_amount").sum().alias("total_sales"))
.sort("total_sales", descending=True)
)
fig, axes = plt.subplots(1, 2, figsize=(13, 6))
COLORS = ["#4878CF", "#6ACC65", "#D65F5F", "#B47CC7", "#C4AD66"]
# ── Left: Sales by product category ──
ax1 = axes[0]
cats = cat_sales["product_category"].to_list()
csales = cat_sales["total_sales"].to_list()
bars1 = ax1.bar(cats, csales, color=COLORS[:len(cats)], alpha=0.85, edgecolor="black", linewidth=0.4)
for bar in bars1:
ax1.text(bar.get_x() + bar.get_width() / 2,
bar.get_height() + max(csales) * 0.01,
f"{bar.get_height()/1e6:.1f}M", ha="center", va="bottom", fontsize=8)
ax1.set_title("Annual sales by product category", fontsize=12, pad=12)
ax1.set_xlabel("Product category", fontsize=10)
ax1.set_ylabel("Sales amount (yen)", fontsize=10)
ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e6:.0f}M"))
ax1.grid(axis="y", alpha=0.3)
ax1.tick_params(axis="x", labelsize=8)
# ── Right: Sales by customer type ──
ax2 = axes[1]
custs = cust_sales["customer_type"].to_list()
cssales = cust_sales["total_sales"].to_list()
bars2 = ax2.bar(custs, cssales, color=COLORS[:len(custs)], alpha=0.85, edgecolor="black", linewidth=0.4)
for bar in bars2:
ax2.text(bar.get_x() + bar.get_width() / 2,
bar.get_height() + max(cssales) * 0.01,
f"{bar.get_height()/1e6:.1f}M", ha="center", va="bottom", fontsize=8)
ax2.set_title("Annual sales by customer type", fontsize=12, pad=12)
ax2.set_xlabel("customer type", fontsize=10)
ax2.set_ylabel("Sales amount (yen)", fontsize=10)
ax2.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e6:.0f}M"))
ax2.grid(axis="y", alpha=0.3)
ax2.tick_params(axis="x", labelsize=8)
plt.tight_layout()
plt.savefig("no096_category_bar.svg", format="svg", bbox_inches="tight")
plt.show()
print("Saved: no096_category_bar.svg")
Saved: no096_category_bar.svg
Interpreting the results
The bars compare sales by product category and customer type, showing larger contributors and sales concentration. Sales are not profit, so investment priorities also require margins, demand, and other information. The M labels mean millions of yen.
No.097: View the distribution of numbers with a histogram
Use in practice
A histogram is a graph used to understand the distribution (dispersion and bias) of numerical data. Utilization in manufacturing industry:
- Distribution of transaction amount → “Are there many small transactions or mainly large transactions?”
- Product unit price distribution → “Where is the price range concentration zone?”
- Distribution of defective numbers → “Where is the boundary between normal and abnormal times?”
Finding outliers in a histogram is It can also be applied to detect fraudulent transactions and provide early warning of production abnormalities.
Approach
Criteria for selecting the number of bins (number of intervals) for the histogram:
| Method | Formula | Features |
|---|---|---|
| Sturges formula | For simple/small data | |
| Scott’s formula | Considering data variation | |
| Freedman–Diaconis | Robust to outliers |
In practice, matplotlib automatically selects bins="auto", or
Adjust manually using as a guide.
Here is the number of bins, is bin width, and is the number of observations. IQR is the third quartile minus the first quartile. Convert a suggested width to a bin count using the data range divided by .
Check with Python
sales_arr = df["sales_amount"].to_numpy()
unit_pr_arr = df["unit_price"].to_numpy()
n = len(sales_arr)
# Recommended number of bins according to Sturges formula
sturges_bins = int(np.ceil(1 + np.log2(n)))
print(f"Number of data items n = {n}")
print(f"Recommended by Sturges formula bin number: k = ceil(1 + log2({n})) = {sturges_bins}")
print()
fig, axes = plt.subplots(1, 2, figsize=(13, 5))
# ── Left: Distribution of transaction unit sales amount ──
ax1 = axes[0]
ax1.hist(sales_arr, bins=sturges_bins, color="#4878CF", edgecolor="white",
alpha=0.85, linewidth=0.5)
ax1.axvline(np.mean(sales_arr), color="#D65F5F", linestyle="--", linewidth=1.5,
label=f"average: {np.mean(sales_arr):,.0f} JPY")
ax1.axvline(np.median(sales_arr), color="#6ACC65", linestyle="-.", linewidth=1.5,
label=f"median: {np.median(sales_arr):,.0f} JPY")
ax1.set_title("Distribution of transaction unit sales amount", fontsize=12, pad=12)
ax1.set_xlabel("Sales amount (yen)", fontsize=10)
ax1.set_ylabel("Number of cases", fontsize=10)
ax1.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e6:.1f}M"))
ax1.grid(axis="y", alpha=0.3)
ax1.legend(fontsize=9)
# ── Right: Product unit price distribution ──
ax2 = axes[1]
ax2.hist(unit_pr_arr, bins=sturges_bins, color="#6ACC65", edgecolor="white",
alpha=0.85, linewidth=0.5)
ax2.axvline(np.mean(unit_pr_arr), color="#D65F5F", linestyle="--", linewidth=1.5,
label=f"average: {np.mean(unit_pr_arr):,.0f} JPY")
ax2.axvline(np.median(unit_pr_arr), color="#4878CF", linestyle="-.", linewidth=1.5,
label=f"median: {np.median(unit_pr_arr):,.0f} JPY")
ax2.set_title("Product unit price distribution", fontsize=12, pad=12)
ax2.set_xlabel("Unit price (yen)", fontsize=10)
ax2.set_ylabel("Number of cases", fontsize=10)
ax2.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e3:.0f}K"))
ax2.grid(axis="y", alpha=0.3)
ax2.legend(fontsize=9)
plt.tight_layout()
plt.savefig("no097_histogram.svg", format="svg", bbox_inches="tight")
plt.show()
print("Saved: no097_histogram.svg")
print()
# Distribution summary statistics
print("Sales amount distribution statistics:")
for label, val in [
("average", np.mean(sales_arr)),
("median", np.median(sales_arr)),
("standard deviation", np.std(sales_arr)),
("minimum value", np.min(sales_arr)),
("maximum value", np.max(sales_arr)),
]:
print(f" {label:8s}: {val:>12,.0f} JPY")
Number of data items n = 301
Recommended by Sturges formula bin number: k = ceil(1 + log2(301)) = 10
Saved: no097_histogram.svg
Sales amount distribution statistics:
average : 795,199 JPY
median : 747,180 JPY
standard deviation: 298,746 JPY
minimum value: 205,403 JPY
maximum value: 1,957,462 JPY
Interpreting the results
Inspect the range where values concentrate, tail lengths, and the number of peaks. A mean above the median can suggest a longer right tail, but does not prove the distribution’s shape. Check whether the pattern remains when changing the number of bins. Sturges’ rule is a starting point, not a guarantee of an optimal histogram.
No.098: View the relationship between two variables with a scatter plot
Use in practice
A scatter diagram is a graph that allows you to visually understand the relationship between two variables (correlation, clusters, outliers). Utilization in manufacturing industry:
- Unit price vs. sales volume → Examine the association between price and quantity
- Number of production vs. number of defectives → Confirmation of consistency of defect rate
- Operation time vs. production volume → Evaluation of line production efficiency
By color-coding by product category, Differences in trends by segment can be expressed in a single graph.
Approach
Look for upward or downward trends, curved relationships, outliers, and groups by category. A weak linear pattern does not mean the variables are unrelated. This dataset assigns different price and quantity patterns to categories, so examine both the overall pattern and patterns within categories.
Check with Python
# Create a scatter plot by category
cat_colors = dict(zip(CAT_NAMES, ["#4878CF", "#6ACC65", "#D65F5F", "#B47CC7", "#C4AD66"]))
fig, axes = plt.subplots(1, 2, figsize=(13, 6))
# ── Left: Unit price vs. sales quantity (by product category) ──
ax1 = axes[0]
for cat in CAT_NAMES:
sub = df.filter(pl.col("product_category") == cat)
ax1.scatter(
sub["unit_price"].to_numpy(),
sub["quantity"].to_numpy(),
label=cat, color=cat_colors[cat],
alpha=0.55, s=35, edgecolors="none"
)
# Regression line (all data)
up_all = df["unit_price"].to_numpy()
qty_all = df["quantity"].to_numpy()
coef = np.polyfit(up_all, qty_all, 1)
x_line = np.linspace(up_all.min(), up_all.max(), 200)
ax1.plot(x_line, np.polyval(coef, x_line), color="black", linewidth=1.2,
linestyle="--", label=f"regression line (inclination={coef[0]:.4f})")
ax1.set_title("Unit price vs. sales quantity (by product category)", fontsize=12, pad=12)
ax1.set_xlabel("Unit price (yen)", fontsize=10)
ax1.set_ylabel("Sales quantity (pieces)", fontsize=10)
ax1.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e3:.0f}K"))
ax1.legend(fontsize=8, loc="upper right")
ax1.grid(alpha=0.25)
# ── Right: Sales amount vs. quantity ──
ax2 = axes[1]
for cat in CAT_NAMES:
sub = df.filter(pl.col("product_category") == cat)
ax2.scatter(
sub["sales_amount"].to_numpy(),
sub["quantity"].to_numpy(),
label=cat, color=cat_colors[cat],
alpha=0.55, s=35, edgecolors="none"
)
ax2.set_title("Sales amount vs. sales volume (by product category)", fontsize=12, pad=12)
ax2.set_xlabel("Sales amount (yen)", fontsize=10)
ax2.set_ylabel("Sales quantity (pieces)", fontsize=10)
ax2.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e6:.1f}M"))
ax2.legend(fontsize=8, loc="upper right")
ax2.grid(alpha=0.25)
plt.tight_layout()
plt.savefig("no098_scatter.svg", format="svg", bbox_inches="tight")
plt.show()
print(f"Save completed: no098_scatter.svg")
print(f"Slope of regression line (unit price→quantity): {coef[0]:.4f} units/JPY")
print(f" → unit price 1,000JPY When it goes up, the quantity {coef[0]*1000:.2f} units change")
Save completed: no098_scatter.svg
Slope of regression line (unit price→quantity): -0.0008 units/JPY
→ unit price 1,000JPY When it goes up, the quantity -0.76 units change
Interpreting the results
The generator tends to place current sensors toward lower prices and larger quantities, and vibration sensors toward higher prices and smaller quantities. A downward-sloping overall regression line does not show that cutting a price would increase quantity.
Price elasticity measures the percentage change in demand relative to a percentage change in price. It is different from the slope of a regression on raw price and quantity, or their correlation coefficient. Estimating a price change’s effect requires further analysis that accounts for products, customers, timing, and other conditions.
No.099: Check the correlation coefficient
Use in practice
The correlation coefficient represents the strength and direction of the linear relationship between two variables as a number from to . Utilization in manufacturing industry:
- Correlation between unit price and quantity → Description of linear association
- Correlation between sales amount and return flag → Return risk assessment for high sales transactions
- Correlation between monthly sales and seasonal dummy → Quantification of seasonality
Visualizing the correlation coefficient matrix with a heat map, You can list the relationships between multiple variables (an expression equivalent to seaborn’s heatmap is implemented in matplotlib).
Approach
Pearson product moment correlation coefficient:
Interpretation criteria for (general guide):
| Range of | Strength of relationship |
|---|---|
| Strong correlation | |
| Moderate correlation | |
| Weak correlation | |
| Almost uncorrelated |
Note: Correlation is sensitive to outliers and measures linear association. It may miss curved relationships. It is undefined when either variable is constant. Always inspect a scatter plot as well.### Check with Python
# Correlation coefficient matrix for numeric sequences
num_cols = ["quantity", "unit_price", "sales_amount", "is_returned"]
col_labels = ["quantity", "unit price", "Sales amount", "Return"]
data_mat = np.column_stack([df[c].to_numpy() for c in num_cols])
corr_mat = np.corrcoef(data_mat, rowvar=False)
print("Correlation coefficient matrix:")
header = f"{'':>8s}" + "".join(f"{lb:>8s}" for lb in col_labels)
print(header)
for i, lbl in enumerate(col_labels):
row = f"{lbl:>8s}" + "".join(f"{corr_mat[i,j]:>8.3f}" for j in range(len(col_labels)))
print(row)
print()
# ── Correlation coefficient heat map (matplotlib implementation) ──
fig, ax = plt.subplots(figsize=(7, 6))
n_vars = len(col_labels)
im = ax.imshow(corr_mat, cmap="RdBu_r", vmin=-1, vmax=1, aspect="auto")
plt.colorbar(im, ax=ax, shrink=0.8, label="correlation coefficient")
# Display numbers in cells
for i in range(n_vars):
for j in range(n_vars):
color = "white" if abs(corr_mat[i, j]) > 0.6 else "black"
ax.text(j, i, f"{corr_mat[i, j]:.3f}",
ha="center", va="center", fontsize=11, color=color, fontweight="bold")
ax.set_xticks(range(n_vars))
ax.set_yticks(range(n_vars))
ax.set_xticklabels(col_labels, fontsize=11)
ax.set_yticklabels(col_labels, fontsize=11)
ax.set_title("Sales KPI correlation coefficient heat map", fontsize=13, pad=12)
ax.grid(False)
plt.tight_layout()
plt.savefig("no099_correlation_heatmap.svg", format="svg", bbox_inches="tight")
plt.show()
print("Saved: no099_correlation_heatmap.svg")
print()
# Noteworthy correlated pairs
pairs = [(i, j) for i in range(n_vars) for j in range(i+1, n_vars)]
print("Correlation coefficients of notable pairs (in descending order of strength):")
sorted_pairs = sorted(pairs, key=lambda p: abs(corr_mat[p[0], p[1]]), reverse=True)
for (i, j) in sorted_pairs:
r = corr_mat[i, j]
strength = "Strong" if abs(r) >= 0.7 else "Medium" if abs(r) >= 0.4 else "Weak"
print(f" {col_labels[i]:>5s} × {col_labels[j]:>5s}: r = {r:+.3f} [{strength}]")
Correlation coefficient matrix:
quantityunit priceSales amount Return
quantity 1.000 -0.735 -0.011 -0.002
unit price -0.735 1.000 0.485 -0.030
Sales amount -0.011 0.485 1.000 -0.061
Return -0.002 -0.030 -0.061 1.000
Saved: no099_correlation_heatmap.svg
Correlation coefficients of notable pairs (in descending order of strength):
quantity × unit price: r = -0.735 [Strong]
unit price × Sales amount: r = +0.485 [Medium]
Sales amount × Return: r = -0.061 [Weak]
unit price × Return: r = -0.030 [Weak]
quantity × Sales amount: r = -0.011 [Weak]
quantity × Return: r = -0.002 [Weak]
Interpreting the results
A negative price–quantity correlation describes a tendency for higher-priced transactions to have smaller quantities in these data. A positive price–sales correlation is also an association; sales were calculated as price times quantity, so it does not establish the effect of raising prices.
Weak correlations with the return flag do not rule out relationships with price or quantity. Check nonlinear patterns and differences across products and customers. Use the heatmap with scatter plots to identify questions for further investigation.
No.100: Load sales data and create an analysis report
Use in practice
No.100 is the final exercise of the series. What you have learned so far: CSV loading → type conversion → aggregation → visualization → correlation analysis Consolidate into one script and create reproducible annual analysis reports.
“Analysis reproducibility” is extremely important in DX in the manufacturing industry. Even if the person in charge changes, the analysis can be performed using the same procedure the next year. Python notebook = living document is the goal.
Approach
Components of one analysis pipeline:
① Read data: pl.read_csv()
② Preprocessing: Type conversion, column addition, missing check
③ Aggregation: group_by() × multiple axes
④ Visualization: 2×2 dashboard
⑤ Text report: KPI summary with print()
This structure is the minimum unit of “ETL (Extract→Transform→Load) + analysis report”, It is the foundation for practical BI dashboards and automated reporting systems.
Check with Python
# ════════════════════════════════════════════════════════════
# No.100 Mini analysis report: Industrial sensors 2024 annual sales analysis
# ════════════════════════════════════════════════════════════
# ── Step 1: Data loading & preprocessing ──
df100 = pl.read_csv(CSV_PATH, try_parse_dates=False)
df100 = df100.with_columns(
pl.col("date").str.to_date("%Y-%m-%d")
).with_columns([
pl.col("date").dt.month().alias("month"),
pl.col("date").dt.to_string("%Y-%m").alias("year_month"),
])
n_rows, n_cols = df100.shape
total_sales = df100["sales_amount"].sum()
total_qty = df100["quantity"].sum()
return_rate = df100["is_returned"].mean() * 100
# ── Step 2: Aggregation ──
# monthly
monthly100 = (
df100.group_by("year_month")
.agg(pl.col("sales_amount").sum().alias("monthly_sales"))
.sort("year_month")
)
# By category
cat100 = (
df100.group_by("product_category")
.agg(pl.col("sales_amount").sum().alias("cat_sales"))
.sort("cat_sales", descending=True)
)
# By customer type
cust100 = (
df100.group_by("customer_type")
.agg(pl.col("sales_amount").sum().alias("cust_sales"))
.sort("cust_sales", descending=True)
)
# TOP3 products
top3_products = (
df100.group_by("product_name")
.agg(pl.col("sales_amount").sum().alias("prod_sales"))
.sort("prod_sales", descending=True)
.head(3)
)
# ── Step 3: 2×2 dashboard ──
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle("Industrial Sensors 2024 Annual Sales Dashboard", fontsize=15, fontweight="bold", y=1.01)
COLORS = ["#4878CF", "#6ACC65", "#D65F5F", "#B47CC7", "#C4AD66"]
# [0,0] Monthly sales trends
ax00 = axes[0, 0]
m_idx = list(range(12))
m_sales = monthly100["monthly_sales"].to_list()
m_labels = [m[5:] for m in monthly100["year_month"].to_list()]
ax00.plot(m_idx, m_sales, marker="o", linewidth=2, color="#4878CF", markersize=5)
ax00.fill_between(m_idx, m_sales, alpha=0.1, color="#4878CF")
ax00.set_title("① Monthly sales trends", fontsize=11, pad=8)
ax00.set_xlabel("Month", fontsize=9)
ax00.set_ylabel("Sales amount (yen)", fontsize=9)
ax00.set_xticks(m_idx)
ax00.set_xticklabels(m_labels, fontsize=8)
ax00.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e6:.0f}M"))
ax00.grid(axis="y", alpha=0.3)
# [0,1] Sales by product category Bar graph
ax01 = axes[0, 1]
c_cats = cat100["product_category"].to_list()
c_sales = cat100["cat_sales"].to_list()
ax01.bar(c_cats, c_sales, color=COLORS[:len(c_cats)], alpha=0.85, edgecolor="black", linewidth=0.4)
ax01.set_title("② Sales by product category", fontsize=11, pad=8)
ax01.set_xlabel("Product category", fontsize=9)
ax01.set_ylabel("Sales amount (yen)", fontsize=9)
ax01.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e6:.0f}M"))
ax01.grid(axis="y", alpha=0.3)
ax01.tick_params(axis="x", labelsize=8)
# [1,0] Scatter plot: unit price vs quantity
ax10 = axes[1, 0]
for cat, clr in zip(CAT_NAMES, COLORS):
sub = df100.filter(pl.col("product_category") == cat)
ax10.scatter(sub["unit_price"].to_numpy(), sub["quantity"].to_numpy(),
label=cat, color=clr, alpha=0.5, s=25, edgecolors="none")
ax10.set_title("③ Unit price vs sales quantity", fontsize=11, pad=8)
ax10.set_xlabel("Unit price (yen)", fontsize=9)
ax10.set_ylabel("Quantity (pieces)", fontsize=9)
ax10.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x/1e3:.0f}K"))
ax10.legend(fontsize=7, loc="upper right")
ax10.grid(alpha=0.2)
# [1,1] Correlation coefficient heat map (4 variables)
ax11 = axes[1, 1]
num_cols100 = ["quantity", "unit_price", "sales_amount", "is_returned"]
col_lbl100 = ["quantity", "unit price", "sales", "Return"]
mat100 = np.column_stack([df100[c].to_numpy() for c in num_cols100])
c100 = np.corrcoef(mat100, rowvar=False)
im100 = ax11.imshow(c100, cmap="RdBu_r", vmin=-1, vmax=1)
for i in range(4):
for j in range(4):
fc = "white" if abs(c100[i, j]) > 0.6 else "black"
ax11.text(j, i, f"{c100[i,j]:.2f}", ha="center", va="center",
fontsize=9, color=fc, fontweight="bold")
ax11.set_xticks(range(4)); ax11.set_xticklabels(col_lbl100, fontsize=9)
ax11.set_yticks(range(4)); ax11.set_yticklabels(col_lbl100, fontsize=9)
ax11.set_title("④ Correlation coefficient heat map", fontsize=11, pad=8)
plt.colorbar(im100, ax=ax11, shrink=0.7)
plt.tight_layout()
plt.savefig("no100_annual_dashboard.svg", format="svg", bbox_inches="tight")
plt.show()
print("Saved: no100_annual_dashboard.svg")
Saved: no100_annual_dashboard.svg
# ── Step 4: Text report output ──
divider = "=" * 54
print(divider)
print("Industrial Sensors 2024 Annual Sales Analysis Report")
print(divider)
print(f" Analysis period: January–December 2024")
print(f" Total number of transactions : {n_rows:>8,} records")
print(f" Total sales amount : {total_sales:>12,} JPY")
print(f" Total sales quantity : {total_qty:>8,} units")
print(f" Overall return rate : {return_rate:>8.2f} %")
print(divider)
print()
print("[Sales ranking by product category]")
for rank, (cat, sales) in enumerate(zip(
cat100["product_category"].to_list(),
cat100["cat_sales"].to_list()), 1):
pct = sales / total_sales * 100
print(f" {rank}rank {cat:10s}: {sales:>12,} JPY ({pct:.1f}%)")
print()
print("[Sales ranking by customer type]")
for rank, (cust, sales) in enumerate(zip(
cust100["customer_type"].to_list(),
cust100["cust_sales"].to_list()), 1):
pct = sales / total_sales * 100
print(f" {rank}rank {cust:8s}: {sales:>12,} JPY ({pct:.1f}%)")
print()
print("[TOP 3 product models]")
for rank, (prod, sales) in enumerate(zip(
top3_products["product_name"].to_list(),
top3_products["prod_sales"].to_list()), 1):
print(f" {rank}rank {prod:6s}: {sales:>12,} JPY")
print()
best_month = monthly100.sort("monthly_sales", descending=True).head(1)
worst_month = monthly100.sort("monthly_sales").head(1)
print(f"[Monthly sales highlights]")
print(f" maximum month: {best_month['year_month'][0]} {best_month['monthly_sales'][0]:>12,} JPY")
print(f" minimum month: {worst_month['year_month'][0]} {worst_month['monthly_sales'][0]:>12,} JPY")
print(f" maximum/minimum ratio: {best_month['monthly_sales'][0] / worst_month['monthly_sales'][0]:.2f} times")
print()
print(divider)
print("That's all")
print(divider)
======================================================
Industrial Sensors 2024 Annual Sales Analysis Report
======================================================
Analysis period: January–December 2024
Total number of transactions : 301 records
Total sales amount : 239,354,914 JPY
Total sales quantity : 11,048 units
Overall return rate : 3.32 %
======================================================
[Sales ranking by product category]
1rank flow sensor: 64,369,428 JPY (26.9%)
2rank temperature sensor: 60,772,674 JPY (25.4%)
3rank vibration sensor: 41,410,765 JPY (17.3%)
4rank pressure sensor: 41,210,887 JPY (17.2%)
5rank current sensor: 31,591,160 JPY (13.2%)
[Sales ranking by customer type]
1rank automobile: 84,512,570 JPY (35.3%)
2rank semiconductor: 53,920,928 JPY (22.5%)
3rank food : 48,413,908 JPY (20.2%)
4rank medical : 36,645,931 JPY (15.3%)
5rank General industry: 15,861,577 JPY (6.6%)
[TOP 3 product models]
1rank TS-A : 20,271,994 JPY
2rank FS-S : 19,761,553 JPY
3rank FS-A : 19,456,558 JPY
[Monthly sales highlights]
maximum month: 2024-09 25,273,346 JPY
minimum month: 2024-04 15,582,567 JPY
maximum/minimum ratio: 1.62 times
======================================================
That's all
======================================================
Interpreting the results
The report combines monthly sales, category sales, a price–quantity scatter plot, and correlations. The gap between the largest and smallest months shows variation within the year; confirming seasonality requires multiple years. If sales are concentrated in a few categories, investigate how changes in their demand could affect the total.
Scatter plots and correlations do not determine the effect of a price change or the cause of returns. Use the summaries as a starting point for reviewing order conditions and quality records.
This completes No.001–100, covering Python basics, CSV loading, aggregation with Polars, and plotting with Matplotlib.
Applying the exercises at work
Through the final chapters No.091-100, the following suggestions for manufacturing data analysis can be obtained.
1. Granular design of aggregation determines the quality of decision-making
The axis to be summarized in group_by depends on the question design itself. For the question “Which products are selling?”
“Which customers are the most valuable?” requires aggregation by customer. The starting point for data analysis is to clarify what you want to know.
2. Normalization of date type is a prerequisite for all time series analysis
After loading CSV, inspect the date column’s type with schema. Convert strings to Date or Datetime as needed, and check for values that cannot be parsed. When outputting year-month strings, use a consistent zero-padded format such as YYYY-MM.
3. Select visualization based on “who sees it”
- Line graph: Time series trend (monthly report for managers)
- Bar graph: Category comparison (ranking by product/customer)
- Histogram: Check distribution (quality control/anomaly detection)
- Scatter chart: Relationship between two variables (evaluation of pricing strategy/equipment efficiency)
4. Correlation is not causation
Even with (strong negative correlation), The conclusion that “lowering the price will always increase the quantity” is incorrect. Correlation analysis presents “candidate hypotheses to be investigated”, Confirming causal relationships requires knowledge of A/B tests, quasi-experiments, and business processes.
5. Analysis reproducibility is the foundation of DX
Record the input data, Python and library versions, and cell order as well as the random seed. Before sharing, restart the kernel and run the notebook from the top to check reproducibility. Keep this information with the notebook so others can repeat the work later.
Applying the code to your data
Checklist for fully utilizing Python data analysis at manufacturing sites
1. Environmental improvement
- Unified Python environment (venv or conda) on all personnel’s PCs
- Fix the versions of Polars, NumPy, and Matplotlib with
requirements.txt - Version control notebooks with Git (track change history)
2. Data pipeline design
- Confirm and standardize CSV export format from production management system
- Unify the representation of column names, data types, and missing values within the company (create a data dictionary)
- Prepare monthly/yearly execution scripts (eliminating copy-paste work)
3. Standardization of visualization and reporting
- Unified color palette and font for graphs for internal reports
- Document KPI definitions (sales amount, return rate, growth rate calculation formula)
- Create notebook template for dashboard
4. Deployment to the team
- Use this series (No.001-100) as an in-house Python training text
- Introducing Polars + matplotlib as a common language for analysts and engineers
- Add interpretation of analysis results and decision-making rules to business procedures manual
Summary
In this chapter (No.091-100), we will introduce aggregation, visualization, and correlation analysis using Polars + matplotlib. I learned from the annual sales performance data of an industrial sensor manufacturer.
| No. | What I learned | Application in the manufacturing industry |
|---|---|---|
| 091 | group_by aggregate | Annual sales aggregate by product category and customer type |
| 092 | Aggregation by product | Identification of main products and candidates for discontinuation by ABC analysis |
| 093 | Date type conversion | Prerequisites for monthly aggregation and time series analysis |
| 094 | Monthly summary | Monthly trends, month-on-month growth rate, quarterly summary |
| 095 | Line graph | Visualization of monthly sales and quantity trends |
| 096 | Bar graph | Comparison of sales by category and customer |
| 097 | Histogram | Distribution of transaction amount/unit price and outlier detection |
| 098 | Scatter plot | Visualizing the association between price and quantity |
| 099 | Correlation coefficient | Quantifying the strength of the relationship between KPIs with a correlation coefficient matrix |
| 100 | Mini analysis report | Bulk output pipeline of totals, graphs, and text |
Skills covered across the 100 exercises:
| Chapter | Scope | Theme |
|---|---|---|
| Chapter 1 | No.001~010 | Python preparation and basics |
| Chapter 2 | No.011-020 | Variables, types, and operations |
| Chapter 3 | No.021-030 | Character strings, lists, and dictionaries |
| Chapter 4 | No.031~040 | Conditional branching and repetition |
| Chapter 5 | No.041-050 | Functions/Modules/Exception Handling |
| Chapter 6 | No.051~060 | File operations and CSV |
| Chapter 7 | No.061~070 | Introduction to NumPy |
| Chapter 8 | No.071~080 | Introduction to Polars |
| Chapter 9 | No.081-090 | Data processing using Polars |
| Chapter 10 | No.091-100 | Aggregation/Visualization/Mini-analysis |
Training and analysis support
For information on promoting DX in the manufacturing industry, building data analysis infrastructure, and in-house Python training, please contact: Please feel free to contact the Surikobo.
📩 Contact: www.surikobo.co.jp/contact Please feel free to contact us first.
*This article is the final article of the “100 Python Exercises for Data Analysis” series. * *Please check the table of contents for the entire series from here. *