轴上的条件语句(子图)and/or on [=11th=] (plt)
Conditionnal statement on axis (subplot) and/or on matplotlib.pyplot (plt)
我有一个函数可以将轴作为参数 (class 'matplotlib.axes._subplots.AxesSubplot')。但是,如果没有传递轴,默认情况下它将采用 "plt" 对象 (matplotlib.pyplot)。由于一些适用于axes的方法不适用于plt,我想使用条件语句。
注意:如果不可能,我将使用 try/except 语句。
def plot1(ax=plt):
# Ax is a subplot object created before the call to the function
ax.plot(t1, f(t1))
if isinstance(ax, module): # <--- this is pseudo-code
# properties specific to plt object
ax.title('title')
ax.xlabel('xlabel')
ax.ylabel('ylabel')
else:
# properties specific to axes object
ax.set_title('title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
我强烈建议不要使用这些不同的输入类型。万一以后功能稍微复杂一点,就会出现各种问题。相反,我会让它只接受一个轴作为输入,或 None
。在后一种情况下,您可以回退到当前轴。
def plot1(ax=None):
ax = ax or plt.gca()
ax.plot(t1, f(t1))
ax.set_title('title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
这当然需要事先将 pyplot 导入为 plt
。如果该功能是要在无法保证这一点的环境中使用,您仍然可以即时进行,
def plot1(ax=None):
if ax is None:
import matplotlib.pyplot as plt
ax = plt.gca()
ax.plot(t1, f(t1))
ax.set_title('title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
我有一个函数可以将轴作为参数 (class 'matplotlib.axes._subplots.AxesSubplot')。但是,如果没有传递轴,默认情况下它将采用 "plt" 对象 (matplotlib.pyplot)。由于一些适用于axes的方法不适用于plt,我想使用条件语句。
注意:如果不可能,我将使用 try/except 语句。
def plot1(ax=plt):
# Ax is a subplot object created before the call to the function
ax.plot(t1, f(t1))
if isinstance(ax, module): # <--- this is pseudo-code
# properties specific to plt object
ax.title('title')
ax.xlabel('xlabel')
ax.ylabel('ylabel')
else:
# properties specific to axes object
ax.set_title('title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
我强烈建议不要使用这些不同的输入类型。万一以后功能稍微复杂一点,就会出现各种问题。相反,我会让它只接受一个轴作为输入,或 None
。在后一种情况下,您可以回退到当前轴。
def plot1(ax=None):
ax = ax or plt.gca()
ax.plot(t1, f(t1))
ax.set_title('title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
这当然需要事先将 pyplot 导入为 plt
。如果该功能是要在无法保证这一点的环境中使用,您仍然可以即时进行,
def plot1(ax=None):
if ax is None:
import matplotlib.pyplot as plt
ax = plt.gca()
ax.plot(t1, f(t1))
ax.set_title('title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')