在matplotlib中突出显示Axis OX和OY

时间:2017-08-10 16:49:30

标签: python matplotlib graph

我需要帮助来突出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公式

Result

我希望获得类似this

的内容

2 个答案:

答案 0 :(得分:0)

看看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

答案 1 :(得分:0)

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

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

相似