You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码报错ModuleNotFoundError:找不到basic_units模块求解决

解决ModuleNotFoundError: No module named 'basic_units'问题

问题原因

basic_units是Matplotlib官方示例专用的自定义单位处理模块,不属于Python标准库或Matplotlib默认安装内容,直接导入会触发模块找不到的错误。

修复方案

将basic_units模块的核心实现直接嵌入代码中,或在同目录下创建basic_units.py文件写入对应代码,即可正常运行:

# 嵌入basic_units模块的核心实现
class BasicUnit:
    def __init__(self, value, unit=''):
        self.value = value
        self.unit = unit

    def __mul__(self, other):
        if isinstance(other, (int, float, np.ndarray)):
            return BasicUnit(other * self.value, self.unit)
        return NotImplemented

    def __rmul__(self, other):
        return self.__mul__(other)

    def __add__(self, other):
        if isinstance(other, BasicUnit) and self.unit == other.unit:
            return BasicUnit(self.value + other.value, self.unit)
        return NotImplemented

    def __sub__(self, other):
        if isinstance(other, BasicUnit) and self.unit == other.unit:
            return BasicUnit(self.value - other.value, self.unit)
        return NotImplemented

    def __truediv__(self, other):
        if isinstance(other, BasicUnit):
            return BasicUnit(self.value / other.value, f"{self.unit}/{other.unit}")
        elif isinstance(other, (int, float)):
            return BasicUnit(self.value / other, self.unit)
        return NotImplemented

    def __rtruediv__(self, other):
        if isinstance(other, (int, float)):
            return BasicUnit(other / self.value, f"1/{self.unit}")
        return NotImplemented

    def __repr__(self):
        return f"{self.value} {self.unit}"

    def __array__(self, dtype=None):
        return np.asarray(self.value, dtype=dtype)

# 定义常用单位
cm = BasicUnit(1, 'cm')
inch = BasicUnit(2.54, 'cm')  # 1英寸=2.54厘米

# 原代码部分
import matplotlib.pyplot as plt
import numpy as np

cms = cm * np.arange(0, 10, 2)

fig, axs = plt.subplots(2, 2)

axs[0, 0].plot(cms, cms)
axs[0, 0].set_title('无单位指定')

axs[0, 1].plot(cms, cms, xunits=cm, yunits=inch)
axs[0, 1].set_title('X轴: cm, Y轴: inch')

axs[1, 0].plot(cms, cms, xunits=inch, yunits=cm)
axs[1, 0].set_xlim(3, 6)  # 数值按当前X轴单位(inch)解析
axs[1, 0].set_title('X轴: inch, Y轴: cm')

axs[1, 1].plot(cms, cms, xunits=inch, yunits=inch)
axs[1, 1].set_xlim(3*cm, 6*cm)  # cm单位会自动转换为inch
axs[1, 1].set_title('X轴/Y轴: inch')

plt.tight_layout()
plt.show()

说明

  • 上述代码先实现了BasicUnit类,用于处理带单位的数值运算,同时定义了cm和inch两个单位实例(inch基于厘米的换算关系定义)。
  • 原绘图逻辑保持不变,添加了标题和tight_layout()优化子图布局。
  • 也可选择将BasicUnit类和单位定义单独保存为basic_units.py文件,放在当前代码同目录下,这样原导入语句from basic_units import cm, inch就能正常使用。

内容的提问来源于stack exchange,提问作者user16239103

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:26:28