如何分组x轴数值减少拥挤 优化yfinance期权数据柱状图x轴标签
实现方式1:手动指定标签显示间隔
你可以直接按固定步长选取要显示的x轴标签,按需调整步长即可控制显示的标签总数:
import yfinance as yf import matplotlib.pyplot as plt aapl = yf.Ticker("AAPL") opt = aapl.option_chain('2021-10-08') opt.calls.set_index('strike', inplace = True) # 先获取绘图的axes对象方便后续操作 ax = opt.calls['lastPrice'].plot.bar() # 核心逻辑:按总刻度数计算步长,最终生成4-5个标签 total_ticks = len(ax.get_xticks()) step = total_ticks // 4 ax.set_xticks(ax.get_xticks()[::step]) ax.set_xticklabels(ax.get_xticklabels()[::step], rotation=0) # rotation可调整标签倾斜角度 plt.tight_layout() # 自动调整布局避免标签被截断 plt.show()
实现方式2:自动控制最大标签数量
如果不想手动计算步长,可以用MaxNLocator自动均匀生成指定数量的标签,更省心:
import yfinance as yf import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator aapl = yf.Ticker("AAPL") opt = aapl.option_chain('2021-10-08') opt.calls.set_index('strike', inplace = True) ax = opt.calls['lastPrice'].plot.bar() # 直接指定最多显示5个x轴标签,工具会自动选择均匀的刻度位置 ax.xaxis.set_major_locator(MaxNLocator(nbins=5)) plt.tight_layout() plt.show()
自定义指定标签数值
如果你需要严格按照固定间隔显示指定数值(比如100、120...200间隔20的规则),可以直接筛选符合条件的索引值作为标签:
# 接上面绘图获取ax后的逻辑 target_step = 20 # 筛选索引中满足间隔要求的位置和数值 show_index = [idx for idx, strike_val in enumerate(opt.calls.index) if strike_val % target_step == 0] show_labels = [strike_val for strike_val in opt.calls.index if strike_val % target_step == 0] ax.set_xticks(show_index) ax.set_xticklabels(show_labels)
内容的提问来源于stack exchange,提问作者Slartibartfast
相关产品推荐
相关产品推荐

