Python 如何将(*args,**kwargs)类型的属性传递给类中的函数?
我想为我的科学数据创建一个自定义绘图模块,但我不知道如何将Python 如何将(*args,**kwargs)类型的属性传递给类中的函数?,python,matplotlib,subplot,named-parameters,Python,Matplotlib,Subplot,Named Parameters,我想为我的科学数据创建一个自定义绘图模块,但我不知道如何将(*arg2,**kwarg2)类型的参数传递给方法 以下是相关代码: import numpy as np import matplotlib.pyplot as plt # class of figures for channel flow # with one subfigure class Homfig: # *args: list of plot features for ax1.plot # (x
(*arg2,**kwarg2)
类型的参数传递给方法
以下是相关代码:
import numpy as np
import matplotlib.pyplot as plt
# class of figures for channel flow
# with one subfigure
class Homfig:
# *args: list of plot features for ax1.plot
# (xdata,ydata,str linetype,str label)
# **kwargs: list of axes features for ax1.set_$(STH)
# possible keys:
# title,xlabel,ylabel,xlim,ylim,xscale,yscale
def __init__(self,*args,**kwargs):
self.args = args
self.kwargs = kwargs
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
for key, val in self.kwargs.iteritems():
getattr(self.ax,'set_'+key)(val)
def hdraw(self):
for arg in self.args:
self.ax.plot(*arg)
leg = self.ax.legend(loc=4)
问题是,arg
本身就是一个类似于(*agr2,**kwarg2)
的元组
自轴绘图(*arg)
它看不到命名变量。
函数hdraw
应该对从init获得的*args
中的输入进行操作,并将绘图线的数据传入arg
。
如何表示arg
由未命名变量和命名变量组成?
当我想要在一个绘图中有多行(使用不同的标签
,线型
等)时,可以多次调用self.ax.plot
)
我使用以下命令从其他python脚本调用模块:
meanfig = hfig.Homfig((datax,datay),title='test plot')
meanfig.hdraw()
如何将标签或线型等功能添加到self.ax.plot,例如:
meanfig = hfig.Homfig((datax,datay,label="test_label",linetype ='o'),title='test plot')
您应该能够使用双**通过考试,即
def hdraw(self):
self.ax.plot(*self.args, **self.kwargs)
leg = self.ax.legend(loc=4)
然后使用
meanfig = hfig.Homfig(datax, datay, label="test_label", linetype ='o', title='test plot')
meanfig = hfig.Homfig(title='test plot')
meanfig.add_plot(datax, datay, label="test_label", linetype ='o')
meanfig.add_plot(datax, 2 * datay, label="test_label_2", linetype ='o')
meanfig.hdraw()
根据评论更新:
如果您想在同一个图形中绘制多个绘图,以您编写的方式将很困难,但您可以这样做
class Homfig:
def __init__(self, title):
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
self.args = []
self.kwargs = []
def add_plot(self, *args, **kwargs):
self.args.append(args)
self.kwargs.append(kwargs)
def hdraw(self):
for args, kwargs in zip(self.args, self.kwargs):
self.ax.plot(*args, **kwargs)
leg = self.ax.legend(loc=4)
然后使用
meanfig = hfig.Homfig(datax, datay, label="test_label", linetype ='o', title='test plot')
meanfig = hfig.Homfig(title='test plot')
meanfig.add_plot(datax, datay, label="test_label", linetype ='o')
meanfig.add_plot(datax, 2 * datay, label="test_label_2", linetype ='o')
meanfig.hdraw()
此处可能重复的'kwargs'用于轴变量。我想把几个绘图放在一个图中,因此会有多个调用
self.ax.plot
查看更新后的答案,以了解执行此操作的方法。遗憾的是,仅在\uuuu init\uuuu
方法中执行此操作将很难以一种好的方式完成。