0
votes

I'm trying to create a line graph using d3.js with this data structure:


    var dataset1 = [ 
            {"video_name": "Apples", "video_views": 100},
            {"video_name": "Oranges", "video_views": 35},
            {"video_name": "Grapes", "video_views": 20},
            {"video_name": "Avocados", "video_views": 85},
            {"video_name": "Tomatoes", "video_views": 60}
        ]

The index number of the object is the x-value and the "video_views" is the y-value.

The problem: It is appending the svg canvas, and the "g" element just fine, but the x and y values for each point in the graph are not being detected, so nothing is showing up.


        // Scale values
    var Line_xScale = d3.scale.linear()
        .domain([0, 100])
        .range([0, Line_Graph_Width]);

    var Line_yScale = d3.scale.linear()
        .domain([0, 100])
        .range([0, Line_Graph_Height]);


    // This is where I suspect the problem is. //

    // SVG path equal to line
    var Path_Var = d3.svg.line()
        .x(function(d, i) {
            return i * 10;
        })
        .y(function(d) {
            return Line_yScale(d.video_views);
        });

    // Connect Element with Data
    group.selectAll('path')
        .data(dataset1)
        .enter()
        .append('path')
            .attr('d', Path_Var) 
            .attr('fill', 'none')
            .attr('stroke', '#fff')
            .attr('stroke-width', 2);

Any help is appreciated. Thanks for reading.

2
just changed to .x(function... return i*10; and still no luckdmr07
stroke is white, but background is blue.dmr07

2 Answers

0
votes

One possible solution:

The index number of the object is the x-value...: domain of x scale is changed to array of input indexes using d3.range():

// Scale values
var Line_xScale = d3.scale.linear()
    .domain(d3.range(dataset1.length))
    .range([0, Line_Graph_Width]);

... and the "video_views" is the y-value.: range is changed so greater values are at the top:

var Line_yScale = d3.scale.linear()
    .domain([0, 100])
    .range([Line_Graph_Height, 0]);

x value of line is changed to calculate width of one point:

var Path_Var = d3.svg.line()
    .x(function(d, i) {
        return i * Line_Graph_Width / dataset1.length;
    })
    .y(function(d) {
        return Line_yScale(d.video_views);
    });

and line is appended using:

group.append('path')
        .attr('d', Path_Var(dataset1)) 
        .attr('fill', 'none')
        .attr('stroke', '#000')
        .attr('stroke-width', 2);

stroke of #fff is white so you'd see nothing even if everything is right.

See example at jsbin.

Using group.selectAll('path').data(dataset1).enter().append('path') you would add not just one path but dataset1.length path elements.

0
votes

You define xScale to be [ 0 - 100 ] but values are [ 0 - 400 ] and out of SVG view, as set in

.x(function(d, i) {
    return i * 100;
})

Try set range of xScale from 0 to 400