如何使用matplotlib让图例显示在图表中?

问题描述 投票:0回答: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: ')

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

我想画出移动平均线的图形 但不能让图例显示出来 除非我把EMAs画在单独的一条线上 就像这样。

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

这显然是一个很大的工作,特别是如果我想说添加或改变我想得到的EMAs。

有什么办法可以让图例显示出来,而不必手动输入每个EMA?

谢谢你,丹

python python-3.x matplotlib stock moving-average
1个回答
0
投票

你可以在绘图之前得到轴,然后用它来绘制图例。绘图完成后再调用它就可以了。

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

结果呢。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.