我在 d3.js 中有一个折线图,每年在 X 轴上都有标签(显示 20 年的数据)。标签是通过以下方式创建的:
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).tickFormat(d3.timeFormat("%b/%d/%Y")).ticks(d3.timeYear))
.selectAll("text")
.style("text-anchor", "end")
.attr("dy", ".25em")
.attr("transform", "rotate(-45)");
结果如下所示:
现在,问题是,我需要不要在每年 1 月 1 日放置标签 - 我需要在 6 月 30 日放置它们。我怎样才能做到这一点?
请参阅Fiddle在这里亲自尝试一下。
最佳答案
执行此操作的一种方法是显式指定每个所需的轴刻度值。函数axis.tickValues
就是为此而设计的。
以下函数生成一个日期数组,从 min
日期(在您的例子中为 2000 年 6 月 28 日)开始,并添加一个年份,直到 max
日期( 2020 年 6 月 28 日)已达到。由于数据集并不包含所有年份的数据,因此有必要执行此生成步骤。
function generateTickvalues(min, max) {
let res = []
, currentExtent = new Date(min.valueOf())
while(currentExtent <= max) {
res.push(new Date(currentExtent.valueOf()))
currentExtent.setFullYear(currentExtent.getFullYear() + 1);
}
return res
}
备注:此函数中需要 new Date(date.valueOf())
,这样原始数据集中的日期值就不会被覆盖。
可以使用 d3.extent
方便地找到数据集中的最小和最大日期。该数组也可以在调用x.domain
时使用。
let dateExtent = d3.extent(data, function(d) { return d.date})
let tickValues = generateTickvalues(dateExtent[0], dateExtent[1])
x.domain(dateExtent);
然后,在生成轴时,调用函数axis.tickValues
,传递刚刚生成的从6月开始的年份数组:
d3.axisBottom(x)
.tickFormat(d3.timeFormat("%b/%d/%Y"))
.ticks(d3.timeYear)
.tickValues(tickValues)
下面代码片段中的演示:
const data = [
{ value: 46, date: '2000-06-28', formatted_date: '06/28/2000' },
{ value: 48, date: '2003-06-28', formatted_date: '06/28/2003' },
{ value: 26, date: '2004-06-28', formatted_date: '06/28/2004' },
{ value: 36, date: '2006-06-28', formatted_date: '06/28/2006' },
{ value: 40, date: '2010-06-28', formatted_date: '06/28/2010' },
{ value: 48, date: '2012-06-28', formatted_date: '06/28/2012' },
{ value: 34, date: '2018-06-28', formatted_date: '06/28/2018' },
{ value: 33, date: '2020-06-28', formatted_date: '06/28/2020' }
];
create_area_chart(data, 'history-chart-main');
function generateTickvalues(min, max) {
let res = []
, currentExtent = new Date(min.valueOf())
while(currentExtent <= max) {
res.push(new Date(currentExtent.valueOf()))
currentExtent.setFullYear(currentExtent.getFullYear() + 1);
}
return res
}
function create_area_chart(data, target){
document.getElementById(target).innerHTML = '';
var parentw = document.getElementById(target).offsetWidth;
var parenth = 0.6*parentw;
var svg = d3.select('#'+target).append("svg").attr("width", parentw).attr("height", parenth),
margin = {top: 20, right: 20, bottom: 40, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var parseTime = d3.timeParse("%Y-%m-%d");
bisectDate = d3.bisector(function(d) { return d.date; }).left;
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var area = d3.area()
.x(function (d) { return x(d.date); })
.y1(function (d) { return y(d.value); });
data.forEach(function (d) {
//only parse time if not already parsed (i.e. when using time period filters)
if(parseTime(d.date))
d.date = parseTime(d.date);
d.value = +d.value;
});
let dateExtent = d3.extent(data, function(d) { return d.date})
let tickValues = generateTickvalues(dateExtent[0], dateExtent[1])
x.domain(dateExtent);
y.domain([0, 1.05 * d3.max(data, function (d) { return d.value; })]);
area.y0(y(0));
g.append("rect")
.attr("transform", "translate(" + -margin.left + "," + -margin.top + ")")
.attr("width", svg.attr("width"))
.attr('class', 'overlay')
.attr("height", svg.attr("height"))
.on("mouseover", function () {
d3.selectAll(".eps-tooltip").remove();
d3.selectAll(".eps-remove-trigger").remove();
focus.style("display", "none");
});
g.append("path")
.datum(data)
.attr("fill", "#f6f6f6")
.attr("d", area);
//create line
var valueline = d3.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.value); });
g.append("path")
.data([data])
.attr('fill', 'none')
.attr('stroke', '#068d46')
.attr("class", "line")
.attr("d", valueline);
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).tickFormat(d3.timeFormat("%b/%d/%Y")).ticks(d3.timeYear).tickValues(tickValues))
.selectAll("text")
.style("text-anchor", "end")
.attr("dy", ".25em")
.attr("transform", "rotate(-45)");
g.append("g")
.call(d3.axisLeft(y)
.tickFormat(function (d) { return "$" + d }))
.append("text")
.attr("fill", "#068d46")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end");
var focus = g.append("g")
.attr("class", "focus")
.style("display", "none");
focus.append("line")
.attr("class", "x-hover-line hover-line")
.attr("y1", 0)
.attr("y2", height);
focus.append("line")
.attr("class", "y-hover-line hover-line")
.attr("x1", width)
.attr("x2", width);
focus.append("circle")
.attr("fill", "#068d46")
.attr("r", 4);
focus.append("text")
.attr("class", "text-date focus-text")
.attr("x", 0)
.attr("y", -20)
.attr("dy", ".31em")
.style("text-anchor", "middle");
focus.append("text")
.attr("class", "text-val focus-text")
.attr("x", 0)
.attr("y", -30)
.attr("dy", ".31em")
.style("text-anchor", "middle");
g.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function () { focus.style("display", null); })
.on("mousemove", function () {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.year > d1.year - x0 ? d1 : d0;
focus.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")");
focus.select(".text-date").text(function () { return d.formatted_date; });
focus.select(".text-val").text(function () { return '$' + d.value; });
focus.select(".x-hover-line").attr("y2", height - y(d.value));
focus.select(".y-hover-line").attr("x2", width + width);
});
}
.chart {
text-align: center;
padding: 10px 10px 25px 10px;
background: #f6f6f6;
}
.chart svg {
overflow: visible;
}
.chart .overlay {
fill: none;
pointer-events: all;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.8.0/d3.min.js"></script>
<div class="chart" id="history-chart-main"></div>
关于javascript - 在 d3.js 图表上显示 6 月而不是 1 月的年度 X 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60756142/