Numpy+matplotlib 每月总产量

matplotlib:利用Numpy随机生成某工厂每天的产量数据。汇总每月总产量,并使用bar 方法 来绘制柱形图。再使用hist 方法来绘制直方图,进行统计分析。

import numpy as np
import matplotlib.pyplot as plt

# ---------------------- 1. Generate data ----------------------
np.random.seed(42)  # Fixed random seed for reproducibility

# Days of each month
days_per_month = [31, 28, 31, 30, 31, 30,
                  31, 31, 30, 31, 30, 31]

# Daily production: normal distribution, mean=120, std=15
daily_production = []
for days in days_per_month:
    month_data = np.random.normal(loc=120, scale=15, size=days)
    # Production cannot be negative
    month_data = np.clip(month_data, a_min=0, a_max=None)
    daily_production.append(month_data)

# Total production per month
month_total = np.array([np.sum(arr) for arr in daily_production])
month_labels = [f"Month {i+1}" for i in range(12)]

# Combine all daily data for histogram
all_daily = np.concatenate(daily_production)

# ---------------------- 2. Plot figures ----------------------
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))

# Bar chart: monthly total production
ax1.bar(month_labels, month_total, color="#4472C4")
ax1.set_title("Factory Monthly Total Production")
ax1.set_xlabel("Month")
ax1.set_ylabel("Total Output")
ax1.tick_params(axis="x", rotation=45)

# Histogram: distribution of daily production
ax2.hist(all_daily, bins=20, color="#5B9BD5", edgecolor="black", alpha=0.7)
ax2.set_title("Histogram of Daily Production")
ax2.set_xlabel("Daily Output")
ax2.set_ylabel("Number of Days")

plt.tight_layout()
plt.show()

# Print summary information
print("Total production per month:")
for m, val in zip(month_labels, month_total):
    print(f"{m}: {val:.2f}")
print(f"\nAnnual total production: {np.sum(month_total):.2f}")
print(f"Mean daily output: {np.mean(all_daily):.2f}, Std: {np.std(all_daily):.2f}")

图片

 

 

下面逐块详细解释这份代码,包括 NumPy 随机生成产量、月度汇总、bar 柱状图、hist 直方图,每一行的作用、函数参数含义。

import numpy as np
import matplotlib.pyplot as plt
  • import numpy as np:导入数值计算库 numpy,用来生成随机数、求和、拼接数组;
  • import matplotlib.pyplot as plt:导入绘图库,用来画柱状图和直方图。
np.random.seed(42)
  • np.random.seed(42):设置随机种子;
  • 如果不设置,每次运行程序,随机生成的产量都不一样;固定种子后,每次运行得到一模一样的数据,方便调试、交作业、复现结果;
  • 42 只是一个随便选的整数,可以换成别的数字。
days_per_month = [31, 28, 31, 30, 31, 30,
                 31, 31, 30, 31, 30, 31]
  • 列表保存一年 12 个月每个月的天数(平年,二月 28 天);后面循环时,按照每个月天数生成对应数量的 “每日产量”。
daily_production = []
for days in days_per_month:
    month_data = np.random.normal(loc=120, scale=15, size=days)
    month_data = np.clip(month_data, a_min=0, a_max=None)
    daily_production.append(month_data)
  • daily_production = []:空列表,用来存放每个月的日产量数组;
  • np.random.normal():生成服从正态分布(高斯分布)的随机数
    • loc=120:均值,代表平均每日产量是 120;
    • scale=15:标准差,代表产量围绕 120 上下波动,波动幅度约 15;
    • size=days:生成多少个数字,等于当月天数;
  • np.clip(...):截断函数
    • a_min=0:所有小于 0 的数字强制改成 0;
    • a_max=None:上限不做限制;
    • 业务含义:产量不可能是负数,防止随机生成负数;
  • append(month_data):把当月的一组日产量数组放进列表;
  • 循环结束后,daily_production 里面有 12 个数组,分别对应 1–12 月每天产量。
month_total = np.array([np.sum(arr) for arr in daily_production])
month_labels = [f"Month {i+1}" for i in range(12)]
  • 列表推导式 [np.sum(arr) for arr in daily_production]
    • np.sum(arr):对一个月里面所有日产量求和,得到这个月总产量;
    • 遍历 12 个月,得到 12 个月度总产量;
  • np.array(...):把求和结果转为 numpy 数组,方便后续运算;
  • month_labels:生成标签字符串:"Month 1", "Month 2" … "Month 12",作为柱状图横轴文字。
all_daily = np.concatenate(daily_production)
  • np.concatenate():拼接数组;
  • 把 12 个独立的、分属各个月份的日产量数组,拼成一个长长的一维数组;
  • 这个数组包含全年每一天的产量,专门供给直方图 hist 使用,用来统计全部日产量的分布。
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
  • plt.subplots(1, 2):创建一张画布,一行、两列,也就是并排两张子图;
  • 返回:
    • fig:整个画布对象;
    • ax1:左边子图(放柱状图);
    • ax2:右边子图(放直方图);
  • figsize=(14,5):画布尺寸,宽 14,高 5(单位:英寸)。
ax1.bar(month_labels, month_total, color="#4472C4")
ax1.set_title("Factory Monthly Total Production")
ax1.set_xlabel("Month")
ax1.set_ylabel("Total Output")
ax1.tick_params(axis="x", rotation=45)
  • ax1.bar():绘制柱状图
    • 第一个参数:横轴标签(月份);
    • 第二个参数:柱子高度(每月总产量);
    • color="#4472C4":柱子颜色(十六进制颜色码);
  • set_title:子图标题;
  • set_xlabel / set_ylabel:设置横轴、纵轴名称;
  • tick_params(axis="x", rotation=45):把横轴文字旋转 45°,防止文字挤在一起重叠。
ax2.hist(all_daily, bins=20, color="#5B9BD5", edgecolor="black", alpha=0.7)
ax2.set_title("Histogram of Daily Production")
ax2.set_xlabel("Daily Output")
ax2.set_ylabel("Number of Days")
  • ax2.hist():绘制直方图
    • all_daily:输入数据,全年所有日产量;
    • bins=20:把产量范围切分成 20 个区间(箱子);程序统计落在每个区间里面一共有多少天;
    • color:柱子填充颜色;
    • edgecolor="black":给每个直方加上黑色边框,看起来更清晰;
    • alpha=0.7:透明度,取值 0~1;0 完全透明,1 不透明;
  • 横轴:日产量大小;纵轴:有多少天的产量落在这个区间;直方图用来观察:大多数日子产量集中在哪个附近、产量分散程度。
plt.tight_layout()
plt.show()
  • plt.tight_layout():自动调整子图间距,防止标题、坐标轴文字互相遮挡;
  • plt.show():弹出绘图窗口,展示整张图。
print("Total production per month:")
for m, val in zip(month_labels, month_total):
    print(f"{m}: {val:.2f}")

print(f"\nAnnual total production: {np.sum(month_total):.2f}")
print(f"Mean daily output: {np.mean(all_daily):.2f}, Std: {np.std(all_daily):.2f}")
  • zip:同时遍历月份标签和对应月度总产量;
  • :.2f:保留两位小数输出;
  • np.sum(month_total):全年总产量;
  • np.mean(all_daily):全年日产量平均值;
  • np.std(all_daily):日产量标准差,反映产量波动大小;
  • 这部分只是控制台文本输出,不画图。

整体逻辑一句话

先用正态随机数模拟每天产量,按月求和得到每月总产量,用 bar 画月度产量对比;再把全部日产量合并,用 hist 画出日产量的频数分布,做统计分析。

区分两个图(很容易混淆)

  • bar 柱状图:类别对比;这里类别是 12 个月份,每个柱子代表一个月的总产量;
  • hist 直方图:连续数值分布;它不是预先给定类别,而是自动对产量数值分区,统计频次。

 

posted @ 2026-11-05 14:52  emanlee  阅读(18)  评论(0)    收藏  举报