如何在 Plotly JS 中悬停堆叠条形图时显示额外的悬停文本

How to display a extra hover text while hovering stacked bar graph in Plotly JS

我想在 Plotly JS 的条形图中显示悬停文本以显示总计数,如下图所示

我无法做到这一点,我总是只能显示 2 个悬停文本,如下所示

请告诉我如何添加 Total Tested 悬停文本作为第一个屏幕截图?

在这里找到我的例子https://codepen.io/Diji/pen/NWjNjjJ

您可以将 Total Tested 添加到图表,方法是将 Total Tested 作为另一条轨迹添加到 graphData

let graphData = [
  {
    x: [
      "4/15-4/21/2021",
      "4/22-4/28/2021",
      "4/29-5/5/2021",
      "5/6-5/12/2021",
      "5/13-5/19/2021",
      "5/20-5/26/2021",
      "5/27-06/02/2021",
      "6/3-6/9/2021",
      "6/10-6/16/2021",
      "6/17-6/23/2021",
    ],
    y: [4240, 4541, 4460, 2653, 4974, 2740, 2290, 2123, 1706, 1413],
    type: "bar",
    name: "Antigen",
    line: {
      color: "#322388",
      shape: "spline",
    },
    hovertemplate: "Antigen <b>%{y}</b><extra></extra>",
    marker: {
      color: "#322388",
    },
  },
  {
    x: [
      "4/15-4/21/2021",
      "4/22-4/28/2021",
      "4/29-5/5/2021",
      "5/6-5/12/2021",
      "5/13-5/19/2021",
      "5/20-5/26/2021",
      "5/27-06/02/2021",
      "6/3-6/9/2021",
      "6/10-6/16/2021",
      "6/17-6/23/2021",
    ],
    y: [3993, 3412, 3445, 6480, 1852, 4538, 3470, 3511, 2059, 2076],
    type: "bar",
    name: "PCR",
    line: {
      color: "#107733",
      shape: "spline",
    },
    hovertemplate: "PCR <b>%{y}</b><extra></extra>",
    marker: {
      color: "#107733",
    },
  },
  {
    // Beginning of Total Tested trace
    x: [
      "4/15-4/21/2021",
      "4/22-4/28/2021",
      "4/29-5/5/2021",
      "5/6-5/12/2021",
      "5/13-5/19/2021",
      "5/20-5/26/2021",
      "5/27-06/02/2021",
      "6/3-6/9/2021",
      "6/10-6/16/2021",
      "6/17-6/23/2021",
    ],
    // Set y axis to 0
    y: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    // Add total count - Antigen + PCR
    base: [
      4240 + 3993,
      4541 + 3412,
      4460 + 3445,
      2653 + 6480,
      4974 + 1852,
      2740 + 4538,
      2290 + 3470,
      2123 + 3511,
      1706 + 2059,
      1413 + 2076,
    ],
    type: "bar",
    name: "Total Tested",
    // Then you can add the hoverTemplate like this
    hovertemplate: "Total Tested <b>%{base}</b><extra></extra>",
    marker: {
      color: "red",
    },
  },
];

具有完整解决方案的 Codepen - https://codepen.io/yushanfernando/pen/XWRpzGK