nvd3折线图,x轴上有字符串值

时间:2014-05-18 22:43:20

标签: d3.js nvd3.js

我是nvd3排行榜的新手。我需要一个折线图,x轴上有字符串值 图表应该像这样Bar Chart,但我需要一条线,而不是条

我的结果如下Line Chart 这些值都映射到x = 0

我的代码

nv.addGraph(function() {
    var chart = nv.models.lineChart()
    .useInteractiveGuideline(true) 
    .transitionDuration(350)
    .x(function(d) { return d.x}) 
    .y(function(d) { return d.y}) 
    .showLegend(true)
    .showYAxis(true)
    .showXAxis(true);

    chart.xAxis.tickValues(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]);

    d3.select(element + ' svg')
    .datum(data) 
    .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
});

和我的数据

[{"color":"#a215af","key":"products","values":[
    {"label":"Monday","y":0,"x":"Monday"},
    {"label":"Tuesday","y":0,"x":"Tuesday"},
    {"label":"Wednesday","y":1,"x":"Wednesday"},
    {"label":"Thursday","y":6,"x":"Thursday"},
    {"label":"Friday","y":2,"x":"Friday"},
    {"label":"Saturday","y":0,"x":"Saturday"},
    {"label":"Sunday","y":13,"x":"Sunday"}]}] 

我尝试了很多,但不知道该怎么做。

任何帮助或建议都会很棒


解决方案 像dcclassics提到的我采用数字值而不是字符串 然后使用tickValues和tickFormat:

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

chart.xAxis.tickValues([0, 1, 2, 3, 4, 5, 6])
.tickFormat(function(d){
    return days[d]
});

2 个答案:

答案 0 :(得分:17)

像提到的dcclassics我使用数字值而不是字符串,然后使用tickValues和tickFormat:

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

chart.xAxis.tickValues([0, 1, 2, 3, 4, 5, 6])
.tickFormat(function(d){
    return days[d]
});

这个解决方案对我有用

答案 1 :(得分:5)

工作解决方案:

var data = [{"color":"#a215af","key":"products","values":[
    {"y":0,"x":0},
    {"y":0,"x":1},
    {"y":1,"x":2},
    {"y":6,"x":3},
    {"y":2,"x":4},
    {"y":0,"x":5},
    {"y":13,"x":6}]}] 

nv.addGraph(function() {
  var chart = nv.models.lineChart()
    .useInteractiveGuideline(true) 
    .transitionDuration(350)
    .x(function(d) { return d.x}) 
    .y(function(d) { return d.y}) 
    .showLegend(true)
    .showYAxis(true)
    .showXAxis(true);

  var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

  chart.xAxis
    .tickValues([0, 1, 2, 3, 4, 5, 6])
    .tickFormat(function(d){
      return days[d]
    });

  d3.select(element + ' svg')
    .datum(data) 
    .call(chart);

  nv.utils.windowResize(chart.update);

  return chart;
});