解决 MatplotlibDeprecationWarning 和 NameError: name 'fm' is not defined 错误
解决 MatplotlibDeprecationWarning 和 NameError: name 'fm' is not defined 错误
在使用 Matplotlib 库创建绘图时,您可能会遇到 'MatplotlibDeprecationWarning' 和 'NameError: name 'fm' is not defined' 错误。这些错误通常是由于缺少必要的导入语句造成的。
错误原因
'MatplotlibDeprecationWarning' 错误是由于使用了在 Matplotlib 3.6 版本中弃用的 'FigureCanvases' 功能而引起的。'NameError: name 'fm' is not defined' 错误是因为您在使用 'fm' 别名之前没有导入 'matplotlib.font_manager' 模块。
解决方法
要解决这些错误,您需要在代码中添加以下导入语句:pythonimport matplotlib.pyplot as pltimport matplotlib.font_manager as fm
第一行代码导入了 'matplotlib.pyplot' 模块,并将其命名为 'plt'。第二行代码导入了 'matplotlib.font_manager' 模块,并将其命名为 'fm'。
代码示例
以下是一个包含导入语句的完整代码示例:pythonimport matplotlib.pyplot as pltimport matplotlib.font_manager as fm
创建画布fig, ax = plt.subplots(figsize=(8, 10))
设置背景色ax.set_facecolor('#F7F7F7')
绘制书籍封面cover_width = 6cover_height = 8cover_colors = ['#FF6666', '#FFFF66', '#66CCFF'] # 红、黄、蓝for i in range(3): ax.add_patch(plt.Rectangle((0, i * (cover_height / 3)), cover_width, cover_height / 3, color=cover_colors[i]))
添加文字title_text = 'ChatGPT与行业应用'editor_text = '主编:郭春来等'plan_text = '十四五规划教材'college_text = '哈尔滨剑桥学院'
font_prop_title = fm.FontProperties(fname='C:/Windows/Fonts/msyh.ttc', size=40) # 使用微软雅黑字体font_prop_others = fm.FontProperties(fname='C:/Windows/Fonts/msyh.ttc', size=24) # 使用微软雅黑字体ax.text(0.5, 6, title_text, fontsize=40, weight='bold', color='black', fontproperties=font_prop_title)ax.text(0.5, 4.5, editor_text, fontsize=24, color='black', fontproperties=font_prop_others)ax.text(0.5, 2.5, plan_text, fontsize=24, color='black', fontproperties=font_prop_others)ax.text(0.5, 1, college_text, fontsize=24, color='black', fontproperties=font_prop_others)
绘制人脑图标brain_icon_path = 'path/to/your/brain_icon.png' # 替换为您的人脑图标路径brain_icon = plt.imread(brain_icon_path)ax.imshow(brain_icon, extent=[2, 4, 2, 4], aspect='auto', zorder=10) # 调整位置和大小,并设置zorder确保位于前面
设置坐标轴ax.axis([0, cover_width, 0, cover_height])ax.axis('off')
展示封面plt.show()
请确保将 'path/to/your/brain_icon.png' 替换为指向实际图像文件的正确路径。
通过添加这些导入语句,您应该能够解决 'MatplotlibDeprecationWarning' 和 'NameError: name 'fm' is not defined' 错误,并成功运行您的代码。
原文地址: http://www.cveoy.top/t/topic/w8k 著作权归作者所有。请勿转载和采集!