简体   繁体   中英

Python: how to use classes for plotting different lines?

I want to plot different lines using a class method. In order to plot a line. Similar to Passing plots out of a class I use this class to plot a line

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()

在此处输入图片说明

However I would like to plot different curves in the same plot and define a function inside the class to do so.

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)

How can I define a function to pass to plotthing?

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

Consider looping through your lists of inputs without needing a separate method:

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()

绘图输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM