如何使用matplotlib在图形中显示图例

2024-04-27 20:13:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

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

有没有办法让图例显示出来,而不必手动输入每个EMA

谢谢, 丹


Tags: importpandasdfdatetimematplotlibstyleasstock
1条回答
网友
1楼 · 发布于 2024-04-27 20:13:32

可以在打印之前获取轴,然后使用它打印图例。在绘图完成后调用它,仅此而已

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

相关问题 更多 >