如何用曲线轴替换Matplotlib轴

时间:2019-07-15 06:13:40

标签: python matplotlib plot axis figure

文档here中有一个很好的曲线轴网格示例。假设您有一个空的图形,然后使用以下方法创建曲线轴:

ax1 = Subplot(fig, 1, 2, 1, grid_helper=grid_helper)

但是,我正在编写一个具有现有轴的函数,并且希望该函数用新的曲线轴替换该轴(ax)。

到目前为止,这是我功能的开始:

import matplotlib.pyplot as plt
from mpl_toolkits.axisartist import SubplotHost
from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear
import mpl_toolkits.axisartist.angle_helper as angle_helper
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D

def sgrid(ax=None):
    """
    Adds an s-plane grid of constant damping factors and natural
    frequencies to a plot.  If ax is not specified, the current
    figure axis is used.

    Parameters
    ----------
    ax : matplotlib axis object
        If not passed, uses gca() to get current axis.

    Returns
    -------
    ax : matplotlib axis
    """

    grid_helper = GridHelperCurveLinear(
        ... some stuff ...
    )

    if ax is None:
        # Get the current axis or create a new figure with one
        ax = plt.gca()
    fig = ax.figure

    # TODO: How can we change the axis if it is already created?
    ax = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    ... (code that adds more stuff to ax) ...

    return ax

此外,我不确定我是否了解SubplotHost的参数。这些是新Axis的初始化参数还是什么?

UPDATE

这里的目标是模拟Pandas.Series.plot函数的工作方式。所需的用例是这样的:

H = tf([2, 5, 1],[1, 2, 3])
rlocus(H)
sgrid()
plt.show()

>>> fig, axes = plt.subplots(2, 1)
>>> rlocus(H1, ax=axes[1])
>>> rlocus(H2, ax=axes[2])
>>> for ax in axes:
>>>     sgrid(ax=ax)  # Later we might want to add ax.zgrid()
>>> plt.show()

sgridrlocus的顺序在理想情况下应与上面相同,因为这与我们正在仿真的MATLAB函数以及与之相似的plt.grid()方法相似。 >

1 个答案:

答案 0 :(得分:1)

grid_helpermpl_toolkits.axisartist.axislines.Axes的关键字。 https://matplotlib.org/api/_as_gen/mpl_toolkits.axisartist.axislines.html

您可能要检查提供的轴是否是此Axes扩展的子类,否则请重新创建轴:

from mpl_toolkits.axisartist import SubplotHost,axislines

...

def sgrid(ax1=None):
    ...
    if ax1 is None:
        ax1=plt.gca()
    fig=ax1.figure
    if not isinstance(ax1,axislines.Axes):
        subargs=ax1.get_geometry()
        fig.delaxes(ax1)
        ax2 = SubplotHost(fig, *subargs, grid_helper=grid_helper)
        fig.add_subplot(ax2)
    else:
       ax2=ax1
    ...

    return ax2

请注意,sgrid()的调用者仍然引用ax1,它不再是图中的一部分。可能需要比仅删除和重新创建更复杂的轴引用替换。