So I read in a csv file on Country GDP, and I filtered out unwanted columns and countries. Now I want to know how to extract the values from this array of objects and use them to create x and y axes for a multi-series line chart. Here is my code

    function country(element) {
    return element.CountryName == "Brazil" ||
            element.CountryName == "China" ||
            element.CountryName == "Russian Federation" ||
            element.CountryName == "United Kingdom" ||
            element.CountryName == "United States" ||
            element.CountryName == "Germany";
}
d3.csv("GDP.csv", function(d) {
    return {
        CountryName : d["Country Name"],
        Indicator : d["Indicator Name"],
        y2004 : d["2004"],
        y2005 : d["2005"],
        y2006 : d["2006"],
        y2007 : d["2007"],
        y2008 : d["2008"],
        y2009 : d["2009"],
        y2010 : d["2010"],
        y2011 : d["2011"],
        y2012 : d["2012"]
    };
},
    function(error, rows) {
    //document.write(rows);
    dataset = rows;
    var filtered = dataset.filter(country);
    console.log(filtered);

    //Code to create axes and map keys
});

Now I currently have a array of 6 objects, each object having values at the specifically named keys. Examples I've seen usually read in key values from the header line of the files, but how would I approach that attempt with this?

The X-axis is for the years 2004-2012, which are column names and key values. Y-axis is the range of those values at those years. The resulting 6 lines are for each country.

Example I'm trying to follow is http://bl.ocks.org/mbostock/3884955

Would I need to parse dates? I don't think so since I'm just working with year numbers and they are key values, not values of a key. Thanks.

有帮助吗?

解决方案

I would assemble my data so that you have 4 keys for each point:

{country:"Germany", indicator:"...",  year:2004, value:55}

rather than having keys for each year. Just post-process your csv call.

As you are doing that, determine the min/max years and the min/max values.

Next you build a year scale(x axis) using a domain of [minYear, maxYear]. Next build a value scale for the y-axis using a domain of [minValue, maxValue].

其他提示

D3 wants to consume arrays of objects with identical sets of keys. If you must, have pre-processing stage where you mogrify the data into something that looks like:

[
    { key: value, key2: value },
    { key: value, key2: value },
    { key: value, key2: value },
    { key: value, key2: value },
    { key: value, key2: value }
]

Otherwise you will be having a very terrible time with D3, as most of the functional programming features of the toolkit will not work at all for you.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top