javascript - 如何从json中获取输入来绘制图形

标签 javascript html css json graph

<html>
<head>
<title>JS Charts</title>
</head>
<script type="text/javascript">
  var Apple = [];
  var Samsung = [];
  var Nokia = [];
  function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'https://api.myjson.com/bins/1igag', true);
    xobj.onreadystatechange = function() {
        if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
        }
    }
    xobj.send(null);
}
loadJSON(function(response) {
  var response;
  var field=JSON.parse(response);
  for (var i = 0; i < field.length; i++) {
        Apple.push(field[i].xxx);
        Samsung.push((field[i].xxx)+10);
        Nokia.push((field[i].xxx)-30);
      }
    sections = 12;
	Val_max = 130;
	Val_min = -40;
	var stepSize = 10;
	var columnSize = 50;
	var rowSize = 50;
	var margin = 10;
	var xAxis = [" ", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 
	canvas = document.getElementById("canvas");
	context = canvas.getContext("2d");
	context.fillStyle = "#0099ff"
	context.font = "20 pt Verdana"
	yScale = (canvas.height - columnSize - margin) / (Val_max - Val_min);
	xScale = (canvas.width - rowSize) / sections;
	context.strokeStyle="#009933"; // color of grid lines
	context.beginPath();
    // print Parameters on X axis, and grid lines on the graph
	for (i=1;i<=sections;i++) {
		var x = i * xScale;
		context.fillText(xAxis[i], x,columnSize - margin);
		context.moveTo(x, columnSize);
		context.lineTo(x, canvas.height - margin);
	}
    // print row header and draw horizontal grid lines
	var count =  0;
	for (scale=Val_max;scale>=Val_min;scale = scale - stepSize) {
		var y = columnSize + (yScale * count * stepSize); 
		context.fillText(scale, margin,y + margin);
		context.moveTo(rowSize,y)
		context.lineTo(canvas.width,y)
		count++;
	}
	context.stroke();
	context.translate(rowSize,canvas.height + Val_min * yScale);
	context.scale(1,-1 * yScale);
		// Color of each dataplot items
	context.strokeStyle="#FF0066";
	plotData(Apple);
	context.strokeStyle="#9933FF";
	plotData(Samsung);
  context.strokeStyle="#000";
	plotData(Nokia);
function plotData(dataSet) {
	context.beginPath();
	context.moveTo(0, dataSet[0]);
	for (i=1;i<sections;i++) {
		context.lineTo(i * xScale, dataSet[i]);
	}
	context.stroke();
}
    });
</script>
<body>
<div align="center">
<h2>Monthly Profits of Companies(in million $)</h2>
<canvas id="canvas" height="400" width="650">
</canvas>
<br>
	<!--Legends for Dataplot -->
<span style="color:#FF0066"> Apple </span>  
<span style="color:#9933FF"> Samsung</span>  
<span style="color:#000"> Nokia </span>
</div>
</body>
</html>

嗨。我需要绘制一个线性图。在这里,我已经采取了样本。现在我需要从 json 文件中获取 x 和 y 的数据。我该怎么做。我不允许使用任何库或 API,只允许使用 HTML、CSS 和 Javascript。谁能告诉我。我的 json 数据看起来像

[{"aa":{  
   "total_visits":"925",
   "2017-07-29":{  
      "visits":38,
      "leads":0
   },

   "total_leads":13
},
"bb":{  
   "total_visits":"144",
   "2017-07-29":{  
      "visits":1,
      "leads":0
   },
          "total_leads":1
},
"cc":{  
   "last_recorded":"2017-07-29",
   "total_visits":"1386",
   "2017-07-29":{  
      "visits":41,
      "leads":0
   },

   "total_leads":12
},
"dd":{  
   "total_visits":"2364",
   "2017-07-29":{  
      "visits":55,
      "leads":2.1
   },

   "total_leads":59
},
"ee":{  

   "2017-07-29":{  
      "visits":44,
      "leads":0
   },

   "total_leads":37
},
"ff":{  

   "total_leads":2
},
"gg":{  

   "total_leads":1
},
"hh":{  

   "total_visits":"115",

   "2017-07-29":{  

      "visits":2,
      "leads":0
   },
   "package_id":"2",
   "total_leads":3
},
"ii":{  

   "total_visits":"2213",

   "2017-07-29":{  

      "visits":94,
      "leads":0
   },

   "total_leads":87
}
}]

我需要获取 total_visits(or)visits(x-axis) 和 total_leads(or)leads(y-axis) 并绘制图表。提前致谢。

最佳答案

试试这个代码

编辑了用于绘制 x、y 轴值的 plotData 函数

function plotData(xVisits,yLeads) {
    context.beginPath();
    context.moveTo(xVisits, yLeads);
    for (i=1;i<xVisits.length;i++) {
        context.lineTo(xVisits[i], yLeads[i]);
    }
    context.stroke();
}

<script type="text/javascript">
  var visits = [];
  var leads = [];
  function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'https://api.myjson.com/bins/17x8l1', true);
    xobj.onreadystatechange = function() {
        if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
        }
    }
    xobj.send(null);
}
loadJSON(function(response) {
  var response;
  var field=JSON.parse(response);
  for (var i = 0; i < field.length; i++) {
  var $this=field[i];
       for (var key in $this) {
          if ($this.hasOwnProperty(key)) {
            var val = $this[key];
            visits.push(val.total_visits);
            leads.push(val.total_leads);
          }
      }
      }
    sections = 12;
	Val_max = 130;
	Val_min = -40;
	var stepSize = 10;
	var columnSize = 50;
	var rowSize = 50;
	var margin = 10;
	var xAxis = [" ", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 
	canvas = document.getElementById("canvas");
	context = canvas.getContext("2d");
	context.fillStyle = "#0099ff"
	context.font = "20 pt Verdana"
	yScale = (canvas.height - columnSize - margin) / (Val_max - Val_min);
	xScale = (canvas.width - rowSize) / sections;
	context.strokeStyle="#009933"; // color of grid lines
	context.beginPath();
    // print Parameters on X axis, and grid lines on the graph
	for (i=1;i<=sections;i++) {
		var x = i * xScale;
		context.fillText(xAxis[i], x,columnSize - margin);
		context.moveTo(x, columnSize);
		context.lineTo(x, canvas.height - margin);
	}
    // print row header and draw horizontal grid lines
	var count =  0;
	for (scale=Val_max;scale>=Val_min;scale = scale - stepSize) {
		var y = columnSize + (yScale * count * stepSize); 
		context.fillText(scale, margin,y + margin);
		context.moveTo(rowSize,y)
		context.lineTo(canvas.width,y)
		count++;
	}
	context.stroke();
	context.translate(rowSize,canvas.height + Val_min * yScale);
	context.scale(1,-1 * yScale);
		// Color of each dataplot items
	context.strokeStyle="#FF0066";
	plotData(visits,leads);
function plotData(xVisits,yLeads) {
	context.beginPath();
	context.moveTo(xVisits, yLeads);
	for (i=1;i<xVisits.length;i++) {
		context.lineTo(xVisits[i], yLeads[i]);
	}
	context.stroke();
}
    });
</script>
<body>
<div align="center">
<h2>Monthly Profits of Companies(in million $)</h2>
<canvas id="canvas" height="400" width="650">
</canvas>
<br>
	<!--Legends for Dataplot -->
<span style="color:#FF0066"> Visits Vs Leads</span>  
</div>
</body>

已更新


您应该编辑 json 数据以显示线性图。

var X = [];
var Y = [];
var data = [];
function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'https://api.myjson.com/bins/gzdjd', true);
    xobj.onreadystatechange = function() {
        if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
        }
    }
    xobj.send(null);
}
loadJSON(function(response) {
	var response;
	var field=JSON.parse(response);
	var values=[];
	for (var i = 0; i < field.length; i++) {
		var $this=field[i];
		for (var key in $this) {
		  if ($this.hasOwnProperty(key)) {
			var val = $this[key];
			values.push({"X":val.total_visits,"Y":val.total_leads});
		  }
		}
	}
    data=({"values":values});
    var graph;
	var xPadding = 30;
	var yPadding = 30;
	var sections = 12;
	var Val_max = 130;
	var Val_min = -40;
	var stepSize = 10;
	var columnSize = 50;
	var rowSize = 50;
	var margin = 10;

	function getMaxY() {
		var max = 0;
		for(var i = 0; i < data.values.length; i ++) {
			if(data.values[i].Y > max) {
				max = data.values[i].Y;
			}
		}
		max += 10 - max % 10;
		return max;
	}

	function getMaxX() {
		var max = 0;
		for(var i = 0; i < data.values.length; i ++) {
			if(data.values[i].X > max) {
				max = data.values[i].X;
			}
		}
		max += 10 - max % 10;
		return max;
	}

	function getXPixel(val) {
		return ((graph.width - xPadding) / getMaxX()) * val + (xPadding * 1.5);
	}

	function getYPixel(val) {
		return graph.height - (((graph.height - yPadding) / getMaxY()) * val) - yPadding;
	}

	graph = document.getElementById("canvas");
	var c = graph.getContext('2d');            

	c.lineWidth = 1;
	c.strokeStyle = '#333';
	c.font = 'italic 8pt sans-serif';
	c.textAlign = "center";

	c.beginPath();
	c.moveTo(xPadding, 0);
	c.lineTo(xPadding, graph.height - yPadding + 20);
	c.lineTo(graph.width, graph.height - yPadding + 20);
	c.stroke();

	for(var i = 0; i < data.values.length; i ++) {
		c.fillText(data.values[i].X, getXPixel(data.values[i].X), graph.height - yPadding + 30);
	}

	c.textAlign = "right"
	c.textBaseline = "middle";

	for(var i = 0; i < getMaxY(); i += 10) {
		c.fillText(i, xPadding - 10, getYPixel(i));
	}

	c.strokeStyle = '#f00';

	c.beginPath();
	c.moveTo(getXPixel(data.values[0].X), getYPixel(data.values[0].Y));
	for(var i = 1; i < data.values.length; i ++) {
		c.lineTo(getXPixel(data.values[i].X), getYPixel(data.values[i].Y));
	}
	c.stroke();

	c.fillStyle = '#333';

	for(var i = 0; i < data.values.length; i ++) {  
		c.beginPath();
		c.arc(getXPixel(data.values[i].X), getYPixel(data.values[i].Y), 4, 0, Math.PI * 2, true);
		c.fill();
	}
	var yScale = (graph.height - columnSize - margin) / (Val_max - Val_min);
	var xScale = (graph.width - rowSize) / sections;
	c.strokeStyle="#009933"; // color of grid lines
	c.beginPath();

	for (i=1;i<=sections;i++) {
		var x = i * xScale;
		//c.fillText(xAxis[i], x,columnSize - margin);
		c.moveTo(x - 18, columnSize);
		c.lineTo(x - 18, graph.height - margin);
	}

	var count =  0;
	for (scale=Val_max;scale>=Val_min;scale = scale - stepSize) {
		var y = columnSize + (yScale * count * stepSize); 
		//c.fillText(scale, margin,y + margin);
		c.moveTo(rowSize - 18,y)
		c.lineTo(graph.width,y)
		count++;
	}
	c.stroke();
});
<div align="center">
<h2>Monthly Profits of Companies(in million $)</h2>
<canvas id="canvas" height="400" width="650">
</canvas>
<br>
	<!--Legends for Dataplot -->
<span style="color:#FF0066"> Visits Vs Leads</span>  
</div>

关于javascript - 如何从json中获取输入来绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45605122/

相关文章:

javascript - jQuery 解除绑定(bind)和绑定(bind)

html - 添加子 div 时父 div 的背景图像为 "collapses"

javascript - Cannot POST/test.php 当我试图将数据输入数据库时​​它给了我这个错误

javascript - Wicket:用淡入和淡出替换面板(WiQuery、JQuery)

javascript - 无法获取javascript对象的属性

javascript - 使用 Electron 在 app.asar 中包含额外文件

jquery - 鼠标单击时未启用输入文本

java - 如何在Java中获取网页上所有<p>标签的字符串值?

html - 证明内容 : flex-end works correctly in chrome but aligns based off the the wrong width in IE

css - 样式化 vanilla html 表格以与样式组件 react