【问题标题】:How to show cartesian axes in matplotlib? [duplicate]如何在 matplotlib 中显示笛卡尔坐标轴? [复制]
【发布时间】:2021-01-11 16:51:00
【问题描述】:

所以我正在开发一个程序,该程序在一个区间内显示函数的图形,并且绘图大小由 matplotlib 自动处理。唯一的事情是,它调整大小而不显示 x=0 和 y=0 笛卡尔轴。到目前为止,我尝试的所有操作,例如 plt.subplot(),只影响显示在底部和左侧的轴,而不影响笛卡尔轴。有没有办法添加轴?

下面是一些示例代码:

import matplotlib.pyplot as plt
import numpy as np


x = np.linspace(-2, 1, 100)
f = lambda x: x**2 - 1
plt.plot(x, f(x))
plt.show()

由此得出的图表如下所示:

不显示笛卡尔坐标轴。有没有办法添加它,也许通过在 x=0 和 y=0 处添加行?

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    您可以将脊椎轴设置为自定义位置,例如原点:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(-2,1,100)
    y = x**2
    
    fig, ax = plt.subplots(1, figsize=(6, 4))
    ax.plot(x, y)
    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.set(ylim=(-1, 4))
    

    否则,您可以添加垂直和水平线:

    fig, ax = plt.subplots(1, figsize=(6, 4))
    ax.plot(x, y)
    ax.axhline(0, color='black')
    ax.axvline(0, color='black')
    

    【讨论】:

      【解决方案2】:

      你可以通过画箭头来做到这一点:

      import matplotlib.pyplot as plt
      import numpy as np
      from pylab import *
      
      
      x = np.linspace(-2, 1, 100)
      f = lambda x: x**2 - 1
      
      
      fig = plt.figure()
      ax = fig.add_subplot(111)
      ax.set_aspect('equal')
      plt.plot(x, f(x))
      
      l,r = ax.get_xlim()
      lo,hi = ax.get_ylim()
      arrow( l-1, 0, r-l+2, 0, length_includes_head = False, head_width = 0.2 )
      arrow( 0, lo-1, 0, hi-lo+2, length_includes_head = True, head_width = 0.2 )
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-05
        • 2019-12-29
        • 1970-01-01
        • 1970-01-01
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多