如何在Matplotlib中让X轴标签居中显示于刻度之间?
如何让Matplotlib X轴标签居中显示在刻度之间?
我用随机数绘制散点图的原始代码如下:
import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np x = np.random.rand(10) y = np.random.rand(10) fig, ax = plt.subplots() ax.plot(y, x, '*') plt.show()
想要自定义X轴标签并让标签居中在两个刻度之间,修改后的代码没达到预期效果:
import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np x = np.random.rand(10) y = np.random.rand(10) fig, ax = plt.subplots() ax.plot(y, x, '*') xlabels = ['potato','tomato','apple','cherry','pie'] # Remove the major tick labels ax.xaxis.set_major_formatter(ticker.NullFormatter()) # Set the major ticks to match the number of labels num_labels = len(xlabels) mticks = np.arange(num_labels) ax.set_xticks(mticks) ax.set_xticklabels(xlabels) # Rotate the x-axis labels for label in ax.get_xticklabels(): label.set_rotation(90) label.set_horizontalalignment('right') # Adjust horizontal alignment plt.show()
问题原因
当前代码是把标签直接绑定在主刻度位置上,自然无法实现“居中于两个刻度之间”的效果。要达成需求,有两种简单的修改方式:
方案一:用主次刻度实现(推荐)
核心逻辑是让主刻度作为分隔线,把自定义标签放在两个主刻度的中间位置(次要刻度):
import matplotlib.pyplot as plt import numpy as np x = np.random.rand(10) y = np.random.rand(10) fig, ax = plt.subplots() ax.plot(y, x, '*') xlabels = ['potato','tomato','apple','cherry','pie'] num_labels = len(xlabels) # 设置主刻度:数量比标签多1,确保每个标签对应两个主刻度的中间 major_ticks = np.arange(num_labels + 1) ax.set_xticks(major_ticks) # 隐藏主刻度的文字标签 ax.xaxis.set_major_formatter(plt.NullFormatter()) # 设置次要刻度:放在相邻主刻度的中间位置 minor_ticks = major_ticks[:-1] + 0.5 ax.set_xticks(minor_ticks, minor=True) # 把自定义标签绑定到次要刻度 ax.set_xticklabels(xlabels, minor=True) # 调整标签样式 for label in ax.get_xticklabels(minor=True): label.set_rotation(90) label.set_horizontalalignment('center') plt.show()
方案二:直接偏移标签位置
如果不想调整刻度体系,也可以手动修改标签的x坐标,让它从当前刻度位置偏移到两个刻度的中间:
import matplotlib.pyplot as plt import numpy as np x = np.random.rand(10) y = np.random.rand(10) fig, ax = plt.subplots() ax.plot(y, x, '*') xlabels = ['potato','tomato','apple','cherry','pie'] num_labels = len(xlabels) mticks = np.arange(num_labels) ax.set_xticks(mticks) ax.set_xticklabels(xlabels) # 可选:隐藏主刻度线,避免视觉干扰 ax.tick_params(axis='x', which='major', length=0) # 调整标签位置:每个标签向右偏移0.5个单位(对应刻度间隔) for label in ax.get_xticklabels(): label.set_rotation(90) label.set_horizontalalignment('center') # 修改标签的x坐标,实现居中 label.set_x(label.get_position()[0] + 0.5) plt.show()
内容的提问来源于stack exchange,提问作者time12
相关产品推荐
相关产品推荐

