如何解决matplotlib绘图Y轴刻度标签重叠溢出(保留全量刻度)

问题描述
使用matplotlib基于CSV数据绘制折线图时,Y轴维度包含近500个唯一值,绘图完成后Y轴刻度标签互相重叠溢出,要求保留全部Y轴刻度、不跳过任何条目,同时保证所有刻度值清晰可读。
原始代码如下:
fig, ax = plt.subplots() #plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi) plt.rcParams["figure.figsize"] = [7.00, 5.50] plt.rcParams["figure.autolayout"] = True space = 3 dash_len = 3 ax.set_facecolor("yellow") ax.plot(sorted(failed_it),failed_p,color='r',linestyle='dashed',dashes=(dash_len, space),alpha=0.7, linewidth = 1,marker='s', markerfacecolor='red', markersize=4) ax.plot(sorted(passed_it),passed_p,color='g',linestyle='dashed',dashes=(dash_len, space),alpha=0.7, linewidth = 1,marker='d', markerfacecolor='blue', markersize=4) plt.style.use('fivethirtyeight') plt.xlabel("Iteration_Rate",fontweight="bold",fontsize=9) plt.ylabel("Trigger_Port,VLAN",fontweight="bold") plt.title("Platform="+str(keyss[3])+",Build="+ str(list1_8112[0][1])+",Trigger-SystemRestart",fontweight="bold") size = fig.get_size_inches()*fig.dpi print(size) ax = plt.gca() ax.set_xticks(np.arange(0,6,1)) ax.xaxis.set_label_coords(1.07, -0.025) ax.xaxis.set_major_locator(plt.MaxNLocator(100)) plt.yticks(port_VLAN_8112,ha='right',fontsize=8) plt.xticks(it_rate_8112[::20],ha='right',fontsize=8) plt.margins(0) ax.grid('on') plt.show() fig = plt.figure()
解决方案
重叠的根本原因是默认画布高度仅5.5英寸,500个标签平均每个标签分到的垂直空间不足0.3毫米,完全无法正常显示。另外原有代码中plt.style.use位置错误,会覆盖之前的自定义配置。按以下步骤修改即可:
注意:
plt.style.use('fivethirtyeight')需要放在所有rcParams配置、画布初始化代码之前,否则style的默认配置会覆盖你自定义的figsize、字号等设置。
- 动态调整画布高度:按每个Y轴标签至少分配0.12英寸垂直空间计算,500个标签需要至少60英寸的画布高度,替换原有figsize配置,直接根据Y轴标签总数计算高度,适配不同数量的标签场景:
# 把这行放在plt.style.use之后,fig, ax = plt.subplots()之前 y_total = len(port_VLAN_8112) plt.rcParams["figure.figsize"] = [7.0, 0.12 * y_total]
- 调整Y轴标签字号与边距:将Y轴标签字号从8号缩小到5-6号,同时给Y轴标题增加内边距,避免标题和标签挤在一起:
# 替换原有plt.yticks和plt.ylabel配置 plt.ylabel("Trigger_Port,VLAN", fontweight="bold", labelpad=20) plt.yticks(port_VLAN_8112, ha='right', fontsize=5)
- 强制显示全部Y轴刻度:关闭matplotlib默认的自动刻度裁剪逻辑,指定固定刻度定位器,确保不会自动跳过任何你设置的Y轴条目:
# 加在plt.yticks配置之后 ax.yaxis.set_major_locator(plt.FixedLocator(range(len(port_VLAN_8112))))
- 优化导出与显示效果:使用tight_layout自动调整边距,避免标签被画布边缘截断;如果需要保存图片,调高DPI并设置bbox_inches='tight',交互预览时直接滚动画布即可查看全部内容:
# 加在plt.show()之前 plt.tight_layout() # 需要保存图片时注释plt.show(),启用下面这行 # plt.savefig("port_vlan_chart.png", dpi=150, bbox_inches='tight') plt.show()
内容的提问来源于stack exchange,提问作者Holkar Klein
相关产品推荐
相关产品推荐

