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

如何在NVD3中设置Tooltip与X轴不同的日期格式?

Customize NVD3 Tooltip Date Format Without Changing X-Axis

No problem at all! You've already got the X-axis date format locked in as %d / %m—we just need to override the tooltip's date display independently, without messing with that existing setup. Here's how to do it cleanly:

Step 1: Keep Your Existing X-Axis Code

First, leave your current X-axis tick formatting exactly as it is—we don't need to touch this:

chart.xAxis.tickFormat(function(d) { 
  return d3.time.format('%d / %m')(new Date(d)); 
});

Step 2: Override the Tooltip Content Generator

NVD3 lets you completely customize the tooltip's content using the contentGenerator method. This lets us define our own date format for the tooltip while keeping the X-axis untouched. Add this code after your X-axis setup:

// Customize tooltip to show date in %d/%m/%y format
chart.tooltip.contentGenerator(function(data) {
  // Format the date with year included
  const formattedDate = d3.time.format('%d / %m / %y')(new Date(data.value));
  
  // Build tooltip HTML that matches NVD3's default styling (so it looks consistent)
  let tooltipContent = `
    <div class="nvtooltip">
      <h3>${formattedDate}</h3>
      <div class="tooltip-body">
  `;
  
  // Loop through each series in the tooltip to display values
  data.series.forEach(series => {
    tooltipContent += `
      <p>
        <span style="color: ${series.color}">●</span> 
        ${series.key}: ${series.value}
      </p>
    `;
  });
  
  tooltipContent += `
      </div>
    </div>
  `;
  
  return tooltipContent;
});

How This Works

  • The contentGenerator function receives a data object that contains all the information for the current tooltip (including the date value from the X-axis).
  • We take the raw date value, convert it to a Date object, and format it with %d / %m / %y to include the year.
  • We build HTML that mirrors NVD3's default tooltip structure and classes, so your tooltip keeps the same look and feel—only the date format changes.

This approach works for most NVD3 chart types (line, bar, area, etc.) since the contentGenerator is a universal tooltip customization method.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:44:31