数据可视化(JavaScript篇与D3篇)

本文介绍了数据可视化的重要性,并通过JavaScript和D3库展示了直方图、二叉树和文字树的实现。D3部分则涵盖了直方图、环图和力导向图的创建,以及如何链接MySQL数据库。这些示例展示了数据可视化在传达复杂信息方面的有效性。
摘要由CSDN通过智能技术生成

前言:什么是数据可视化?

数据可视化主要旨在借助于图形化手段,清晰有效地传达与沟通信息。笔者认为将抽象的数据以直观的图形表示出来,并且我们能从中提取出有效信息,那么数据可视化的目的就达到了。图像和图表已被证明是一种有效的方法来进行新信息的传达与教学,运用数据可视化技术,可以让我们对于数据的理解和记忆更为深刻。
下面笔者总结了目前为止,可视化课程内容教学中的所学。笔者还有很多地方需要学习改进,欢迎大家批评指正!

一、JavaScript篇

1、可视化直方图

说明

在进入实例代码之前,你需要了解一下有关于svg的知识: W3school:SVG
我们这次要用到的是矩形(rect)和文本(text)

基本语法

var svg=document.getElementById(ID);//返回对拥有指定 ID 的第一个对象的引用
svg.setAttribute(‘width’,w);//设置svg的宽
svg.setAttribute(‘height’,h);//设置svg的高
rec[i]=document.createElement(“rect”)//创建rect元素
txt1[i]=document.createElement(“text”)//创建text元素
svg.appendChild(xxx);//向节点的子节点列表的末尾添加新的子节点
xxx.outerHTML="<rect x= y= width= height= fill=‘rgb(··· )’>";//获取元素内的html内容和文本

(1)代码

<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>票房统计直方图</title>
	</head>
	<body>
		<h1 style="text-align:center">2011-2020全国全年票房统计直方图(单位:亿元)</h1>
		<svg id="mysvg" width=800 height=600>
		<text x="0" y="530" fill="grad">年份:</text>
		</svg>
		<script>
			var w = window.innerWidth
			|| document.documentElement.clientWidth
			|| document.body.clientWidth;

			var h = window.innerHeight
			|| document.documentElement.clientHeight
			|| document.body.clientHeight; 
			//获得浏览器窗口的高度和宽度:(不包括工具栏和滚动条)
			w=w*0.98;
			h=h*0.98;
			
			var svg=document.getElementById("mysvg");
			svg.setAttribute('width',w);
			svg.setAttribute('height',h);
			
			var rec_data=[131,171,218,296,441,454,559,607,641,203];//2011-2020票房数据
			var rec=new Array();
			var txt1=new Array();//票房数据txt显示
			var txt2=new Array();//年份txt显示
			for(var i=0;i<10;i++){
				rec[i]=document.createElement("rect")
				txt1[i]=document.createElement("text");
				txt2[i]=document.createElement("text");
				svg.appendChild(rec[i]);
				svg.appendChild(txt1[i]);
				svg.appendChild(txt2[i]);
				var rec_h=rec_data[i]/2;
				rec[i].outerHTML="<rect x="+i*(w/10) + " y="+(500-rec_h)+" width="+ (w/10-5)+" height="+rec_h+ " fill='rgb("+(131-rec_h/5)+","+(175-rec_h/5)+","+(155-rec_h/5)+")'>";
				txt1[i].outerHTML="<text x="+(i*w/10+(w/10-5)/2)+" y="+(490-rec_h)+" fill='rgb(131,175,155)'>"+rec_h*2+"</text>";
				txt2[i].outerHTML="<text x="+(i*w/10+(w/10-5)/2)+" y=530 fill='grad'>"+(2011+i)+"</text>"
			}
			
			var lineX=document.createElement("line");
			svg.appendChild(lineX);
			lineX.outerHTML="<line x1=0 y1=510 x2="+w+" y2=510 stroke='gray' />";
			
		</script>
	<p align="center" style="font-family:verdana;color:black">数据来源:2011-2020猫眼票房</p>		
	</body>
</html>

(2)实验结果
在这里插入图片描述

2、二叉树

基本语法

这次用到了(line),用法与(rect)和(text)相同
var L=L * rate * (0.7+Math.random() * 0.5);//每次衰减后的长度,rate是衰减率
var aL=a-0.6 * Math.PI/4 * (0.7+Math.random() * 0.5);//向左转动的角度:参数自设
var aR=a+0.5 * Math.PI/4 *(0.7+Math.random() * 0.5);//向右转动的角度
show(x2,y2,L,rate,aL,count-1);//左子树:具体看自己写的函数
show(x2,y2,L,rate,aR,count-1);//右子树
递归下去

(1)代码

<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>随机二叉树</title>
	</head>
	<body>
		<svg id="mysvg" >
		</svg>
		<script>
			var w = window.innerWidth
			|| document.documentElement.clientWidth
			|| document.body.clientWidth;

			var h = window.innerHeight
			|| document.documentElement.clientHeight
			|| document.body.clientHeight; 
			//获得浏览器窗口的高度和宽度:(不包括工具栏和滚动条)
			w=w*0.98;
			h=h*0.98;
			
			//设置svg为全屏
			var svg=document.getElementById("mysvg");
			svg.setAttribute('width',w);
			svg.setAttribute('height',h*1.5);
			
			
			var x0=w/2;
			var y0=h*1.4;
			var L=200;
			var rate=0.7;
			var a=-Math.PI/2;
			var count=9;
			var fontsize=10;
			
			function show(x0,y0,L,rate,a,count){
				var x1=x0;
				var y1=y0;
				var x2=x1+L*Math.cos(a);
				var y2=y1+L*Math.sin(a);
				
				var lineX=document.createElement("line");
				svg.appendChild(lineX);
				lineX.outerHTML="<line x1="+(x1+0.6*count)+" y1="+(y1+0.6*count)+" x2="+(x2+0.6*count)+" y2="+(y2+0.6*count)+" stroke='rgb(162,153,136)' stroke-width="+fontsize+" />";
				//255,255,100
				
				if(count<3)
				{
					var lineX2=document.createElement("line");
					svg.appendChild(lineX2);
					lineX2.outerHTML="<line x1="+(x1+0.6*count)+" y1="+(y1+0.6*count)+" x2="+(x2+0.6*count)+" y2="+(y2+0.6*count)+" stroke='rgb(255,255,100)' stroke-width="+fontsize*0.6+" />";
				
				}
				
				var L=L*rate*(0.7+Math.random()*0.5);
				var aL=a-0.6*Math.PI/4*(0.7+Math.random()*0.5);
				var aR=a+0.5*Math.PI/4*(0.7+Math.random()*0.5);
				if (count>0){
					show(x2,y2,L,rate,aL,count-1);//左
					show(x2,y2,L,rate,aR,count-1);
				}
			}
			show(x0,y0,L,rate,a,count);
		</script>
	</body>
</html>

(2)实验结果
在这里插入图片描述

3、文字树

基本语法

与上面二叉树类似(可自己添加创意)

(1)代码

<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>祈愿树</title>
	</head>
	<body>
		<svg id="mysvg" width=800 height=600>
		</svg>
		<script>
			var w = window.innerWidth
			|| document.documentElement.clientWidth
			|| document.body.clientWidth;

			var h = window.innerHeight
			|| document.documentElement.clientHeight
			|| document.body.clientHeight; 
			//获得浏览器窗口的高度和宽度:(不包括工具栏和滚动条)
			w=w*0.98;
			h=h*0.98;
			
			//设置svg为全屏
			var svg=document.getElementById("mysvg");
			svg.setAttribute('width',w);
			svg.setAttribute('height',h);
			
			var title=document.createElement("text");
			svg.appendChild(title);
			title.outerHTML="<text x="+((w/2)-120)+" y=50 fill='grad' font-size=40 >祈愿文字树</text>";
			
			var x0=w/2;
			var y0=h;
			var L=200;
			var rate=0.6;
			var a=-Math.PI/2;
			var count=9;
			var fontsize=20;
			var str="我是一颗祈愿树";
			function show(x0,y0,L,rate,a,count){
				var fontsize=count*1.5;
				var L=str.length*fontsize;
				var x1=x0;
				var y1=y0;
				var x2=x1+L*Math.cos(a);
				var y2=y1+L*Math.sin(a);
				
				var line_branch=document.createElement("line");
				svg.appendChild(line_branch);
				line_branch.outerHTML="<line x1="+x1+" y1="+y1+" x2="+x2+" y2="+y2+" stroke='rgb(107,81,82)' stroke-width="+fontsize*2+" />";
				
				var line_light=document.createElement("line");
				svg.appendChild(line_light);
				line_light.outerHTML="<line x1="+(x1+0.6*count)+" y1="+(y1+0.6*count)+" x2="+(x2+0.6*count)+" y2="+(y2+0.6*count)+" stroke='rgb(162,153,136)' stroke-width="+fontsize+" />";
				
				var words=document.createElement("text");
				svg.appendChild(words);
				words.outerHTML="<text x="+x1+" y="+y1+" rotate=90 transform='rotate("+(a*180/Math.PI)+","+x1+","+y1+")' fill='rgb(255,255,100)' font-size="+fontsize+" >"+str+"</text>"
				
				var aL=a-Math.PI/6*(0.5+0.5*Math.random());
				var aR=a+Math.PI/6*(0.5+0.5*Math.random());
				
				if (count>0){
					show(x2,y2,L,rate,aL,count-1);
					show(x2,y2,L,rate,aR,count-1);

					if (count<5)
					{
						wL=count*3*Math.random();
						hL=count*20*Math.random();
						var paper=document.createElement("rect");
						svg.appendChild(paper);
						paper.outerHTML="<rect x="+x1+"  y="+y1+" width="+wL+" height="+hL+" fill='red' >";
					}
				}
			}
			show(x0,y0,L,rate,a,count);
		</script>
	</body>
</html>

(2)实验结果
在这里插入图片描述

二、D3篇

说明

D3学习网站:https://d3js.org/

使用D3前提:
(1)项目中链接<script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
(2)下载 d3.v3.min.js :https://pan.baidu.com/s/18ysWVA6G-o6oSB4AqMJo-w 提取码:vhje

1、直方图

(1)代码

<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>D3直方图</title>
	</head>
	<body bgcolor="black">
		<svg id="mysvg"></svg>
		
		<script src="http://d3js.org/d3.v4.js"></script>
		<script>
			
			var w = window.innerWidth
			|| document.documentElement.clientWidth
			|| document.body.clientWidth;

			var h = window.innerHeight
			|| document.documentElement.clientHeight
			|| document.body.clientHeight; 
			//获得浏览器窗口的高度和宽度:(不包括工具栏和滚动条)
			w=w*0.98;
			h=h*0.98;
			
			
			var svg0=document.getElementById("mysvg");
			svg0.setAttribute('width',w);
			svg0.setAttribute('height',h*0.10);

			var title=document.createElement("text");
			svg0.appendChild(title);
			title.outerHTML="<text x="+(w/10)*0.2+" y=40 fill='white' font-size=40 >不同职业睡眠质量受心理压力影响的人群比例</text>";
			
			var dataset=[74,71,69,68,68,66,66,65,63,61];
			var dataset1=new Array(10);
			for (var i=0;i<10;i++){
				dataset1[i]=dataset[i]*h*0.01*0.80;
				}
			
			var svg=d3.select("body")
					  .append("svg")
					  .attr("width",w)
					  .attr("height",h*0.9);
					  
			var tips = svg.append("g")
				          .attr("class","tips")
				          .style("display","none")
				          .style('font-size', '10px')
				          .style('font-weight', 'bold');
			tips.append("text")
				.attr("x",8)
				.attr("dy",".75em");

			var xWidth = w;
			var yWidth = h*0.8;
			//X轴比例尺
			var xScale = d3.scaleBand()
				.domain(d3.range(dataset1.length))
				.range([0,xWidth]);
			//Y轴比例尺
			var yScale = d3.scaleLinear()
				.domain([0,d3.max(dataset1)])
				.range([0,yWidth]);	
			var format=d3.format("02d");
			
			
			svg.selectAll("rect")
			   .data(dataset1)
			   .enter()
			   .append("rect")
			   .attr("x",function(d,i){
					return i*(w/dataset1.length)+(w/dataset1.length)*0.2;
				})
			   .attr("y",function(d){
					return h*0.85-d;
				})
			   .attr("width",(w/dataset1.length)*0.5)
			   .attr("height",function(d){
					return d;
				})
			   .attr("fill",'rgb(117,99,163)')
			   .on("mouseover",function(d,i){
					d3.select(this)
					  .attr("fill",'rgb(234,175,200)');
					  tips.style("display",null);
				})
				.on("mouseout",function(d,i){
					d3.select(this)
					  .transition()
					  .duration(500)
					  .attr("fill",'rgb(117,99,163)');
				})
				.on("mousemove",function(d,i) {
					console.log(yScale(d))
					tips.attr("transform","translate("+(xScale(i)+(w/dataset1.length)*0.3)+","+100+")");
					tips.select("text").text(format((d*100)/(h*0.8))+"%");
					tips.attr("fill","white");
				});
			
			var dataset2=[ "互联网" , "商贸" , "房地产" , "制造业" , "餐饮文娱" , "教育" , "广告" , "代理" , "金融" , "政府公共","互联网"];
			var text = svg.selectAll("text")
						  .data(dataset2);	
			text.enter()				
				.append("text")			
				.attr("fill","white")
				.attr("font-size","14px")
				.attr("text-anchor","middle")
				.attr("x", function(d,i){
					return  xScale(i);
				})
				.attr("y", function(d){
					return h*0.85;
				})
				.attr("dx",xScale.bandwidth()/2)
				.attr("dy","1em")
				.text(function(d){
					return d;
				});
			
			
		</script>
		<p align="center" style="font-family:verdana;color:white">数据来源:2020CBNData调研数据</p>
	</body>
</html>

(2)实验结果
在这里插入图片描述

2、环图(带直方图)

(1)代码

<!DOCTYPE html>
<html lang="en">
	<head>
	<meta charset="UTF-8">
	<title>大众心理认知度调研</title>
	<style>
  .container {
  margin: 1px auto;
  width: 1000px;
  height: 500px;
  
  }
  polyline {
  fill: none;
  stroke: #000000;
  stroke-width: 2px;
  stroke-dasharray: 4px;
  }
	</style>
	<style type="text/css">
		p{
			font-size:15px;
			font-weight:900;
		}
	</style>
	</head>
	<body>
		
		<h1 align="center">大众心理认知度调研</h1>
		<hr width="100%"  size="10" color="gray"></hr>
		<h3 align="center">大众获取心理知识途径</h3>
		<div id="hist"></div>
		<hr width="100%"></hr>
		<h3 align="center">大众寻求心理帮助途径</h3>
		<div class="container">
			<svg width="100%" height="100%"></svg>
		</div>
		<div id="sign"></id>
		<script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
		<script>
			var w = window.innerWidth
			|| document.documentElement.clientWidth
			|| document.body.clientWidth;

			var h = window.innerHeight
			|| document.documentElement.clientHeight
			|| document.body.clientHeight; 
			//获得浏览器窗口的高度和宽度:(不包括工具栏和滚动条)
			w=w*0.98;
			h=h*0.98;
			
			var width = 1000, height = 500;
			//var w=1000,h=500
  
			var svg = d3.select("#hist")
        				.append("svg")
        				.attr("width",w)
        				.attr("height",h*1.5/3);

        	var index = [0,1,2,3,4,5];
        	var color = [ '#589BAD'];
        	var ordinal = d3.scale.ordinal()
        					.domain(index)
        					.range(color);
        					
			var dataset1=[96.45,27.79,46.34,26.78,23.62,22.96,5.79];
            var text1=["网络平台(微信公众号等)","心理类书籍&期刊杂志","心理类课程&讲座","音视频节目","网络社交圈分享","朋友聊天介绍等","其他"]
            var dataset3= [{name:"网络平台(微信公众号等)",value:96.45},
			               {name:"心理类书籍&期刊杂志",value:27.79},
						   {name:"心理类课程&讲座",value:46.34},
						   {name:"音视频节目",value:26.78},
						   {name:"网络社交圈分享",value:23.62},
						   {name:"朋友聊天介绍等",value:22.96},
						   {name:"其他",value:5.79}
							];
							
        	var min = d3.min(dataset1);
        	var max = d3.max(dataset1);
        	var linear = d3.scale.linear()
        				   .domain([min,max])
        				   .range([46.32,771.6]);
        	var rectHeight = 40;
        	svg.selectAll("rect")
        	   .data(dataset1)
        	   .enter()
        	   .append("rect")
        	   .attr("x",400)
        	   .attr("y",function(d,i){
        	   	return i*rectHeight;
        	   })
        	   .attr("width",function(d){
        	   	return linear(d);
        	   })
        	   .attr("height",rectHeight-10)
        	   .attr("fill",function(d,i){
        	   	return ordinal(i);
        	   })
			   .on("mouseover",function(d,i){
				     d3.select(this)
					   .attr('opacity', 0.7);
					 svg.append("text")
					    .attr("id","value")
				         .attr("x",w*4/5)
				         .attr("y",h/3)
				         .attr("text-anchor","middle")
				         .attr("font-size",36)
			             .text(d+"%");
					   })
			   .on("mouseout",function(d){
				     d3.select(this)
					   .attr('opacity', 1)
					d3.select("#value")
					  .remove()
					 })
			
			var texts1 = svg.selectAll('text')
                    .data(text1)
                    .enter()
                    .append('text')
                    .attr('fill', "black")
                    .text(function(d,i) {
    				   return text1[i]; })
					
                    .attr("x",width/6)
        	        .attr("y",function(d,i){
        	   	return i*rectHeight+20;
        	    })
			

  
			// 创建一个分组用来组合要画的图表元素
			var main = d3.select('.container svg').append('g')
                                        .classed('main', true)
                                        .attr('transform', "translate(" + width/2 + ',' + height/2 + ')');
  
			// 数据193.03
			var dataset = [
							{name:"其他",value:4.305},
						    {name:"上网查相关资料",value:30.658},
   							{name:"阅读心理专业书籍",value:25.089},
   							{name:"找专业心理咨询师",value:14.583},
   							{name:"去医院就诊",value:11.982},
    						{name:"不需要专业资源",value:7.962},
	 						{name:"拨打咨询热线",value:5.421}
   
							];
			var pie = d3.layout.pie()
								.sort(null)
								.value(function(d) {
									return d.value;});
			var pieData = pie(dataset);
 
			// 创建计算弧形路径的函数
			var radius = 200;
			var arc = d3.svg.arc()
                  .innerRadius(110)
                  .outerRadius(radius);
			var outerArc = d3.svg.arc()
                       .innerRadius(1.2 * radius)
                       .outerRadius(1.2 * radius);
			var oArc = d3.svg.arc()
                   .innerRadius(1.1 * radius)
                   .outerRadius(1.1 * radius);
			var slices = main.append('g').attr('class', 'slices');
			var lines = main.append('g').attr('class', 'lines');
			var labels = main.append('g').attr('class', 'labels');
  
			// 添加弧形元素(g中的path)
			var arcs = slices.selectAll('g')
                   .data(pieData)
                   .enter()
                   .append('path')
                   .attr('fill', function(d, i) {
                      return getColor(i); })
                   .attr('d', function(d){
                      return arc(d);  })
				   .on("mouseover",function(d){
				     d3.select(this)
					   .attr('opacity', 0.7);
					 slices.append("text")
					       .attr("id","value")
				           .attr("x",8)
				           .attr("y",10)
				           .attr("text-anchor","middle")
				           .attr("font-size",36)
				           .text(d.value+"%");
					   } 
				    )
				   .on("mouseout",function(d){
				     d3.select(this)
					   .attr('opacity', 1);
					  d3.select("#value")
					    .remove();
					   }); 
 
			// 添加文字标签
			var texts = labels.selectAll('text')
                    .data(pieData)
                    .enter()
                    .append('text')
                    .attr('dy', '0.2em')
                    .attr('fill', function(d, i) {
                       return getColor(i); })
                    .text(function(d, i) {
    				   return d.data.name; })
                    .style('text-anchor', function(d, i) {
                       return midAngel(d)<Math.PI ? 'start' : 'end';  })
                    .attr('transform', function(d, i) {
                       // 找出外弧形的中心点
                       var pos = outerArc.centroid(d);
                      // 改变文字标识的x坐标
                       pos[0] = radius * (midAngel(d)<Math.PI ? 1.5 : -1.5);
     
                       return 'translate(' + pos + ')'; })
                    .style('opacity', 1);

			var polylines = lines.selectAll('polyline')
								.data(pieData)
   								.enter()
   								.append('polyline')
   								.attr('points', function(d) {
   								 return [arc.centroid(d), arc.centroid(d), arc.centroid(d)];
   								})
   								.attr('points', function(d) {
									var pos = outerArc.centroid(d);
									pos[0] = radius * (midAngel(d)<Math.PI ? 1.5 : -1.5);
									return [oArc.centroid(d), outerArc.centroid(d), pos];
   								})
   								.style('opacity', 0.3);
 
  			function midAngel(d) {
  				return d.startAngle + (d.endAngle - d.startAngle)/2;
			}
  			function getColor(idx) {
  			var palette = [
    			'#ee9ca7','#F7816E', '#F9CE8C','#edf98c', '#C3E3E5', '#589BAD', '#CC5959'
  			]
  			return palette[idx % palette.length];
  			}
			
 		</script>
	<p align="center" style="font-family:verdana;color:black">数据来源:简单心理和果壳共同发起的《2020大众心理健康认知度调研问卷》</p>
	<hr width="100%"  size="10" color="gray"></hr>
	<p>结论:<br> 大众对自身的心理健康还比较关注,会通过多种途径来了解心理知识,其中通过网络获取相关知识的比重最大。而且在出现心理问题时,大众还是更倾向于通过互联网寻求帮助,而非专业咨询。</p>
	</body>
</html>

(2)实验结果
在这里插入图片描述

3、力导向图

(1)代码

基于路径Path的力导向图

<html>    
  <head>  
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>
		著名哲学家、心理学家关系网图
	</title>
	<style>
			path{
			  fill: none;
			  stroke: #5084C3;
			  stroke-width: 1.5px;
			}
			circle {
			  stroke: #C43239;
			  stroke-width: 20px;
			}
			text {
			  font: 14px sans-serif;
			  pointer-events: none;
			  
			}
			.tooltip{  
				position: absolute;  
				width: 240px;  
				height: auto;  
				font-family: simsun;  
				font-size: 10px;
				text-align: left;  
				color: black;  
				border-width: 1px solid black;  
				background-color: A6BFC3;  
				border-radius: 3px;  
			}  
			.tooltip:after{   
				content: '';  
				position: absolute;  
				bottom: 100%;  
				left: 20%;  
				margin-left: -3px;  
				width: 0;  
				height: 0;  
				border-bottom: 12px solid black;  
				border-right: 12px solid transparent;  
				border-left: 12px solid transparent;  
			}  
	</style>  
  </head> 
  <h1 align="center">著名哲学家、心理学家力导向图</h1>
<hr width="100%"  size="8" color="#A6BFC3" opacity=0.5 ></hr>  
  <body style=" opacity:1"> 
   <script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
	<script type="text/javascript">  
		var  width=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)*0.98;
		var  height=(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)*0.9;
		var  img_h=50;
		var  img_w=50;
		var  radius=10;
		var svg=d3.select("body")  
                .append("svg")  
                .attr("width",width)  
                .attr("height",height); 	
		var nodes=[
		        {name:"苏格拉底",image:"0.jpg",intro:"—公元前469年(一说公元前470年)出生,苏格拉底是哲学的圣徒和殉道者,至今,没有哪位哲学家像他那样痴迷于过一种正义的生活。"},
		        {name:"柏拉图",image:"1.jpg",intro:"——公元前427年出生,柏拉图和老师苏格拉底,学生亚里士多德并称为希腊三贤。他创造或发展的概念包括:柏拉图思想、柏拉图主义、柏拉图式爱情等。"},
				{name:"色诺芬",image:"2.jpg",intro:"——公元前430年出生,雅典人,历史学家,苏格拉底的弟子。他以记录当时的希腊历史、苏格拉底语录而著称。"},
				{name:"亚里士多德",image:"3.jpg",intro:"——公元前384年出生,世界古代史上伟大的哲学家、科学家和教育家之一,堪称希腊哲学的集大成者。他是柏拉图的学生,亚历山大的老师。"},
				{name:"普罗提诺",image:"4.jpg",intro:"——公元205年出生,其学说融汇了毕达哥拉斯和柏拉图的思想以及东方神秘主义,视太一为万物之源,人生的最高目的就是复返太一,与之合一。罗马帝国时代最伟大的哲学家"},
				{name:"托马斯·阿奎那",image:"5.jpg",intro:"——1225年出生,中世纪经院哲学的哲学家、神学家。他把理性引进神学,用 “自然法则”来论证“君权神授”说,是自然神学最早的提倡者之一,也是托马斯哲学学派的创立者,成为天主教长期以来研究哲学的重要根据。"},
				{name:"笛卡尔",image:"6.jpg",intro:"——1596年3月31日出生,法国哲学家、数学家、物理学家。他对现代数学的发展做出了重要的贡献,因将几何坐标体系公式化而被认为是解析几何之父。他还是西方现代哲学思想的奠基人之一,是近代唯物论的开拓者,提出了“普遍怀疑”的主张。"},
				{name:"卢梭",image:"7.jpg",intro:"——1712年6月28日出生,国十八世纪启蒙思想家、哲学家、教育家、文学家,民主政论家和浪漫主义文学流派的开创者,启蒙运动代表人物之一。他提出“人民主权”的思想,国家主权不能分割,也不能转让,一切人权的表现和运用必须表现人民的意志,法律是“公意”,在法律面前人人平等,君主不能高于法律。"},
				{name:"康德",image:"8.jpg",intro:"——1749年4月22日出生,德国古典哲学创始人,其学说深深影响近代西方哲学,并开启了德国古典哲学和康德主义等诸多流派。康德是启蒙运动时期最后一位主要哲学家,是德国思想界的代表人物。"},
				{name:"席勒",image:"9.jpg",intro:"——1759年11月10日出生,席勒是德国文学史上著名的“狂飙突进运动”的代表人物,也被公认为德国文学史上地位仅次于歌德的伟大作家。"},
				{name:"黑格尔",image:"10.jpg",intro:"——1770年8月27日出生,德国19世纪唯心论哲学的代表人物之一,黑格尔的思想标志着19世纪德国唯心主义哲学运动的顶峰,对后世哲学流派,如存在主义和马克思的历史唯物主义都产生了深远的影响"},
				{name:"谢林",image:"11.jpg",intro:"——1775年1月27日出生,主要领域:自然哲学、自然科学、美学、宗教、形而上学、认识论,其思想常常被英语系国家所轻视,主要原因之一是因为黑格尔后来的崇高地位,他在《哲学史讲演录》中故意贬低了谢林,将谢林描述为德国唯心主义发展过程中的一个小注脚。"},
				{name:"狄尔泰",image:"12.jpg",intro:"——1833年11月19日出生,他曾研究黑格尔青年时期的手稿,于1906年发表了《黑格尔青年时代的历史》。最初属于新康德主义,后转向生命哲学,致力于所谓“历史理性的批判”,主张“历史的相对主义”。认为哲学的中心问题是生命。"},
				{name:"尼采",image:"13.jpg",intro:"——1844年10月15日出生,尼采猛烈的揭露和批判传统的基督教道德和现代理性,对现代理性也持批判态度,是后主客二分哲学的过激派"},
				{name:"弗洛伊德",image:"14.jpg",intro:"——1856年5月6日出生,奥地利精神病医师、心理学家、精神分析学派创始人。弗洛伊德的精神分析开创潜意识心理的研究,开创了人格心理学、动力心理学和变态心理学的新领域,并促进自我心理学的发展。"},
				{name:"海德格尔",image:"15.jpg",intro:"——1889年9月26日出生,海德格尔是存在主义哲学的创始人和主要代表之一,批判黑格尔的”绝对精神“主义,主张”天人合一“的哲学思想,反对西方旧形而上学思想。"}
		];
		
		var edges=[{source:0,target:1,relation:"老师"},
		           {source:0,target:2,relation:"老师"},
				   {source:1,target:2,relation:"同门"},
				   {source:1,target:3,relation:"老师"}, 
				   {source:4,target:1,relation:"延续&超越"},
				   {source:5,target:3,relation:"延续&超越"}, 
				   {source:6,target:1,relation:"“回忆说”影响大"}, 
				   {source:8,target:4,relation:"继承"},
				   {source:8,target:7,relation:"具有相通性"}, 
				   {source:8,target:6,relation:"批判"}, 
				   {source:9,target:1,relation:"继承"},
				   {source:10,target:9,relation:"延续&超越"},
			       {source:10,target:8,relation:"延续&发扬唯物主义"},
				   {source:10,target:1,relation:"继承&批判"},
				   {source:11,target:8,relation:"超越"},
				   {source:11,target:10,relation:"相互批评"},
				   {source:12,target:10,relation:"研究出版书籍"},
				   {source:13,target:8,relation:"批判"},
				   {source:13,target:10,relation:"批判"},
				   {source:13,target:14,relation:"少数补充"},
				   {source:14,target:13,relation:"延续"},
				   {source:15,target:10,relation:"批判&反对"},
				   {source:15,target:8,relation:"延续少数&否定多数"}];
			   
var force=d3.layout.force()
                .nodes(nodes)
				.links(edges)
				.size([width,height])
				.linkDistance(350)
				.charge(-1200)
                .start();	
        //提示框部分
		var tooltip=d3.selectAll("body")  
                    .append("div")  
                    .attr("class","tooltip")  
                    .style("opacity",0.0); 

       //箭头绘制	
		var defs = svg.append("defs");
		var radius=70;
		var arrowMarker = defs.append("marker")
								.attr("id","arrow")
								.attr("markerUnits","strokeWidth")
								.attr("markerWidth","4")
								.attr("markerHeight","4")
								.attr("viewBox","0 0 4 4")
								.attr("refX",20+radius/8-2)   //实际是radius/strokeWidth
								.attr("refY",2)
								.attr("orient","auto");

		var arrow_path = "M0,1 L4,2 L0,3 L0,0";

		arrowMarker.append("path")
					.attr("d",arrow_path); 					
		var color=d3.scale.category20();
		var path = svg.selectAll("path")
								  .data(edges)
								  .enter()
								  .append("path")
								  .attr("id", function(d,i) {
									   return "edgepath" +i;
								  })
								  .attr("class","edges")
								  .attr("marker-end","url(#arrow)");		
		var pathtext = svg.selectAll('.pathText')
				  .data(edges)
				  .enter()
				  .append("text")
				  .attr("class","pathText")
				  .append('textPath')
				  .attr("text-anchor", "middle")//居中
				  .attr("startOffset","50%")
				  .attr('xlink:href', function(d,i) { return "#edgepath" + i; })
				  .text(function(d) { return d.relation; });						  
		var  img_h=80;
		var  img_w=80;
		var  radius=30;								
		var  circles=svg.selectAll("forceCircle")
	               .data(nodes)
				   .enter()
				   .append("circle")
				   .attr("class","forceCircle")
				   .attr("r",radius)
				   .style("stroke","DarkGray")
				   .style("stroke-width","1.0px")
				   .attr("fill", function(d, i){
                                    //创建圆形图片
                                    var defs = svg.append("defs").attr("id", "imgdefs");
                                    var catpattern = defs.append("pattern")
                                                         .attr("id", "catpattern" + i)
                                                         .attr("height", 1)
                                                         .attr("width", 1);
                                    catpattern.append("image")
                                            .attr("x", - (img_w / 2 - radius+5.8))
                                            .attr("y", - (img_h / 2 - radius+3.5))
                                            .attr("width", img_w+11)
                                            .attr("height", img_h+6)
                                            .attr("xlink:href","image/"+d.image);
                                    return "url(#catpattern" + i + ")";
                    })
					.on("mouseover",function(d,i){    //加入提示框
                        tooltip.html("人物简介"+d.intro)
                               .style("left",(d3.event.pageX)+"px")  
                               .style("top",(d3.event.pageY+20)+"px")  
                               .style("opacity",0.8);  
					})
					.on("mousemove",function(d){            
                          tooltip.style("left",(d3.event.pageX)+"px")  
                                 .style("top",(d3.event.pageY+20)+"px"); })           
                   .on("mouseout",function(d){  
                        tooltip.style("opacity",0.0); })
				   .call(force.drag);  
	    var texts=svg.selectAll(".forceText")
                 .data(nodes)
				 .enter()
				 .append("text")
				 .attr("class","forceText")
				 .attr("x",function(d){return d.x;})
				 .attr("y",function(d){return d.y;})
				 .style("stroke", "#02206D")
                 .attr("dx","-1.5em")
				 .attr("dy","3em")
				 .text(function(d){return d.name;});
				 	
		force.on("tick",function(){
		      path.attr("d", function(d) {
					var dx = d.target.x - d.source.x;//增量
					var	dy = d.target.y - d.source.y;
					return "M" + d.source.x + ","+ d.source.y + "L" + d.target.x + "," + d.target.y;
				  });
			  circles.attr("cx",function(d){return d.x;});
			  circles.attr("cy",function(d){return d.y;});
			  texts.attr("x",function(d){return d.x;});
			  texts.attr("y",function(d){return d.y;});
		});
		
		
	</script>
	<hr width="100%"  size="3" color="#A6BFC3" opacity=0.5></hr>
  </body>
</html>

(2)实验结果

4、链接MySQL数据库

链接数据库

固定格式:
<%@ page contentType=“text/html; charset=gb2312” %>
<%@ page language=“java” %>
<%@ page import=“com.mysql.cj.jdbc.Driver” %> //注意这个
<%@ page import=“java.sql.*” %>
<%
//驱动程序名
String driverName=“com.mysql.cj.jdbc.Driver”;
//数据库用户名
String userName="–用户名(默认root)–";
//密码
String userPasswd="–数据库密码–";
//数据库名
String dbName="–数据库名–";
//表名
String tableName="–表名–";
//联结字符串
String url=“jdbc:mysql://localhost:3306/”+dbName+"?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
Class.forName(“com.mysql.cj.jdbc.Driver”).newInstance();
Connection connection=DriverManager.getConnection(url,"–用户名–","–密码–");
Statement statement = connection.createStatement();
<--------数据操作------->
String sql="······";//查询语句
ResultSet rs = statement.executeQuery(sql); //rs返回查询语句的结果集
·······
<--------数据操作------->
rs.close();
statement.close();
connection.close(); //打完“电话”别忘了关闭哦! %>

数据库中取出的数据传到js:
类似于如下操作:
<% for(int i=0;i <count.length;i++){ %>
dataset[ <%=i%> ]= " <%=count[i]%> ";
<%}%>
<% %>内的是java的数据和语法

(1)代码

<body>
<div id="wc"></div>
<%@ page contentType="text/html; charset=gb2312" %> 
<%@ page language="java" %> 
<%@ page import="com.mysql.cj.jdbc.Driver" %> 
<%@ page import="java.sql.*" %> 
<% 
                        //out.print("<center><h1><font color=blue>Matrix Word Cloud English Learning</h1></center>"); 
						//驱动程序名 
						String driverName="com.mysql.cj.jdbc.Driver"; 
						//数据库用户名 
						String userName="--用户名(默认root)--"; 
						//密码 
						String userPasswd="--数据库密码--"; 
						//数据库名 
						String dbName="--数据库名--"; 
						//表名 
						String tableName="--表名--"; 
						//联结字符串 
						String url="jdbc:mysql://localhost:3306/"+dbName+"?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8"; 
						Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); 
						Connection connection=DriverManager.getConnection(url,"--用户名--","--密码--"); 
						Statement statement = connection.createStatement(); 
						int count[]=new int[26];
						for(int i=0;i<26;i++){
							int aa=Integer.valueOf('a')+i;
							char cha = (char) aa;
							//out.print(aa);
							//out.print(cha);

							//String sql="SELECT * FROM "+tableName+" where english like 'a%' "+"order by english"; 
							String sql="SELECT * FROM "+tableName+" where english like '"+cha+"%' "+"order by english"; 
							ResultSet rs = statement.executeQuery(sql);  
							// 输出每一个数据值 
							
							String str;
							int j=0;
							while(rs.next()) { 
								str=(rs.getString(2)).substring(0,1);
								//out.print(str+" "); 
								j++;
							}
							//out.print(" "+j+" <br>"); 
							count[i]=j;
							rs.close();
						} 
						statement.close(); 
						connection.close(); 
%>
<script src="http://d3js.org/d3.v3.min.js"></script>
		<script>
		    var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

			var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
			w=w*0.98;
			h=h*0.95;
			var color=d3.scale.category10();
			
			var dataset =new Array(26);
			<% for(int i=0;i <count.length;i++){ %>
				dataset[ <%=i%> ]= " <%=count[i]%> ";
			<%}%>


			//var dataset=[100,90,88,700,888,180];
			var dataset=new Array(10);
			for (var i=0;i<10;i++){
				dataset[i]=Math.floor(Math.random()*500);
			}
			var ww=w/dataset.length;
			var svg=d3.select("body")
			          .append("svg")
					  .attr("width",w)
					  .attr("height",h);
			var rect=svg.selectAll("rect")
			            .data(dataset)
				        .enter()
			            .append("rect")
                          .attr("x",function(d,i){return i*w/dataset.length})
						  .attr("y",function(d){return h-d})
						  .attr("width",ww*0.95)
						  .attr("height",function(d){return d})
						  .attr("fill",function(d,i){return color(i)});
						  
			var rect=svg.selectAll("text")
			            .data(dataset)
				        .enter()
			            .append("text")
                          .attr("x",function(d,i){return i*w/dataset.length})
						  .attr("y",function(d){return h-d})
                          .text(function(d){return d})
						  .attr("dx",ww/2)
						  .attr("dy","-1em")
						  .attr("text-anchor","middle")
                          .attr("fill",function(d,i){return color(i)});					  
		
		</script>

</body>

(2)实验结果
在这里插入图片描述

5、词云图

说明: 除了加载 d3.v3.min.js(前面有发),还需加载d3.layout.cloud.js
d3.layout.cloud.js下载:https://pan.baidu.com/s/1vY-MZU-rG6FnCaap0lGx4Q 提取码:roqh

数据库:
在这里插入图片描述
(1)代码 :等上完课交作业了再发,嘿嘿!

(2)实验结果

在这里插入图片描述

个人心得: 数据可视化的课程还是收获满满的,但还是有很多不足,仍需加强学习,继续努力,未完待续······

  • 8
    点赞
  • 78
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值