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

如何修复Matplotlib绘制函数及导数共享X轴子图的报错代码

代码修复方案

存在的问题及修复点

  • 缺少numpy、matplotlib.pyplot的导入语句
  • 直接使用Python内置关键字min、max作为np.arange的参数,需要替换为自定义的实际x轴范围变量
  • top.set_title()的字符串参数没有加引号,会报语法错误
  • 子图(Axes对象)设置坐标轴标签需要使用set_xlabel()/set_ylabel()方法,直接调用xlabel()/ylabel()是pyplot级别的用法,不适用于子图对象
  • 混淆了x轴刻度设置方法:set_xticks()用于指定刻度位置,设置刻度颜色、字体大小、旋转角度需要调用tick_params()方法
  • plt.show()不需要传入figure参数,直接调用即可

修复后可运行的完整示例

下面以f(x)=x²、导函数df(x)=2x、x轴范围为-10到10为例,给出可运行代码,你可以自行替换自定义的f(x)和df(x)、修改x轴范围:

import numpy as np
import matplotlib.pyplot as plt

# 自定义原函数和导函数,可根据需求替换
def f(x):
    return x ** 2

def df(x):
    return 2 * x

# 自定义x轴范围,不要用min、max作为变量名
x_min = -10
x_max = 10
x = np.arange(x_min, x_max, 0.5)

figure, (top, bottom) = plt.subplots(2, sharex=True, figsize = [5.0, 7.0])
# 绘制上方原函数图像
top.plot(x, f(x), 'b', linewidth = 5)
top.set_title('Function f(x)')
top.set_ylabel('f(x)')
# 绘制下方导函数图像
bottom.plot(x, df(x), 'g-', linewidth = 8) 
bottom.set_title('Derivative function of f(x)')
bottom.set_xlabel('x')
bottom.set_ylabel('df(x)')
# 设置x轴刻度样式
bottom.tick_params(axis='x', colors = 'r', labelsize = 12, rotation = 30)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:24:04