【问题标题】:Highlight the Axis OX and OY in matplotlib在 matplotlib 中突出显示 Axis OX 和 OY
【发布时间】:2025-12-17 03:25:02
【问题描述】:

我需要帮助来突出 matplotlib.pyplot 中的 Axis OX 和 OY。我用它来渲染函数图并且没有突出显示的 OX 和 OY 图看起来未完成。 这是我的代码:

import matplotlib.pyplot as plt
import numpy as np

def render_func_graph(formula, x_range):
    try:
        fig = plt.figure()    
        x = np.array(x_range)
        y = eval(formula)
        print(y)
        plt.plot(x, y, 'go-')
        plt.scatter(0,0)
        plt.grid(True)
        plt.show()
    except Exception as err:
        print(str(err))  

def main():
    func = input('f(x):')
    render_func_graph(func, range(-10, 10))

if __name__ == '__main__':
    main()

我正在为1/x 公式得到这个

我想得到类似this的东西

【问题讨论】:

  • 您能更好地描述您的预期结果吗?
  • 添加了预期结果的链接
  • 你能告诉我this example 没有帮助吗?除了图片之外,还要描述您想要什么以及阻止您到达那里的原因。由于 SO 不是代码编写服务,因此如果您展示您迄今为止所尝试的内容,获得答案的机会会更高。
  • 哦,你的例子正是我所需要的。我看错了方向。我尝试在 OX 和 OY 轴上渲染线条并在其上循环。非常感谢!

标签: python matplotlib graph


【解决方案1】:

看看here,看来你可以用


#matplotlib.pyplot.axes(*args, **kwargs) -> could just modify axis color

#matplotlib.pyplot.axhline(y=0, xmin=0, xmax=1, hold=None, **kwargs)
axhline(linewidth=4, color='r') #adds thick red line @ y=0

#matplotlib.pyplot.axvline(x=0, ymin=0, ymax=1, hold=None, **kwargs)
axvline(linewidth=4, color='r') #adds thick red line @ x=0

【讨论】:

  • 感谢您的回答。它解决了我的问题,就像@ImportanceOfBeingErnes 的例子一样。
【解决方案2】:

嗯,完成后的代码如下所示:

import matplotlib.pyplot as plt
import numpy as np

def render_func_graph(formula, x_range):
    try:
        fig = plt.figure()    
        x = np.array(x_range)
        y = eval(formula)
        plt.xticks(np.arange(min(x), max(x)+1, 1.0))
        ax = fig.add_subplot(111)
        plt.plot(x, y, 'go-')
        ax.spines['left'].set_position('zero')
        ax.spines['right'].set_color('none')
        ax.spines['bottom'].set_position('zero')
        ax.spines['top'].set_color('none')
        ax.spines['left'].set_smart_bounds(True)
        ax.spines['bottom'].set_smart_bounds(True)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        plt.scatter(0,0)
        plt.grid(True)
        plt.show()
    except Exception as err:
        print(str(err))  

def main():
    func = input('f(x):')
    render_func_graph(func, np.arange(-5, 5, 0.5))

if __name__ == '__main__':
    main()

1/x 的结果类似于this

【讨论】: