novus / nvd3

A reusable charting library written in d3.js
http://nvd3.org/
Other
7.22k stars 2.14k forks source link

How to use nvd3.js to create a scatter plot based on data from two dropdown lists (X- and Y- axis)? #366

Closed crabcanon closed 9 years ago

crabcanon commented 11 years ago

I have a csv dataset which has around 18 properties (columns) and each property contains over 3000 records(rows). For example:

A B C D (properties - 18 columns)

1 1 1 1 (records - over 3000 rows)

2 2 2 2

3 3 3 3

4 4 4 4

I would like to create two dropdown lists which correspond to the x- and y-axis in nvd3.js, so that users could select two properties and map them on the scatter plot.

For example:

here is my codes:

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>The Multi-Visualization</title>
    <link href="nvd3/src/nv.d3.css" rel="stylesheet" type="text/css">
    <style type="text/css">
        #g1{
            border: 2px solid black;
            width: 100%;
            height: 100%;
            float: left;
            -webkit-box-sizing:border-box;
            -moz-box-sizing:border-box;
            box-sizing:border-box;
        }
    </style>
<body>
    <script src="nvd3/lib/d3.v3.js"></script>
    <!--<script src="nvd3/lib/fisheye.js"></script>-->
    <script src="nvd3/nv.d3.js"></script>
    <script src="nvd3/src/tooltip.js"></script>
    <script src="nvd3/src/utils.js"></script>
    <script src="nvd3/src/models/legend.js"></script>
    <script src="nvd3/src/models/axis.js"></script>
    <script src="nvd3/src/models/distribution.js"></script>
    <script src="nvd3/src/models/scatter.js"></script>
    <script src="nvd3/src/models/scatterChart.js"></script>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script>
        var data=[
            {
                "key" : "NAME",
                "values" : []
            },
            {
                "key" : "STATE_NAME",
                "values" : []
            },
            {
                "key" : "MALES",
                "values" : []
            },//Population
            {
                "key" : "FEMALES",
                "values" : []
            },//Population
            {
                "key" : "Noins",
                "values" : []
            },// % of persons ages 18+ who do not have health plan or health insurance
            {
                "key" : "hosp",
                "values" : []
            },// hospitals per 1000 pop
            {
                "key" : "hosponc",
                "values" : []
            },// hospitals with oncology service per 1000 pop
            {
                "key" : "pcincome",
                "values" : []
            },// per capita income
            {
                "key" : "pctcoled",
                "values" : []
            },// % adults over 25 with 4+ years college education
            {
                "key" : "pctpoor",
                "values" : []
            },// % living below federal poverty line
            {
                "key" : "pctwhtcl",
                "values" : []
            },// adults employed in white collar jobs
            {
                "key" : "unemploy",
                "values" : []
            },// % unemployed
            {
                "key" : "RCALLAALA9395",
                "values" : []
            },// Age-Adjusted Rate of Colon Cancer Mortality, All Races, All Ages, Female+Male, 1993-1995
            {
                "key" : "RCALLAALA9698",
                "values" : []
            },// Age-Adjusted Rate of Colon Cancer Mortality, All Races, All Ages, Female+Male, 1996-1998
            {
                "key" : "RCALLAALA9901",
                "values" : []
            },// Age-Adjusted Rate of Colon Cancer Mortality, All Races, All Ages, Female+Male, 1999-2001
            {
                "key" : "RLALLAALA9395",
                "values" : []
            },// Age-Adjusted Rate of Lung Cancer Mortality, All Races, All Ages, Female+Male, 1993-1995
            {
                "key" : "RLALLAALA9698",
                "values" : []
            },// Age-Adjusted Rate of Lung Cancer Mortality, All Races, All Ages, Female+Male, 1996-1999
            {
                "key" : "RLALLAALA9901",
                "values" : []
            }// Age-Adjusted Rate of Lung Cancer Mortality, All Races, All Ages, Female+Male, 1999-2001

        ];

        d3.csv("USA_Cancer.csv", function(error,csv){
            if(error) return console.log("there was an error loading the csv:" + error);
            console.log("there are " + csv.length + " elements in my csv set");
            csv.sort(function(a,b){return a.length-b.length;});

            var dataset=["NAME","STATE_NAME","MALES","FEMALES","Noins","hosp","hosponc","pcincome", "pctcoled","pctpoor","pctwhtcl","unemploy","RCALLAALA9395","RCALLAALA9698","RCALLAALA9901","RLALLAALA9395","RLALLAALA9698","RLALLAALA9901"];
            for (var i=0; i < dataset.length; i++){
                data[i].values = csv.map(function(d){return [+d[dataset[i]] ]; });
            };

            d3.select("#drop1")
                .append("select")
                .attr("id","select1")
                .selectAll("option")
                .data(dataset)
                .enter()
                .append("option")
                .attr("value", function(d){return d;})
                .text(function(d){return d;});

            d3.select("#drop2")
                .append("select")
                .attr("id","select2")
                .selectAll("option")
                .data(dataset)
                .enter()
                .append("option")
                .attr("value", function(d){return d;})
                .text(function(d){return d;});
        });
        var  chart;
        nv.addGraph(function(){
            chart=nv.models.scatterChart()
                        .showDistX(true)
                        .showDistY(true)
                        .useVoronoi(true)
                        .color(d3.scale.category10().range())
                        .transitionDuration(300);
            chart.xAxis.tickFormat(d3.format('.01f'));
            chart.yAxis.tickFormat(d3.format('.01f'));
            chart.tooltipContent(function(key){
                return '<h3>' + key + '</h3>';
            });
            d3.select("#g1 svg")
                .datum(inputData(data))
                .call(chart);
            nv.utils.windowResize(chart.update);
            chart.dispatch.on('stateChange', function(e){('New State', JSON.stringify(e)); });
            return chart;
        });

        function inputData(datainput){
            var output={};
            d3.select('#select1')
                .on("change",function(){
                    key1 = this.selectedIndex;
                    for(i=0; i<datainput[key1].length; i++){
                        output["x"].values.push({
                            y:datainput[i].values
                        });
                    }
                });

            d3.select('#select2')
                .on("change",function(){
                    key2 = this.selectedIndex;
                    for(j=0; j<datainput[key2].length; j++){
                        output["y"].values.push({
                            y:datainput[j].values
                        });
                    }
                });
            return output;
        }
    </script>
    <div id="g1">
        <div id="drop1"></div>
        <div id="drop2"></div>
        <svg></svg>
    </div>
</body>

I personally think the problems are caused by the function inputData(), but I am not sure. Please help! I will appreciate that!

timelyportfolio commented 11 years ago

Not really an answer but maybe something to think about. Here is a similar example by @ramnathv using rCharts with angularjs to update the chart. Do you a gist or jsfiddle with the data or minimal data? I'll be happy to look at it if you do.

crabcanon commented 11 years ago

Hi @timelyportfolio, Thanks for your reply! you can download the data from this website http://www.geovista.psu.edu/ESTAT/. It's a pretty amazing visualization tool which is written by java. And all of the datasets are contained in the package.

timelyportfolio commented 11 years ago

I tried to change just enough to get a working chart that you could then refine and perfect. Here it is as a site and as a repo.

Let me know if it helps. Please note this is not perfect and should not be considered best practice.

crabcanon commented 11 years ago

Hi @timelyportfolio, WOW! Pretty helpful! I will check it carefully, many thanks!