简体   繁体   中英

How to call a D3 script as a function

Is it possible to call a D3 script as a function? Specifically to pass a data selector?

I have a simple donut chart that I use to display data for a month. I'd like to be able to recall that same D3 graphic and pass it different data for each month of the year, based on an onClick event. So that the chart would be redrawn in the same space.

I've seen other charts that have a radio selection that is triggered by onchange that runs a section of the D3 script again to redraw the graphic. But can I not just setup my D3 script as a function, and call it whenever I want to display different data?

I have also seen a chart here that calls the D3 function using (window.d3) , but it does not seem like the function definition of (function(d3){...} will allow for any variables to be passed. Or maybe I don't understand exactly how that is executing.

What is the easiest way to accomplish a reactive chart based on a click outside the svg?

I did a similar job where I had links and I could select one of the links to select the appropriate JSON to use for the plot. Below is the HTML snippet of interest -

<ul class="dropdown-menu" role="menu">
                    <li><a class="m" value="2014-02-19" href="#">2014-02-19</a></li>
                    <li><a class="m" value="2014-02-20" href="#">2014-02-20</a></li>
                    <li><a class="m" value="2014-02-21" href="#">2014-02-21</a></li>
                    <li><a class="m" value="2014-02-22" href="#">2014-02-22</a></li>
                    <li><a class="m" value="2014-02-23" href="#">2014-02-23</a></li>
                </ul>
...

This is the Javascript snippet doing the selection -

        //On click, update with new data            
        d3.selectAll(".m")
            .on("click", function() {
                var date = this.getAttribute("value");

                var str;
                if(date == "2014-02-19"){
                    str = "19.json";
                }else if(date == "2014-02-20"){
                    str = "20.json";
                }else if(date == "2014-02-21"){
                    str = "21.json";
                }else if(date == "2014-02-22"){
                    str = "22.json";
                }else{
                    str = "23.json";
                }

                d3.json(str,function(json){

                    dataset = json;
                    stack(dataset);
                    ...

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM