0

I would like to make this dynamic js function, where the user can choose the values returned in the json request by constructing a querystring and then plotting the returned json using d3. Something like this:

function line_chart(canvas_element, request_url, x_axis, y_axis) {

    var svg = d3.select(canvas_element)
    //...other code to set tup the canvas

    // construct the url
    var url = request_url+"?x_axis="+x_axis+"&y_axis="+y_axis

    d3.json(url, function(error, data){
        if(error) return console.warn(error);

        // scale the range of data
        x.domain(d3.extent(data, function(d) {return d.x_axis;}));
        y.domain([0, d3.max(data, function(d) {return d.y_axis})]);

        // other code to draw the svg, axes etc..
   };
};

Now if I set x_axis="tomatoes" and y_axis="bananas" I get json data back like this:

[{"tomatoes": 1 , "bananas": 40}, {"tomatoes": 2 , "bananas": 30},
{"tomatoes": 3 , "bananas": 78}]

But my code that scales the range of data d.x_axis doesn't work because it's looking for a field in the json x_axis that doesn't exist. How can I write this so I can get the js to look for whatever field is specified as an input variable to the function?

1
  • Would help if you provided a working example, fiddle maybe ... Commented Jun 8, 2016 at 13:06

1 Answer 1

1

Just modify your accessor functions to be dynamic:

x.domain(d3.extent(data, function(d) {return d[x_axis];}));
y.domain([0, d3.max(data, function(d) {return d[y_axis];})]);

d[x_axis] would use the value of x_axis to find the property d.tomatoes.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that's what I was looking for. I'm still new to js so wasn't completely clear on the syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.