如何使用tickFormat只显示年份(以世纪和最后两位数字表示)

How to use tickFormat to only show the year (as century and last two digits)

本文关键字:表示 最后 两位 数字 tickFormat 何使用 显示      更新时间:2023-09-26

这是我的代码,包括JSON示例以及我如何解析日期。

现在的日期显示为:2013年1月10日,例如

如何为x轴编写tickFormat函数,返回tickValues函数中指定的第一年的全年(带世纪)和所有其他年份的'14(例如2014年)?

            JSON structure:
            var shortData5= [
            {"date":"10/1/2013","shortFig":12},
            {"date":"11/1/2013","shortFig":34},
            {"date":"12/1/2013","shortFig":-25}]

            //fyi- var shortData5 is passed in my chart building function as "thedata"
            var parseDate = d3.time.format("%x").parse;
            thedata.forEach(function(d) {               
                parseDate(d.date);
            }); 
            //Set up the X scales
            //for bars
            var xScaleOrdinal = d3.scale.ordinal()
                .rangeRoundBands([0, width], .1)
                .domain(thedata.map(function(d) { return d.date; }));
            //With the X scales, set up the X axis  
            var xAxis= d3.svg.axis()
                .orient("bottom")
                .tickFormat() //need function here;
            if(theDiv=="#contructionSingleMulti"|| theDiv=="#volumeExistingLong"|| theDiv=="#volumeNewLong"){
                xAxis.scale(xScaleOrdinal)
 .tickValues([thedata[4].date,thedata[16].date,thedata[28].date,thedata[40].date,thedata[52].date,thedata[64].date,thedata[76].date,thedata[88].date,thedata[100].date,thedata[112].date]);             
            }else{
                xAxis.scale(xScaleOrdinal)
                .tickValues([thedata[0].date,thedata[3].date]);             
            }

            //Call the X axis
            baseGroup.append("g")
                 .attr("class", "xaxis")
                 .attr("transform", "translate(0," + height + ")")
                 .call(xAxis);

我不确定您想如何根据提出问题的方式来格式化勾号值。也许举个例子会更有帮助。您可以创建一个自定义刻度格式函数,以传递给刻度的.tickFormat访问器方法。

你可以这样做:

scale.tickFormat(myCustomTickFormatter);
function myCustomTickFormatter(datum, index)
{
    return /** some manipulation of datum **/
} 

另请参阅http://bl.ocks.org/mbostock/4149176以获取定义自己的自定义tick格式化程序的更复杂示例。