You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib直方图的指定横轴位置添加带标签的X形标记

实现方案

你可以通过matplotlib的混合坐标变换功能实现需求:X轴使用实际数据坐标匹配你要的横轴位置,Y轴使用轴相对坐标,无需绑定实际数据的Y轴数值,标记会固定显示在X轴附近的指定位置。

新增代码步骤

  1. 先导入混合坐标变换工具:
from matplotlib.transforms import blended_transform_factory
  1. 在plt.subplots_adjust(bottom=0.15)之前添加如下代码,你可以自行修改markers列表里的横轴数值为你需要的实际值:
# 创建混合变换:x用数据坐标,y用轴相对坐标
trans = blended_transform_factory(ax.transData, ax.transAxes)
# 定义标记的横轴位置和对应标注,数值可自行替换为你需要的实际值
markers = [
    (-1.2, 'orange'),
    (0.3, 'apple'),
    (1.5, 'pineapple')
]
for x_val, label in markers:
    # 绘制X形标记,y=0.02表示在轴高度2%的位置,固定在X轴上方
    ax.scatter(x_val, 0.02, marker='x', s=80, c='black', transform=trans, zorder=10)
    # 绘制标注文本,放在X标记下方
    ax.text(x_val, -0.06, label, ha='center', transform=trans, fontsize=10)

完整修改后代码

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter
from matplotlib.transforms import blended_transform_factory

data = np.random.randn(82)
fig, ax = plt.subplots()
counts, bins, patches = ax.hist(data, facecolor='yellow', edgecolor='gray')

# Set the ticks to be at the edges of the bins.
ax.set_xticks(bins)
# Set the xaxis's tick labels to be formatted with 1 decimal place...
ax.xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))

# Change the colors of bars at the edges...
twentyfifth, seventyfifth = np.percentile(data, [25, 75])
for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]):
    if rightside < twentyfifth:
        patch.set_facecolor('green')
    elif leftside > seventyfifth:
        patch.set_facecolor('red')

# Label the raw counts and the percentages below the x-axis...
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
for count, x in zip(counts, bin_centers):
    # Label the raw counts
    ax.annotate(str(count), xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -18), textcoords='offset points', va='top', ha='center')

    # Label the percentages
    percent = '%0.0f%%' % (100 * float(count) / counts.sum())
    ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -32), textcoords='offset points', va='top', ha='center')

# 新增:添加X形标记和标注
trans = blended_transform_factory(ax.transData, ax.transAxes)
markers = [
    (-1.2, 'orange'),
    (0.3, 'apple'),
    (1.5, 'pineapple')
]
for x_val, label in markers:
    ax.scatter(x_val, 0.02, marker='x', s=80, c='black', transform=trans, zorder=10)
    ax.text(x_val, -0.06, label, ha='center', transform=trans, fontsize=10)

# Give ourselves some more room at the bottom of the plot
plt.subplots_adjust(bottom=0.2) # 可以把底部边距调大一点避免标注被截断
plt.show()

你可以根据实际排版需求调整标记的大小s、颜色c、文本位置的Y相对值、底部边距bottom的数值。

内容的提问来源于stack exchange,提问作者inic72

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:06:03