传递字符串作为绘图的参数

时间:2016-02-08 12:40:50

标签: python python-3.x matplotlib

我希望这个函数取一个字符串,指示它应该绘制哪些数据(x,y或z)作为参数。

def plotfit(axis):

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.scatter(xdata, ydata, func_z(vars,fitted_z),c='r')
    ax.set_title('B_z of %s' % name)
    ax.scatter(xdata, ydata, zfield, c='b')

如何使下面代码的粗体部分替换为我的字符串参数,以便例如plotfit(x)会用“x”替换下面粗体z的所有实例并相应地绘制? 兴趣点:

  • func_的ž
  • fitted_的ž
  • ž字段
  • 's z %s'

我想象的是:

ax.scatter(xdata, ydata, func(axis as a string)(vars,fitted_(axis as a string)),c='r')

2 个答案:

答案 0 :(得分:1)

您可以使用在代码中充当switch语句的字典,如下所述。

def plotfit(a_letter):
    assert a_letter in ["x", "y", "z"]
    fitted = {"x" : fitted_x, "y" : fitted_y, "z" : fitted_z}
    fields = {"x" : field_x, "y" : field_y, "z" : field_z}
    afunc = {"x" : afunc_x, "y" : afunc_y, "z" : afunc_z}
    # ...
    ax.scatter(xdata, ydata, afunc[a_letter](vars,fitted[a_letter]),c='r')
    #...
    ax.set_title('B_%s of %s' %(a_letter, name))

但是,您也可以考虑其他选择:

  • 使用plotfit将函数fit,func,field作为参数
  • 让plotfit将对象作为具有拟合,函数和字段方法的参数
  • 在基类中定义plotfit并使用self.func,self.fit和self.field。这些方法将在不同的子类中实现

请注意,对于这种情况使用exec语句被视为不良做法,如Why should exec() and eval() be avoided?

中所述

答案 1 :(得分:0)

一种解决方案是使用exec执行不同的代码,具体取决于我想要解析为函数的string类型参数,例如:

def plotfit(axis):
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    exec("ax.scatter(xdata, ydata, func_" + axis + "(vars,fitted_" + axis + "),c='r')")

类似的技术可用于您想要执行此操作的其他行。

请注意,建议不要使用exec(或eval),因为它通常可以隐藏错误并且可能含糊不清。请参阅:Why should exec() and eval() be avoided?