如何修复“ D3JS上的折线图不显示”

时间:2019-07-18 11:28:58

标签: javascript d3.js

我有d3js项目,我使d3js文件中的全局js可重用,但折线图未显示。 情况是该行无法显示,但是所有func正常运行,所有变量正常运行。

我的D3JS代码

/*Global d3 Line */
function jLine() {

		var margin = {top: 30, right: 10, bottom: 60, left: 60},
		    width = 650 - margin.left - margin.right,
		    height = 450 - margin.top - margin.bottom,
		    innerWidth = width - margin.left - margin.right,
		    innerHeight = height - margin.top - margin.bottom;

			// Parse month variable
			var parseMonth = d3.timeParse("%b");
			var formatMonth = d3.timeFormat("%b");
			var formatDatas = d3.timeFormat("%B");

	function chart(selection){
		selection.each(function (data){
			// Format data
            data.forEach(function(d) {
	            d.Month = parseMonth(d.Month);
	            d.Datas = +d.Datas;
            });
			
			// Select SVG element
			var svg = d3.select(this).selectAll("svg").data([data]);
			var svgEnter = svg.enter().append("svg")
				.style("width", width + margin.left + margin.right + "px")
    			.style("height", height + margin.top + margin.bottom + "px")
    			.attr("width", width + margin.left + margin.right)
    			.attr("height", height + margin.top + margin.bottom);
			var gEnter = svgEnter.append("g");


			svg.merge(svgEnter).attr("width", width)
				.attr("height",height);

			var g = svg.merge(svgEnter).select("g")
				.attr("transform","translate(" + margin.left + "," + margin.top + ")")
				.attr("class", "svg");

			// Set ranges
			var x = d3.scaleTime()
			    .domain([parseMonth("Jan"),parseMonth("Dec")])
			    .range([0, innerWidth]);
			var y = d3.scaleLinear()
			    .range([innerHeight, 0]);

			
			//set value to console log
			var totalData = d3.sum(data.map(function(d){return d.Datas}));
			var AvrData = d3.mean(data.map(function(d){return d.Datas}));

			var console = {};
			var total = document.getElementById("total");
			var avr = document.getElementById("avr");

			console.log = function(text) {
			    var element = document.createElement("strong");
			    var txt = document.createTextNode(text);

			    element.appendChild(txt);
			    total.appendChild(element);
			}

			console.log1 = function(text) {
			    var element = document.createElement("strong");
			    var txt = document.createTextNode(text);

			    element.appendChild(txt);
			    avr.appendChild(element);
			}

			// Define line
			var valueLine = d3.line()
			    .x(function(d) { return x(d.Month); })
			    .y(function(d) { return y(+d.Datas); });

			// Scale range of data
			x.domain(d3.extent(data, function(d) { return d.Month; }));
			y.domain([0, d3.max(data, function(d) { return d.Datas; })]);
			
			// Set up x axis
			var xaxis = g.append("g")
			   .attr("class","x axis")
			   .attr("transform", "translate(0," + innerHeight + ")")
			    .style("color","#000")
			    .call(d3.axisBottom(x)
			      .ticks(d3.timeMonth)
			      .tickSize(0, 0)
			      .tickFormat(d3.timeFormat("%b"))
			      .tickSizeInner(0)
			      .tickPadding(10));

		  	// Set up y axis
			var yaxis = g.append("g")
			   .attr("class","y axis")
			    .style("color","#000")
			    .call(d3.axisLeft(y)
			      .ticks(10)
			      .tickSizeInner(0)
			      .tickPadding(5)
			      .tickSize(5, 5));
		  
		  	// Start Style Chart
			// Define div for tooltip
			var div = d3.select("this")
			    .append("div") 
			    .attr("class", "tooltip")       
			    .style("opacity", 0);
 		  	// function grid Y Axis
			function grid_y() {   
			    return d3.axisLeft(y)
			    .ticks(15)
			}

			// Function Trasnsition Stoke
			function transition(path) {
			    path.transition()
			    .duration(2000)
			    .attrTween("stroke-dasharray", tweenDash);
			}

			// Function Transition Dash
			function tweenDash() {
			    var l = this.getTotalLength(),
			        i = d3.interpolateString("0," + l, l + "," + l);
			    return function (t) { return i(t); };
			}

			// add the Y gridlines
			g.append("g")     
			    .attr("class", "grid")
			    .call(grid_y()
			      .tickSize(-innerWidth)
			      .tickFormat("")
			      )

			// add tittle chart
			g.append("text")
			    .attr("dx", (width / 2))             
			    .attr("dy", 0 - (margin.top / 3))
			    .attr("text-anchor", "middle")  
			    .style("font-size", "16px") 
			    .style("font-weight","bold")
			    .text("Grafik Bulanan");

			// add Label X
			g.append("text")
			    .attr("class", "x label")
			    .attr("text-anchor", "end")
			    .attr("dx", width - 250)
			    .attr("dy", height + 45)
			    .style("font-size","13px")
			    .style("font-weight","bold")
			    .text("Bulan");

			// add Label Y
			g.append("text")
			    .attr("class", "y label")
			    .attr("text-anchor", "end")
			    .attr("dx", - 75)
			    .attr("dy", - 40)
			    .attr("transform", "rotate(-90)")
			    .style("font-size","13px")
			    .style("font-weight","bold")
			    .text("Rupiah [x1.000.000]");
			// End Style Chart
			  
			// Draw line chart
			var path = g.append("path")
				.datum([function(d){return d;}])
			    .attr("class", "line")
			    .attr("d", valueLine)
			    .call(transition);
			  
			// Add Tooltip Style
			g.selectAll("dot")
			    .data(function(d){return d;})
			    .enter()
			    .append("circle")
			    .attr("class","dots")
			    .attr("cx", function(d) { return x(d.Month); })
			    .attr("cy", function(d) { return y(d.Datas); })
			    .attr("r", 5)
			    .on("mouseover", function(d) {
			         div.transition()
			         .duration(200)
			         .style("opacity", 1);
			         div.html("<b>"+ formatDatas(d.Month) +"</b>"+ "<br/>" + d.Datas)
			         .style("left", (d3.event.pageX - 270) + "px")
			         .style("top", (d3.event.pageY - 200) + "px")
			         d3.select(this)
			         .style("fill","red");
			    })
			    .on("mouseout", function(d) {
			         div.transition()
			         .duration(500)
			         .style("opacity", 0);
		             d3.select(this)
			         .style("fill","#2196f3");
			     });

			// Console Log Data to HTML Tag
			hasiltotal = totalData.toFixed(0.2);
			hasilavr = AvrData.toFixed(2);
			console.log(hasiltotal)
			console.log1(hasilavr)
		});
	}
	return chart;
}
.card-header:first-child {
  border-radius: calc(.35rem - 1px) calc(.35rem - 1px) 0 0;
}

.card-header {
  padding: .75rem 1.25rem;
  margin-bottom: 0;
  background-color: #f8f9fc;
  border-bottom: 1px solid #e3e6f0;
}

.text-primary {
  color: #4e73df!important;
}

.font-weight-bold {
  font-weight: 700!important;
}

.dropdown-item:focus, .dropdown-item:hover {
  color: #f8f9fc;
  text-decoration: none;
  background-color: #4e73df;
}

.card-body {
  flex: 1 1 auto;
  padding: 0px;
}


/*  Line Chart Style */
.line {
  fill: none;
  stroke: #2196f3 ;
  stroke-width: 3px;
}

.grid line {
  stroke: #000;
  stroke-opacity: 0.25;
  shape-rendering: crispEdges;
}

.grd line {
  stroke: #000;
  stroke-opacity: 0.25;
  shape-rendering: crispEdges;
}

.grid path {
  stroke-width: 0;
}

div.tooltip {
  position: absolute;
  text-align: center;
  color: #fff;
  width: 80px;
  font-family: "Verdana";
  font-size: 0.95em;
  background-color: #232F34;
  pointer-events: none;
}

.dots {
  stroke: none;
  fill: #2196f3 ;

}
.dots:hover {
  stroke-width: 2px;
  stroke: #d32f2f;
}


.bar {
  fill: #2196f3 ;
}

.bar:hover {
  fill: #E8743B;
}

.bara:hover {
  fill: #d32f2f;
}

/*Pie Chart Style */
.pie {
  margin: 30px;
}

svg {
  float: left;
}

.legend {
  float: left;
  font-family: "Verdana";
  font-size: .7em;
}

.pie text {
  font-family: "Verdana";
}

.pie .name-text {
  font-size: .8em;
}

.pie .value-text {
  font-size: 3em;
}

label {
  margin-right: 1rem;
}
fieldset {
  border: none;
}
legend {
  font-weight: bold;
}
<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="assets/css/jStyle.css">
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script src="csm-d3API.js"></script>
</head>

<body>
                                <div style="padding: 10px;">
                                    <div style="text-align: right;font-size: 12px;padding-right: 10px;">
                                        <div style="padding: 5px;padding-top: 0px;"><span>Total :&nbsp;</span>
                                            
                                            <span id="total"></span>

                                            <span>&nbsp;|&nbsp;</span><span>Avg. :&nbsp;</span>

                                            <span id="avr"></span>
                                        </div>

                                        <div id="line" class="svg-container" style="height: 375px;"></div>
                                        <!--START SCRIPT USABLE-->
                                        <script>
                                            var lineChart = jLine();
                                            // Parse month variable
                                            var parseMonth = d3.timeParse("%b");

                                            d3.csv("data/line_data.csv")
                                                .then(function(data){
                                                    d3.select("#line")
                                                    .datum(data)
                                                    .call(lineChart);
                                                })

                                            .catch(function(error){
                                                if (error) throw error; 
                                            });
                                        </script>
                                    </div>
                                </div>
       
   
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.js"></script>
</body>

</html>

**

/*Global d3 Line */
function jLine() {
        var margin = {top: 30, right: 10, bottom: 60, left: 60},
            width = 650 - margin.left - margin.right,
            ...
            innerHeight = height - margin.top - margin.bottom;

            // Parse month variable
            var parseMonth = d3.timeParse("%b");
            ...
            var formatDatas = d3.timeFormat("%B");

    function chart(selection){
        selection.each(function (data){
            // Format data
            data.forEach(function(d) {
                d.Month = parseMonth(d.Month);
                d.Datas = +d.Datas;
            });

            // Select SVG element
            var svg = d3.select(this).selectAll("svg").data([data]);
            var svgEnter = svg.enter().append("svg")
                ...
                .attr("height", height + margin.top + margin.bottom);
            var gEnter = svgEnter.append("g");


            svg.merge(svgEnter).attr("width", width)
                .attr("height",height);

            var g = svg.merge(svgEnter).select("g")
                .attr("transform","translate(" + margin.left + "," + margin.top + ")")
                .attr("class", "svg");

            // Set ranges
            var x = d3.scaleTime()
                .domain([parseMonth("Jan"),parseMonth("Dec")])
                .range([0, innerWidth]);
            var y = d3.scaleLinear()
                .range([innerHeight, 0]);

            // Define line
            var valueLine = d3.line()
                .x(function(d) { return x(d.Month); })
                .y(function(d) { return y(+d.Datas); });

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

            // Set up x axis
            var xaxis = g.append("g")
               .attr("class","x axis")
               .attr("transform", "translate(0," + innerHeight + ")")
                .style("color","#000")
                .call(d3.axisBottom(x)
                  .ticks(d3.timeMonth)
                  .tickSize(0, 0)
                  .tickFormat(d3.timeFormat("%b"))
                  .tickSizeInner(0)
                  .tickPadding(10));

            // Set up y axis
            var yaxis = g.append("g")
               .attr("class","y axis")
                .style("color","#000")
                .call(d3.axisLeft(y)
                  .ticks(10)
                  .tickSizeInner(0)
                  .tickPadding(5)
                  .tickSize(5, 5));

            // Start Style Chart
            // Define div for tooltip
            var div = d3.select("this")
                .append("div") 
                .attr("class", "tooltip")       
                .style("opacity", 0);
            // function grid Y Axis
            function grid_y() {   
                return d3.axisLeft(y)
                .ticks(15)
            }

            // Function Trasnsition Stoke
            function transition(path) {
                path.transition()
                .duration(2000)
                .attrTween("stroke-dasharray", tweenDash);
            }

            // Function Transition Dash
            function tweenDash() {
                var l = this.getTotalLength(),
                    i = d3.interpolateString("0," + l, l + "," + l);
                return function (t) { return i(t); };
            }

            // add the Y gridlines
            g.append("g")     
                .attr("class", "grid")
                .call(grid_y()
                  .tickSize(-innerWidth)
                  .tickFormat("")
                  )

            // add tittle chart
            g.append("text")
                .attr("dx", (width / 2))             
                .attr("dy", 0 - (margin.top / 3))
                .attr("text-anchor", "middle")  
                .style("font-size", "16px") 
                .style("font-weight","bold")
                .text("Grafik Bulanan");

            // add Label X
            g.append("text")
                .attr("class", "x label")
                .attr("text-anchor", "end")
                .attr("dx", width - 250)
                .attr("dy", height + 45)
                .style("font-size","13px")
                .style("font-weight","bold")
                .text("Bulan");

            // add Label Y
            g.append("text")
                .attr("class", "y label")
                .attr("text-anchor", "end")
                .attr("dx", - 75)
                .attr("dy", - 40)
                .attr("transform", "rotate(-90)")
                .style("font-size","13px")
                .style("font-weight","bold")
                .text("Rupiah [x1.000.000]");
            // End Style Chart

            // Draw line chart
            var path = g.append("path")
                .datum([function(d){return d;}])
                .attr("class", "line")
                .attr("d", valueLine)
                .call(transition);

            // Add Tooltip Style
            g.selectAll("dot")
                .data(function(d){return d;})
                .enter()
                .append("circle")
                .attr("class","dots")
                .attr("cx", function(d) { return x(d.Month); })
                .attr("cy", function(d) { return y(d.Datas); })
                .attr("r", 5)
                .on("mouseover", function(d) {
...})
                .on("mouseout", function(d) {
...});

            // Console Log Data to HTML Tag
            console.log(chart)
        });
    }
    return chart;
}

这是我的html代码:

    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script src="d3/csm-d3API.js"></script>
......
<div id="line" class="svg-container" style="height: 375px;"></div>
                                        <!--START SCRIPT USABLE-->
                                        <script>
                                            var lineChart = jLine();
                                            // Parse month variable
                                            var parseMonth = d3.timeParse("%b");

                                            d3.csv("data/line_data.csv")
                                                .then(function(data){
                                                    d3.select("#line")
                                                    .datum(data)
                                                    .call(lineChart);
                                                })

                                            .catch(function(error){
                                                if (error) throw error; 
                                            });
                                        </script>

我的浏览器没有显示来自consol日志的消息,但该行未显示。

请帮助:(

0 个答案:

没有答案