我想使用类方法绘制不同的线条。为了画一条线。与Passing plots out of a class类似,我使用此类绘制线
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
class Plotter(object):
def __init__(self, xval=None, yval=None, dim1=None, dim2=None):
self.xval = xval
self.yval = yval
self.dim1 = dim1
self.dim2 = dim2
def plotthing(self):
fig, ax = plt.subplots(figsize=(self.dim1,self.dim2))
ax.plot(self.xval, self.yval, 'o-')
return fig
app = Plotter(xval=range(0,10), yval=range(0,10), dim1=5, dim2=5)
plot = app.plotthing()
但是我想在同一图中绘制不同的曲线并在类中定义一个函数。
Xval = []
Yval = []
xval=range(0,10)
yval=range(0,10)
Xval.append(xval)
Yval.append(yval)
xval=range(0,10)
yval=np.sin(range(0,10))
Xval.append(xval)
Yval.append(yval)
如何定义要传递给绘图的函数?
class Plotter(object):
def __init__(self, xval=None, yval=None, dim1=None, dim2=None):
self.xval = xval
self.yval = yval
self.dim1 = dim1
self.dim2 = dim2
def function_do_plot(x, y):
do something
def plotthing(self):
fig, ax = plt.subplots(figsize=(self.dim1,self.dim2))
for i in range(0, len(self.xval)):
x = xval[i]
y = yval[i]
fig = function_do_plot(x, y)
return fig
答案 0 :(得分:0)
考虑遍历输入列表,而无需使用单独的方法:
class Plotter(object):
def __init__(self, xval=None, yval=None, dim1=None, dim2=None):
self.xval = xval # LIST
self.yval = yval # LIST
self.dim1 = dim1
self.dim2 = dim2
def plotthing(self):
fig, ax = plt.subplots(figsize=(self.dim1,self.dim2))
for i, j in zip(self.xval, self.yval):
ax.plot(i, j, 'o-')
return fig
# POPULATE LIST OF RANGES
Xval = []; Yval = []
xval = range(0,10)
yval = range(0,10)
Xval.append(xval)
Yval.append(yval)
xval = range(0,10)
yval = np.sin(range(0,10))
Xval.append(xval)
Yval.append(yval)
# PASS IN LIST OF RANGES
app = Plotter(xval=Xval, yval=Yval, dim1=5, dim2=5)
plot = app.plotthing()