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

如何实现以日期为横轴的Plotly水平直方图

需求实现方案:水平重叠直方图(日期轴+自定义数值)

完全可以实现你的需求,以下是修改后的完整代码及关键说明:

修改后的完整代码

HTML部分

<head>
    <!-- Load plotly.js into the DOM -->
    <script src='https://cdn.plot.ly/plotly-3.0.1.min.js'></script>
</head>

<body>
    <div id='myDiv'></div>
</body>

JavaScript部分

// 替换为你的示例数据
const dates = ["2010-01-01", "2012-01-01", "2014-01-01"];
const trace1Values = [10, 12, 14];
const trace2Values = [15, 20, 22];

// 定义水平直方图轨迹
const trace1 = {
  y: dates,
  x: trace1Values,
  type: "histogram",
  orientation: "h", // 设置为水平直方图
  marker: {
    color: 'blue'
  },
  name: "Trace 1"
};

const trace2 = {
  y: dates,
  x: trace2Values,
  type: "histogram",
  orientation: "h",
  marker: {
    color: 'grey'
  },
  name: "Trace 2"
};

const data = [trace1, trace2];
const layout = {
  barmode: "overlay", // 保持重叠模式
  yaxis: {
    type: "category", // 将y轴设为分类轴,适配日期
    title: "日期"
  },
  xaxis: {
    title: "数值"
  },
  title: "日期对应数值的水平重叠直方图"
};

Plotly.newPlot('myDiv', data, layout);

关键修改点说明

  • 水平直方图设置:给每个trace添加orientation: 'h',同时将日期数据绑定到y轴,数值数据绑定到x轴,替换原有的随机数据结构
  • 日期轴配置:在layout的yaxis中设置type: "category",确保日期以分类形式正确显示,若需要时间轴特性可改为type: "date"
  • 数据结构调整:直接使用你提供的结构化日期-数值数据,替换原有的随机生成数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:18:28