我正在尝试仅选择要在我的X轴上显示的特定范围的标签。基本上它是一个时间序列,我想选择每个替代月份显示在轴标签上。但无法弄清楚这样做的方法。
到目前为止,这是我的小提琴
http://jsfiddle.net/sourabhtewari/1n19kwpv/
我的代码暂时看起来像这样
var stuff = [{
"year": 2015,
"month": 12,
"s1": 0.38
},
{
"year": 2016,
"month": 1,
"s1": 0.39
},
{
"year": 2016,
"month": 2,
"s1": 0.43
},
{
"year": 2016,
"month": 3,
"s1": 0.40
},
{
"year": 2016,
"month": 4,
"s1": 0.39
},
{
"year": 2016,
"month": 5,
"s1": 0.39
},
{
"year": 2016,
"month": 6,
"s1": 0.38
},
{
"year": 2016,
"month": 7,
"s1": 0.37
},
{
"year": 2016,
"month": 8,
"s1": 0.37
},
{
"year": 2016,
"month": 9,
"s1": 0.35
},
{
"year": 2016,
"month": 10,
"s1": 0.37
},
{
"year": 2016,
"month": 11,
"s1": 0.36
},
{
"year": 2016,
"month": 12,
"s1": 0.37
},
{
"year": 2017,
"month": 1,
"s1": 0.35
},
{
"year": 2017,
"month": 2,
"s1": 0.36
},
{
"year": 2017,
"month": 3,
"s1": 0.37
},
{
"year": 2017,
"month": 4,
"s1": 0.38
},
{
"year": 2017,
"month": 5,
"s1": 0.35
},
{
"year": 2017,
"month": 0.36,
"s1": 0.36
},
{
"year": 2017,
"month": 7,
"s1": 0.36
},
{
"year": 2017,
"month": 8,
"s1": 0.35
},
{
"year": 2017,
"month": 9,
"s1": 0.36
},
{
"year": 2017,
"month": 10,
"s1": 0.37
},
];
var vals = [];
for (var i = 0; i < stuff.length; ++i) {
var date = new Date(stuff[i]["year"], stuff[i]["month"] - 1, 1);
vals.push({
x: date,
y: stuff[i]["s1"]
});
}
nv.addGraph(function() {
var data = [{
"values": vals,
"key": "s1",
"color": "#000000"
}];
var chart = nv.models.lineChart()
.forceY([0, 0.5]);
chart.xAxis.axisLabel("Date (m/y)")
.tickFormat(function(d, i) {
if (i % 2 == 1) d3.select(this).remove();
console.log(i);
return d3.time.format("%b-%y")(new Date(d))
});
chart.yAxis.axisLabel("s1").tickFormat(d3.format(","));
d3.select("#chart svg")
.datum(data)
.call(chart);
nv.utils.windowResize(function() {
d3.select("#chart svg").call(chart)
});
return chart;
});
答案 0 :(得分:0)
尝试为xAxis添加刻度线(d3.utcMonth)。
chart.xAxis.axisLabel("Date (m/y)")
.ticks(d3.utcMonth)
.tickFormat(function(d,i) {
return d3.time.format("%b-%y")(new Date(d))
}) ;
答案 1 :(得分:0)
我相信这个问题的答案是肯定的,你可以通过一个可能的警告(下面)。
根据this,您可以执行以下操作:
// Add the X Axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x)
.ticks(d3.timeMonth.every(2)));
我不赞成的一件事是d3v3中是否包含timeMonth方法。似乎nvd3还不支持d3v4,这个例子是在d3v4中制作的。
希望这有帮助。