迭代调用函数中的结果将被覆盖

时间:2019-07-12 14:20:10

标签: python function matplotlib subplot

以下函数在调用时绘制股票价格和交易量。但是,当调用它来迭代创建多个图时,输出中只会显示最后一个图。如何刷新图输出以获得多个图。尝试睡眠功能,但不起作用。

import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np


def skplot(ticker,dt1,dt2):
    tck = yf.Ticker(ticker)
    print(ticker+"\n"+"Market      Cap:"+'${:,.0f}'.format(tck.info["marketCap"]))
    df = yf.download(ticker, start=dt1, end=dt2)

    top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4)
    top.plot(df.index, df["Close"])
    plt.title(ticker)

    bottom = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4)
    bottom.bar(df.index, df['Volume'])

    plt.gcf().set_size_inches(10,8)

    time.sleep(1)

#this one works
skplot("HLIT","2018-01-01","2019-07-11")

#called in a loop produce only the last chart


def stocklist():
    '''Returns a list of stocks that met the criteria for rsi_plot'''
    l=[   
"HLIT"  ,
"OHRP"  ,
"HELE"  ,
"CY"           ]
    for i in l:
#        print(i)
        skplot(i,"2018-01-01","2019-07-11")
    return

stocklist()

2 个答案:

答案 0 :(得分:1)

尝试在plt.figure()上方添加top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4)
如果您不这样做,那么您将不断在同一图形中进行绘制并覆盖它,或者我认为是这样。因为我自己的matplotlib正在运行,所以无法真正测试它。

答案 1 :(得分:0)

如果您想要一个包含所有绘图的图形,则需要更改每个绘图的位置(行,列)并删除rowspancolspan参数:

def f(i):
    r,c = divmod(i, 4)
    top = plt.subplot2grid((4,4), (r, c))
    top.plot(range(10*i), range(10*i))

for i,thing in enumerate(range(16)):
    f(i)

plt.show()
plt.close()

除非您希望将绘图放置在常规网格之外的其他位置(类似于these examples),否则只能使用plt.subplot

def g(i):
    plt.subplot(4,4,i)
    plt.plot(range(10*i), range(10*i))

for i,thing in enumerate(range(16),1):
    g(i)

plt.show()
plt.close()