【问题标题】:How to get legend to show in graph using matplotlib如何使用 matplotlib 让图例显示在图表中
【发布时间】:2020-05-02 18:32:42
【问题描述】:

制作了一个简单的程序来为股票创建指数移动平均线。代码如下:

import yfinance as yf
import pandas_datareader as pdr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.style as style
import datetime as dt

yf.pdr_override()

style.use('ggplot')

startyear = 2019
startmonth = 1
startday = 1

start = dt.datetime(startyear, startmonth, startmonth)
end = dt.datetime.now()

stock = input('Enter stock ticker: ')

df = pdr.get_data_yahoo(stock, start, end)

emasUsed = [3, 5, 8, 10, 13, 15, 30, 35, 40, 45, 50, 60]

for x in emasUsed:
    ema = x
    df['EMA_'+str(ema)] = df['Adj Close'].ewm(span=ema, adjust=True).mean()
    df['EMA_'+str(ema)].plot()

plt.show()

我想绘制移动平均线,但无法显示图例,除非我将 EMA 绘制在单独的行上,如下所示:

df[['EMA_3', 'EMA_5', 'EMA_8', etc...]].plot()

这显然需要做很多工作,特别是如果我想说添加或更改我想要获得的 EMA。

有什么方法可以显示图例而无需手动输入每个 EMA?

谢谢, 丹

【问题讨论】:

    标签: python python-3.x matplotlib stock moving-average


    【解决方案1】:

    您可以在绘图之前获取轴,然后使用它来绘制图例。在情节完成后调用它就可以了。

    import yfinance as yf
    import pandas_datareader as pdr
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.style as style
    import datetime as dt
    
    yf.pdr_override()
    
    style.use('ggplot')
    
    startyear = 2019
    startmonth = 1
    startday = 1
    
    start = dt.datetime(startyear, startmonth, startmonth)
    end = dt.datetime.now()
    
    #stock = input('Enter stock ticker: ')
    stock = 'SPY'
    
    df = pdr.get_data_yahoo(stock, start, end)
    
    emasUsed = [3, 5, 8, 10, 13, 15, 30, 35, 40, 45, 50, 60]
    
    fig, ax = plt.subplots(figsize=(10, 8)) # get the axis and additionally set a bigger plot size
    
    for x in emasUsed:
        ema = x
        df['EMA_'+str(ema)] = df['Adj Close'].ewm(span=ema, adjust=True).mean()
        df['EMA_'+str(ema)].plot()
    legend = ax.legend(loc='upper left') # Here's your legend
    
    plt.show()
    

    结果:

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2021-03-27
      • 1970-01-01
      • 2020-12-09
      • 2023-03-06
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      相关资源
      最近更新 更多