matplotlib 我怎样才能保持一个python函数的图形结果,尽管它被多次调用?

dffbzjpn  于 2023-02-13  发布在  Python
关注(0)|答案(2)|浏览(153)

我在为一个看跌期权绘制收益率曲线时很开心,我做了一个函数,它可以在给定参数的情况下绘制曲线,我希望能够为多个不同的参数绘制曲线,并同时显示它们以进行比较,这是我目前所做的:

import matplotlib.pyplot as plt
import numpy as np
#counter=1
def my_function(option,strike,bid,price):
    if option=="put":
        breakeven=price-bid
        x=[breakeven-10,breakeven,price,price+bid]
        y=[0]*len(x)
        i=0
        while i<len(x):
            if x[i]<price:
                y[i]=(x[i]*-100) + breakeven*100
            else:
                y[i]=-100*bid
            print(x[i],y[i])
            i+=1
        plt.figure(counter)
        plt.plot(x, y, label = str(strike))
        #naming the x axis
        plt.xlabel('price')
        #naming the y axis
        plt.ylabel('profit')
        plt.show() 
     #counter+=1          
my_function("put",90,20,100)
my_function("put",90,10,100)

但是,它只是替换它,而不是生成另一个图形。
在绘图之前,我尝试过使用全局计数器和plt.figure(计数器),但它不接受递增计数器。

iqih9akk

iqih9akk1#

你需要把fig, ax = plt.subplots()plt.show()从循环中取出来实现这一点,否则你就在同一个图上写东西。
代码如下所示:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

def my_function(option,strike,bid,price):
    if option=="put":
        breakeven=price-bid
        x=[breakeven-10,breakeven,price,price+bid]
        y=[0]*len(x)
        i=0
        while i<len(x):
            if x[i]<price:
                y[i]=(x[i]*-100) + breakeven*100
            else:
                y[i]=-100*bid
            # print(x[i],y[i])
            i+=1
        ax.plot(x, y, label = str(strike))
        #naming the x axis
        ax.set_xlabel('price')
        #naming the y axis
        ax.set_ylabel('profit')
        # plt.show()  <-- remove this !!
         
my_function("put",90,20,100)
my_function("put",90,10,100)

# plot all lines
plt.show()

结果是这样的

ajsxfq5m

ajsxfq5m2#

import matplotlib.pyplot as plt
import numpy as np

plt.close()
fig, ax = plt.subplots()

def my_function(option,strike,bid,price):
    if option=="put":
        breakeven=price-bid
        x=[breakeven-10,breakeven,price,price+bid]
        y=[0]*len(x)
        i=0
        while i<len(x):
            if x[i]<price:
                y[i]=(x[i]*-100) + breakeven*100
            else:
                y[i]=-100*bid
            # print(x[i],y[i])
            i+=1
        ax.plot(x, y, label = str(strike))
        #naming the x axis
        ax.set_xlabel('price')
        #naming the y axis
        ax.set_ylabel('profit')
        # plt.show() 
         
my_function("put",90,20,100)
my_function("put",90,10,100)

相关问题