D3折线图没有正确的X&使用标签

时间:2016-11-23 06:18:59

标签: javascript d3.js svg charts linechart

在下面的折线图中,尽管图表已正确绘制,但带有标签的x和y轴未正确绘制。有人可以帮我解决这个问题吗?

SNIPPET:

<html>

<head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.12/angular.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script>

</head> 

<body ng-app="myApp" ng-controller="myCtrl"> 

  <svg width="500" height="300"></svg>

<script>
//module declaration 
var app = angular.module('myApp',[]);

//Controller declaration
app.controller('myCtrl', function($scope){

    var data = [
            {x: "2016-01-10", y: "10.02"},
            {x: "2016-02-10", y: "15.02"},
            {x: "2016-03-10", y: "50.02"},
            {x: "2016-04-10", y: "40.02"},
            {x: "2016-05-10", y: "10.02"}
        ];

    var parseTime = d3.timeParse("%Y-%m-%d");

    var xScale = d3.scaleTime().range([0,500]).domain(d3.extent(data, function(d){ return parseTime(d.x)}));

    var yScale = d3.scaleLinear().range([300,0]).domain([0,50]);


    //Plotting domain on x and y axis 
    var xAxis = d3.scaleBand().rangeRound([0, 500]).padding(0.6); 
    var yAxis = d3.scaleLinear().rangeRound([300, 0]); 
    xAxis.domain(data.map(function(d) { return d.letter; }));
    yAxis.domain([0, d3.max(data, function(d) { return d.frequency; })]);

    //Final printing of elements on svg 

    //Plortting of x-axis 
    d3.select("svg")
        .append("g")
        .attr("transform", "translate(0," + 300 + ")")
        .call(d3.axisBottom(xAxis)); 

    //Plotting of y-axis 
    d3.select("svg")
        .append("g")
        .call(d3.axisLeft(yAxis).ticks(10, "%")); 


        //the line function for path 
    var lineFunction = d3.line()
        .x(function(d) {return xScale(parseTime(d.x)); })
        .y(function(d) { return yScale(d.y); })
        .curve(d3.curveLinear);

    //Main svg container
    var mySVG = d3.select("svg");

    //defining the lines
    var path = mySVG.append("path");

    //plotting lines
    path
        .attr("d", lineFunction(data))
        .attr("stroke",function() { return "hsl(" + Math.random() * 360 + ",100%,50%)"; })
        .attr("stroke-width", 2)
        .attr("fill", "none");

});
</script> 

</body> 

</html> 

结果:

enter image description here

的问题:

  
      
  1. X轴未来
  2.   
  3. 缺少X轴上的标签
  4.   
  5. 缺少Y轴上的Lables
  6.   

请帮助我正确地获取图表。

1 个答案:

答案 0 :(得分:1)

关于y轴:您没有从原点位置进行平移。它应该是:

 d3.select("svg")
    .append("g")
    .attr("transform", "translate(30, 0)")//30 here is just an example
    .call(d3.axisLeft(yAxis).ticks(10, "%")); 

关于x轴:你将它一直翻译到高度。它应该小于:

  d3.select("svg")
    .append("g")
    .attr("transform", "translate(0," + (height - 30) + ")")//30 is just an example
    .call(d3.axisBottom(xAxis)); 

简而言之:正确设置边距并根据边距平移轴。

PS:在您的数据中不会显示任何内容,因为您的数据中没有letterfrequency