Matplotlib中K线图(candlestick)图例显示异常问题求助
问题原因
- 直接用字典给
plt.legend()传参的方式不符合Matplotlib的规范,无法正确映射标签与颜色的对应关系。 candlestick_ohlc函数不会自动为涨跌K线生成图例条目,必须手动创建虚拟元素来关联图例。
解决方案
- 绘制收盘价曲线时保存线条对象,用于图例关联。
- 手动创建代表上涨、下跌K线的矩形元素,作为图例的对应项。
- 将线条对象和矩形元素按顺序传入
plt.legend(),明确标签与元素的对应关系。
修改后的完整代码
#Import import numpy as np import yfinance as yf import matplotlib.pyplot as plt from mplfinance.original_flavor import candlestick_ohlc import matplotlib.dates as mdates from matplotlib.patches import Rectangle #Dates to get stocks start_date = "2020-01-01" end_date = "2023-05-08" #Get to the site tesla_data = yf.download("TSLA", start = start_date, end = end_date) #Get info off the site tesla_weekly_data = tesla_data.resample("W").agg({"Open":"first", "High":"max", "Low":"min", "Close":"last", "Volume":"sum"}).dropna() tesla_weekly_data.reset_index(inplace = True) tesla_weekly_data["Date"] = tesla_weekly_data["Date"].map(mdates.date2num) #Configer the plot fig, ax = plt.subplots(figsize=(16,8)) #Show Canddlestick candlestick_ohlc(ax, tesla_weekly_data.values, width = 5, colorup = "green", colordown = "red") #Fonts font1 = {"family":"serif", "color":"black", "size":40, "fontweight":"bold"} font2 = {"family":"serif", "color":"black", "size":20, "fontweight":"bold"} #Show Descripton of title and labels plt.xlabel("Date", fontdict = font2) plt.ylabel("Price",fontdict = font2) plt.title("Tesla Stock Prices", fontdict = font1) #Show the stocks line,保存线条对象 close_line, = plt.plot(tesla_data["Close"], color = "cyan", linewidth = 2) #创建涨跌K线的图例元素 up_patch = Rectangle((0,0), 1, 1, facecolor="green") down_patch = Rectangle((0,0), 1, 1, facecolor="red") #Add legend,传入元素和对应标签 plt.legend([close_line, up_patch, down_patch], ["Tesla Close Prices", "Price Up", "Price Down"]) #优化x轴日期显示(可选) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) fig.autofmt_xdate() #Show the plot plt.show()
关键修改点说明
- 绘制收盘价曲线时,用
close_line, = plt.plot(...)保存线条对象(逗号不能省略,因为plot返回的是元素列表)。 - 用
Rectangle创建虚拟矩形块,分别匹配上涨、下跌K线的颜色,用于图例展示。 plt.legend()接收两个列表参数:第一个是绘图元素集合,第二个是对应的标签集合,确保顺序一一对应。- 额外添加了x轴日期格式优化,避免日期重叠,提升图表可读性。
内容的提问来源于stack exchange,提问作者Damian
相关产品推荐
相关产品推荐

