d3 javascript在同一页面上显示多个图表

时间:2017-12-11 20:04:47

标签: javascript html d3.js

我正在尝试显示两个图表,一个条形图和一条线,一个是同一个简单的html页面。当在不同的html文件中显示时,两个图表都能正确显示,但是当我将它们放在一起时,它们会中断。

根据creating multiple divs上这个答案的建议,我创建了两个div对象来保存我的图形并以不同的方式命名它们。

<!--Create svg elements to hold d3 object -->
    <div id="Chart1"></div>

    <div id="Chart2"></div> 

附加到第一个div

// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#Chart2").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

附加到第二个div

var BarChart = d3.select("#Chart1").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top     + ")");

但是它仅显示折线图和折线图的轴。图表的行未显示,我在控制台上看不到任何输出以指示错误。 Program Output

完整的代码在这里

    <html>
        <body>

        <!--Create svg elements to hold d3 object -->
        <div id="Chart1"></div>

        <div id="Chart2"></div> 

<script>

            // set the dimensions and margins of the graph
            var margin = {top: 50, right: 20, bottom: 80, left: 120},
                width = 960 - margin.left - margin.right,
                height = 900 - margin.top - margin.bottom;

            // parse the date / time
            var parseTime = d3.timeParse("%Y");

            // set the ranges
            var x = d3.scaleTime().range([0, width]);
            var y = d3.scaleLinear().range([height, 0]);

            // define the line
            var valueline = d3.line()
                .x(function(d) { return x(d.year); })
                .y(function(d) { return y(d.sum); });

            // append the svg obgect to the body of the page
            // appends a 'group' element to 'svg'
            // moves the 'group' element to the top left margin
            var svg = d3.select("#Chart2").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform",
                      "translate(" + margin.left + "," + margin.top + ")");

            // Get the data
            d3.csv("data/YearContributionSum.csv", function(error, data2) {
                if (error) throw error;

                // format the data
                data2.forEach(function(d) {
                    d.year = parseTime(d.year);
                    d.sum = +d.sum;
                    });

                // Scale the range of the data
                x.domain(d3.extent(data2, function(d) { return d.year; }));
                y.domain([0, d3.max(data2, function(d) { return d.sum; })]);

                // Add the valueline path.
                svg.append("path")
                  .data([data2])
                  .attr("class", "line")
                  .attr("d", valueline);

                // Add the X Axis
                svg.append("g")
                  .attr("transform", "translate(0," + height + ")")
                  .call(d3.axisBottom(x));


                // text label for the x axis
                svg.append("text")             
                  .attr("transform",
                        "translate(" + (width/2) + " ," + 
                                       (height + margin.top + 20) + ")")
                  .style("text-anchor", "middle")
                  .text("Year");    

                // Add the Y Axis
                svg.append("g")
                  .call(d3.axisLeft(y));

                  // text label for the y axis
                svg.append("text")
                  .attr("transform", "rotate(-90)")
                  .attr("y", 0 - margin.left)
                  .attr("x",0 - (height / 2))
                  .attr("dy", "1em")
                  .style("text-anchor", "middle")
                  .text("Sum of Contributions");     

            });

        </script>
        <script>

            var margin = {top: 20, right: 30, bottom: 100, left: 80},
                width = 1500 - margin.left - margin.right,
                height = 800 - margin.top - margin.bottom;

            var x = d3.scaleBand()
                .rangeRound([0, width], .1);
            var y = d3.scaleLinear()
                .range([height, 0]);

            var xAxis = d3.axisBottom(x);
            var yAxis = d3.axisLeft(y);

            var BarChart = d3.select("#Chart1").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            d3.csv("data/PurposeContributionSum.csv", type, function(error, data) {
              if (error) throw error;
                data.sort(function(a, b){ return b.sum - a.sum;});
                x.domain(data.map(function(d) { return d.purpose; }));
                y.domain([0, d3.max(data, function(d) { return d.sum; })]);

                BarChart.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis)
                    .selectAll("text")
                    .attr("y", 0)
                    .attr("x", 9)
                    .attr("dy", ".35em")
                    .attr("transform", "rotate(90)")
                    .style("text-anchor", "start");

                BarChart.append("g")
                    .attr("class", "y axis")
                    .call(yAxis);

                BarChart.selectAll(".bar")
                    .data(data)
                    .enter().append("rect")
                    .attr("class", "bar")
                    .attr("x", function(d) { return x(d.purpose); })
                    .attr("y", function(d) { return y(d.sum); })
                    .attr("height", function(d) { return height - y(d.sum); })
                    .attr("width", x.bandwidth());
            });

            function type(d) {
                d.sum = +d.sum; // coerce to number
                return d;
            }

        </script>
    </body>
<\html>

1 个答案:

答案 0 :(得分:0)

折线图在渲染时可能会遇到一些问题,如果折线图的输入正确,则代码似乎正常工作,这里是working JSbin

const contributionSum = [ // Had to mock this
    { year: '1990', sum: 1000 }, 
    { year: '1991', sum: 1090 },
    { year: '1992', sum: 900 },
    { year: '1993', sum: 1300 },
    { year: '1994', sum: 1250 },
    { year: '1995', sum: 1150 }];
// Format data
const formatContributions = contributionSum.map(v => {
    return {
        year: parseTime(v.year),
        sum: +v.sum
    }
});
// Scale the range of the data
x.domain(d3.extent(formatContributions, d => d.year));
y.domain([0, d3.max(formatContributions, d => d.sum)]);

我认为问题来自你提供给折线图的输入,我还必须创建一些额外的变量来保持条形图渲染的顺序:

var xBar = d3.scaleBand()
    .rangeRound([0, width], .1);
var yBar = d3.scaleLinear()
    .range([height, 0]);

var xBarAxis = d3.axisBottom(xBar);
var yBarAxis = d3.axisLeft(yBar);