如何在NVD3中设置Tooltip与X轴不同的日期格式?
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
contentGeneratorfunction receives adataobject 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
Dateobject, and format it with%d / %m / %yto 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

