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

如何绘制带各时间步垂直直方图的折线图

实现均值折线+时间步垂直分布直方图的方法

可以利用matplotlib的inset_axes功能,在主图的每个时间点位置嵌入小型横向直方图(对应你要的垂直分布展示),具体代码如下:

import numpy as np
import matplotlib.pyplot as plt

# 生成示例数据,行是观测值,列是时间步
x = np.random.rand(100,10) + np.arange(0,10)/100
timesteps = np.arange(x.shape[1])
mean_vals = np.mean(x, axis=0)

# 创建主图
fig, ax = plt.subplots(figsize=(10,6))
ax.plot(timesteps, mean_vals, marker='o', color='tab:blue', label='均值')
ax.set_xlabel('时间步')
ax.set_ylabel('均值')
ax.legend()
ax.grid(axis='y', alpha=0.3)

# 设置每个嵌入直方图的大小和位置参数
hist_width = 0.2  # 每个直方图的宽度
hist_height = 1.5 # 直方图的纵向长度

for i in timesteps:
    # 在对应时间步位置创建嵌入坐标轴
    inset_ax = ax.inset_axes([i - hist_width/2, ax.get_ylim()[0], hist_width, hist_height])
    # 绘制横向直方图,orientation='horizontal'实现垂直分布展示
    inset_ax.hist(x[:,i], orientation='horizontal', bins=10, color='tab:orange', alpha=0.7)
    # 隐藏嵌入轴的多余刻度和标签,让画面更整洁
    inset_ax.set_xticks([])
    inset_ax.set_yticks([])
    # 给每个直方图顶部标注均值点
    inset_ax.scatter(0, mean_vals[i], color='tab:blue', marker='o')

plt.tight_layout()
plt.show()

关键说明:

  • 用inset_axes在主图指定位置创建小坐标轴,参数[x0, y0, width, height]对应嵌入轴左下角坐标、宽度和高度
  • 直方图设置orientation='horizontal',将常规横向分布转为垂直方向,匹配时间步的观测值分布展示需求
  • 隐藏嵌入轴刻度避免干扰主图视觉,也可根据需求保留必要刻度

如果想要更简洁的展示,也可以用小提琴图结合折线图的方式:

fig, ax = plt.subplots(figsize=(10,6))
# 绘制小提琴图展示每个时间步的分布
ax.violinplot(x, positions=timesteps, showmeans=True, showmedians=False, widths=0.3)
# 叠加均值折线
ax.plot(timesteps, mean_vals, marker='o', color='red', linewidth=2, label='均值')
ax.set_xlabel('时间步')
ax.set_ylabel('数值')
ax.legend()
plt.show()

这种方式能直观展示每个时间步的分布形态和均值位置,和你想要的效果逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:50:26