如何将Matplotlib中X轴刻度标签移近X轴
问题:调整Matplotlib图表X轴刻度标签与刻度线的间距,适配PPT展示
我正尝试精简图表,以便将其与其他图表一同放入PPT幻灯片且保持清晰可读。若能将X轴刻度标签移近刻度线会大有帮助,但我不知该如何操作。我已添加了模拟数据,实际文件中这些数据为日期,特此说明。
原代码
import matplotlib.pyplot as plt from matplotlib import rcParams import matplotlib.dates as dates import math from matplotlib.ticker import MaxNLocator from matplotlib.legend_handler import HandlerLine2D tva_blue = '#003A70' lt_grey = '#BFBFBF' green = '#00B050' median = '#7F7F7F' black = '#000000' x = [10, 20, 30,40, 50, 60, 70, 80] y = [8, 5, 3, 6, 8, 6, 2, 9] z = [11, 10, 10, 9, 9, 9, 8, 7] dates.ConciseDateConverter(x) labels = x tfont = {'font': 'arial', 'size': 6.5, 'fontweight': 'bold'} lfont = {'font': 'arial', 'size': 6, 'fontweight': 'bold'} #Set Chart Size rcParams['figure.figsize'] = (2, 1) fig, ax = plt.subplots() fig.set_dpi(400) # Find Min / Max, use to set y axis dimensions mx = math.ceil(12) ymin = round(8) # Generate Bar Chart with Line interse plt.bar(x, y, color = tva_blue, width = 20, align = 'center', label = 'Retail Rate (¢/kWh)') plt.plot(x, z, color = green, lw = 1.5, label = 'Top Quartile') # Place Date labels onto x axis plt.xticks(x, labels, fontsize = 5, rotation='vertical') plt.yticks(y, fontsize = 5) # Set y axis parameters plt.ylim(8, (mx)) plt.ylabel("Cents / kWh", fontdict = lfont) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) #Add title to chart plt.title('TVA Effective Retail Rate \n 12-Month Rolling Average Trends \nTVA Rate Gap to Top Quartile Utility Co. Peers' , fontdict=(tfont), fontname = 'Arial', y = 1.32, color = 'black') # Hide top, right spines plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) # Center Ticks, Pad margins ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=16)) ax.tick_params(axis='x', which='minor', tick1On=True, tick2On=False, length = 3) ax.tick_params(axis='x', which='major', tick1On=False, tick2On=False) for label in ax.get_xticklabels(minor=True): label.set_horizontalalignment('center') ax.margins(x=0.013) # Format left and bottom axes for axis in ['left', 'bottom']: ax.spines[axis].set_linewidth(.7) ax.spines[axis].set_color(black) # Format Legend Line Width def update(handle, orig): handle.update_from(orig) handle.set_linewidth(2.5) # Format Legend Location plt.legend(handler_map={plt.Line2D : HandlerLine2D(update_func=update)}, ncol = 2, bbox_to_anchor = (0.5, 1.40), loc = 'upper center', frameon = False, fontsize = 5) # Generate chart plt.show()
解决方案
要让X轴刻度标签靠近刻度线,核心是通过ax.tick_params()的pad参数控制标签与刻度线的间距,同时针对日期数据优化显示逻辑。以下是修改后的代码及关键说明:
关键调整点
- 用
ax.tick_params(axis='x', which='major', pad=1)设置主刻度标签的间距,pad值越小,标签离刻度线越近(默认值为4) - 修正原代码中y轴下限设置错误的问题,避免柱状图被截断
- 替换为真实日期数据模拟,贴合实际使用场景
- 添加
plt.tight_layout()优化布局,防止标签被截断
修改后的代码
import matplotlib.pyplot as plt from matplotlib import rcParams import matplotlib.dates as dates import math from matplotlib.ticker import MaxNLocator from matplotlib.legend_handler import HandlerLine2D import datetime tva_blue = '#003A70' lt_grey = '#BFBFBF' green = '#00B050' median = '#7F7F7F' black = '#000000' # 模拟实际日期数据 x = [datetime.datetime(2023, i, 1) for i in range(1,9)] y = [8, 5, 3, 6, 8, 6, 2, 9] z = [11, 10, 10, 9, 9, 9, 8, 7] # 格式化日期标签 labels = [d.strftime('%Y-%m') for d in x] tfont = {'font': 'arial', 'size': 6.5, 'fontweight': 'bold'} lfont = {'font': 'arial', 'size': 6, 'fontweight': 'bold'} # 设置图表尺寸 rcParams['figure.figsize'] = (2, 1) fig, ax = plt.subplots() fig.set_dpi(400) # 计算y轴范围 mx = math.ceil(12) ymin = 0 # 绘制柱状图和折线图 ax.bar(x, y, color = tva_blue, width = 20, align = 'center', label = 'Retail Rate (¢/kWh)') ax.plot(x, z, color = green, lw = 1.5, label = 'Top Quartile') # 设置X轴刻度和标签,调整标签与刻度线的间距 ax.set_xticks(x) ax.set_xticklabels(labels, fontsize = 5, rotation='vertical') ax.tick_params(axis='x', which='major', pad=1) # 关键:缩小标签与刻度线的距离 ax.tick_params(axis='y', fontsize = 5) # 设置y轴参数 ax.set_ylim(ymin, mx) ax.set_ylabel("Cents / kWh", fontdict = lfont) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # 添加标题 ax.set_title('TVA Effective Retail Rate \n 12-Month Rolling Average Trends \nTVA Rate Gap to Top Quartile Utility Co. Peers' , fontdict=(tfont), fontname = 'Arial', y = 1.32, color = 'black') # 隐藏顶部和右侧边框 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # 设置X轴次要刻度 ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=16)) ax.tick_params(axis='x', which='minor', tick1On=True, tick2On=False, length = 3, pad=0) ax.tick_params(axis='x', which='major', tick1On=False, tick2On=False) for label in ax.get_xticklabels(minor=True): label.set_horizontalalignment('center') ax.margins(x=0.013) # 格式化左侧和底部边框 for axis in ['left', 'bottom']: ax.spines[axis].set_linewidth(.7) ax.spines[axis].set_color(black) # 调整图例线条宽度 def update(handle, orig): handle.update_from(orig) handle.set_linewidth(2.5) # 设置图例位置 ax.legend(handler_map={plt.Line2D : HandlerLine2D(update_func=update)}, ncol = 2, bbox_to_anchor = (0.5, 1.40), loc = 'upper center', frameon = False, fontsize = 5) # 优化布局并显示图表 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者user8346341
相关产品推荐
相关产品推荐

