如何强制所有xAxis标签显示在我的图表上而不通过.tickvalues定义每个标记?
我是nvd3的新手,这是我的第一次尝试。 也许有一个心地善良的人可以查看我的代码并帮助我。 我做了我的研究,但没有任何对我有用。
这是我的代码:
var data = [
{
"key": "www.WebsiteA.com",
"values": [
{date:"20151221",rank:1},
{date:"20151222",rank:3},
{date:"20151223",rank:2},
{date:"20151224",rank:4},
{date:"20151225",rank:2},
{date:"20151226",rank:5},
{date:"20151227",rank:3},
{date:"20151228",rank:2},
{date:"20151229",rank:2},
{date:"20151230",rank:1},
{date:"20151231",rank:2},
{date:"20160101",rank:4},
{date:"20160102",rank:5},
{date:"20160103",rank:3},
] },
{
"key": "www.WebsiteB.com",
"values": [
{date:"20151221",rank:2},
{date:"20151222",rank:1},
{date:"20151223",rank:3},
{date:"20151224",rank:5},
{date:"20151225",rank:1},
{date:"20151226",rank:4},
{date:"20151227",rank:1},
{date:"20151228",rank:5},
{date:"20151229",rank:3},
{date:"20151230",rank:4},
{date:"20151231",rank:2},
{date:"20160101",rank:1},
{date:"20160102",rank:3},
{date:"20160103",rank:2},
] },
]
nv.addGraph(function() {
var chart = nv.models.lineChart()
.x(function(d) {return d3.time.format("%Y%m%d").parse(d.date) })
.y(function(d) {return d.rank})
.yDomain([6, 1])
.color(d3.scale.category10().range())
.useInteractiveGuideline(true)
.margin({left: 100})
.margin({right: 50})
.margin({bottom: 100})
;
chart.legend.margin({top: 10, right:60, left:80, bottom: 100});
chart.xAxis
.tickFormat(function(d) {return d3.time.format('%Y-%m-%d')(new Date(d)) })
.rotateLabels(-45)
;
chart.xScale(d3.time.scale()); //fixes misalignment of timescale with line graph
chart.yAxis
.axisLabel('Rank')
.tickFormat(d3.format('d'))
;
d3.select('#chart svg')
.datum(data)
.transition().duration(500)
.call(chart)
;
nv.utils.windowResize(chart.update);
return chart;
});
你可以在这里找到小提琴:http://jsfiddle.net/Marei/1azqmx1L/3/
谢谢!
答案 0 :(得分:2)
我认为(我之前只使用过d3,而不是nvd3)需要指定要使用tickValues()
显示的xValues列表。
因此,您需要做的第一件事就是获取所有xValues的列表(订单和/或重复项无关紧要):
//Map all xValues for each dataset to an array (tmp)
var tmp = data.map(function(e) {
return e.values.map(function(d) {
return d3.time.format('%Y%m%d').parse(d.date);
});
});
//And flatten out that array, so you have all your xValues in a 1D-array
var xValues = [].concat.apply([], tmp);
然后使用它来设置您要显示所有xValues:
chart.xAxis
.tickFormat(function(d) {return d3.time.format('%Y-%m-%d')(new Date(d)) })
.rotateLabels(-45)
.tickValues(xValues)
.showMaxMin(false)
;
showMaxMin
需要设置为false
,否则必须显示所有结束值
答案 1 :(得分:0)
我有x的字符串值, 因此,对于tickValues(),我创建了一个基于索引的数组,其项目长度为
axisLabel: graph.x_label,
tickValues: Array.from({ length: graph.values.length }, (x, i) => i),