我试图在图表上显示一些日期/值配对,但 x 轴上有重复的值:
这是渲染刻度的代码:
chart
.select(".x-axis")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale).ticks(data.length).tickFormat(d3.timeFormat("%y-%m")));
完整代码片段:
var data = [{
date: "2020-01-01",
popularity: 50
},
{
date: "2020-02-01",
popularity: 150
},
{
date: "2020-03-01",
popularity: 200
},
{
date: "2020-04-01",
popularity: 250
},
{
date: "2020-05-01",
popularity: 200
},
{
date: "2020-06-01",
popularity: 250
},
{
date: "2020-07-01",
popularity: 350
}
];
// Create SVG and padding for the chart
const svg = d3
.select("#chart")
.append("svg")
.attr("height", 400)
.attr("width", 600);
const margin = {
top: 50,
bottom: 50,
left: 50,
right: 50
};
const chart = svg.append("g").attr("transform", `translate(${margin.left},0)`);
const width = +svg.attr("width") - margin.left - margin.right;
const height = +svg.attr("height") - margin.top - margin.bottom;
const grp = chart
.append("g")
.attr("transform", `translate(-${margin.left},-${margin.top})`);
// Add empty scales group for the scales to be attatched to on update
chart.append("g").attr("class", "x-axis");
chart.append("g").attr("class", "y-axis");
function updateScales(data) {
// Create scales
const yScale = d3
.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, dataPoint => dataPoint.popularity)]);
// Set Date Range
var earliestDate = new Date(data[0].date);
var lastDate = new Date(data[data.length - 1].date);
// Setting up date on the X axis
const xScale = d3
.scaleLinear()
.range([0, width])
.domain([earliestDate, lastDate]);
return {
yScale,
xScale
};
}
蛊毒传说
相关分类