运行Python matplotlib代码时表格下方出现坐标轴,如何隐藏?
解决Matplotlib表格图表坐标轴显示问题
你手动用text和plot绘制表格时,Matplotlib默认的Axes对象会显示坐标轴元素,只需添加一行代码就能隐藏它们:
方法一:完全隐藏坐标轴(推荐)
在plt.show()之前添加ax.axis('off'),直接关闭所有坐标轴相关元素(刻度、边框、标签)。
修改后的完整代码:
import matplotlib as mpl import matplotlib.patches as patches from matplotlib import pyplot as plt import datetime # 创建画布和坐标轴对象 fig, ax = plt.subplots(figsize=(8, 6)) # 设置表格行列数 rows = 10 cols = 6 # 设置坐标范围,增加上下左右内边距 ax.set_ylim(-1, rows + 1) ax.set_xlim(0, cols + .5) current_date = datetime.datetime.now() # 示例数据 data = [ {'id': 'player10', 'Price %': 125.658, 'Vol %': 255.489, 'goals': 125.859}, {'id': 'player9', 'Price %': 2, 'Vol %': 72, 'goals': 0}, {'id': 'player8', 'Price %': 3, 'Vol %': 47, 'goals': 0}, {'id': 'player7', 'Price %': 4, 'Vol %': 99, 'goals': 0}, {'id': 'player6', 'Price %': 5, 'Vol %': 84, 'goals': 1}, {'id': 'player5', 'Price %': 6, 'Vol %': 56, 'goals': 2}, {'id': 'player4', 'Price %': 7, 'Vol %': 67, 'goals': 0}, {'id': 'player3', 'Price %': 8, 'Vol %': 91, 'goals': 1}, {'id': 'player2', 'Price %': 9, 'Vol %': 75, 'goals': 3}, {'id': 'player1', 'Price %': 10, 'Vol %': 70, 'goals': 4} ] # 绘制表格内容 for row in range(rows): d = data[row] ax.text(x=.5, y=row, s=d['id'], va='center', ha='left') ax.text(x=2.5, y=row, s=d['Price %'], va='center', ha='right') ax.text(x=3.5, y=row, s=d['Vol %'], va='center', ha='right') ax.text(x=4.5, y=row, s=d['goals'], va='center', ha='right') # 绘制表头 ax.text(.5, 9.75, '', weight='bold', ha='left') ax.text(2.5, 9.75, 'Price %', weight='bold', ha='right') ax.text(3.5, 9.75, 'Vol %', weight='bold', ha='right') ax.text(4.5, 9.75, 'Goals', weight='bold', ha='right') # 绘制表格横线 for row in range(rows): ax.plot( [0, cols + 1], [row -.5, row - .5], ls=':', lw='.5', c='grey' ) # 绘制表头底部加粗横线 ax.plot([0, cols + 1], [9.5, 9.5], lw='.5', c='black') # 设置标题 ax.set_title( " test1 %s/%s/%s" % (current_date.day, current_date.month, current_date.year), loc='left', fontsize=15, weight='bold', color='r' ) # 隐藏坐标轴 ax.axis('off') plt.show()
方法二:精细控制隐藏元素
如果只想隐藏刻度和标签,保留表格边框,可替换上面的ax.axis('off')为以下代码:
# 隐藏x、y轴刻度 ax.set_xticks([]) ax.set_yticks([]) # 隐藏四个方向的边框 ax.spines[['top', 'right', 'bottom', 'left']].set_visible(False)
内容的提问来源于stack exchange,提问作者Ardaa
相关产品推荐
相关产品推荐

