您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

可视化数据分析-基于JavaScript的d3实践学习

目录

一.svg简介

二.D3简介

D3功能来源

常用语法说明

三.d3可视化访问MySQL数据库

实现方法

四.具体用例实现

svg绘制直方图

svg绘制二叉树(以电影票房为例)

D3进行数据可视化(链接数据库)

D3绘制直方图​

D3绘制饼图

D3绘制力导向图

D3绘制词云图



 

一.svg简介

SVG是什么

可缩放矢量图形(Scalable Vector Graphics)是基于可扩展标记语言(Extensible Markup Language,XML ),用于描述二维矢量图形的一种图形格式,一般用在网页。

SVG创建工具

由于SVG是XML文件,SVG图像可以用任何文本编辑器创建,但它往往是与一个绘图程序一起使用,如Inkscape、Adobe Illustrator,更方便地创建SVG图像。

SVG使用方式

1. 浏览器直接打开

2. 在HTML中使用<img>标签引用

3. 直接在HTML中使用SVG标签

4. 作为CSS背景

SVG优点

1. 矢量的图形,不会失真任意伸缩。

2. 可被非常多的工具读取和修改(比如记事本)。

3. 与 JPEG 和 GIF 图像比起来,尺寸更小,且可压缩性更强。

4. 图像中的文本是可选的,同时也是可搜索的(很适合制作地图)。

浏览器支持

IE9+,Firefox,Chrome,Opera和Safar、iOS、Android3+ 都支持SVG。

 

二.D3简介

  D3.js 是一个基于数据的操作文档的 JavaScript 库,可以绑定任何数据到 ,支持 DIV 图案生成,也支持 SVG 图案的生成,D3提供了各种简单易用的函数,大大简化JS操作数据的难度,尤其在数据可视化方面,D3已将生成可视化的复杂步骤精简到了几个简单函数,只需输入几个简单数据,就可将数据转换绘制为各种基本图形。在操作过程中可以简单这样来解释:有一个存在若干个结点的选择区域,其中有若干个结点可以容纳数据,其结点和数据一一对应,在操作过程中实际上时将数据存放在节点中,这一过程称为绑定数据。

D3功能来源

直接引用d3.v3.js或其他d3版本文档。

常用语法说明

d3.select("body")
选择器:D3采用了一种声明式的方法,对任意节点集合的操作被称为选择。例如:

1

d3.select('#vis').append('div').style('top', '20px').style('left','20px');

selectAll("p")
选择DOM中的所有段落。由于没有存在,这将返回一个空的选择。这个选择为空,代表段落很快就会存在。

data(dataset)
计数和分析我们的数据值。如果dataset中有五个值,则之后我们的数据集将会执行5次,每个值一次。

enter()
要创建新的数据绑定的元素,需要使用enter() 。这个方法会在DOM中,然后被传递给它的数据。如果有更多的数据值比相应的DOM元素,然后进入() 创建一个新的占位符元素,关闭的引用到这个新的占位符链中的下一个步骤。

append("p")
以占位符enter() 到DOM中插入一个p元素。

text("New paragraph!")
将新创建的p和插入一个文本值的参考。

function(){return ;}

动态属性:D3 支持这种以 function 方式传入的属性,这样的属性是动态的,每次执行的时候再去调用计算获得:

1

2

3

d3.selectAll("p").style("color", function() {

  return "hsl(" + Math.random() * 360 + ",100%,50%)";

});

三.d3可视化访问MySQL数据库

实现方法

在html页面中嵌入Java代码,在tomcat的lib目录中引入mysql-connector-java-5.1.6-bin.jar包,编写Java代码取出数据库中相关数据,再在d3中进行可视化操作。

四.具体用例实现

 

svg绘制直方图


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>直方图</title>
</head>
<body>
    <svg id="mySVG" width="800" height="600" version="1.1"></svg>
	<script type="text/javascript">        
		var mysvg = document.getElementById("mySVG");
        var rec= new Array();
        var txt=new Array();
		for(var i=0;i<6;i++){
			rec[i] = document.createElement("rect");
            txt[i] = document.createElement("text");
			mysvg.appendChild(rec[i]);
            mysvg.appendChild(txt[i]);
            var h=Math.random()*255;
            var r=Math.floor(Math.random()*255);
            var g=Math.floor(Math.random()*255);
            var b=Math.floor(Math.random()*255);
			rec[i].outerHTML="<rect x="+(45*i)+" y="+(400-h)+" width=42 height="+h+" style='fill:rgb("+r+","+g+","+b+")'/>";
            txt[i].outerHTML="<text x="+(10+45*i)+" y="+(400-h)+">"+Math.floor(h)+"</text>";
        }
  </script>
</body>
</html>

 

svg绘制二叉树(以电影票房为例)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>树形二叉树</title>	
</head>

<body>
<h1 align="center" fontsize=7>电影总票房排序文字二叉树-计科鲁俊丽-201811113010</h1>
<svg id="svg01" 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.9;

	
    var svg=document.getElementById("svg01");
    svg.setAttribute("width",w);
    svg.setAttribute("height",h);
    
    var x0=w/2;
	var y0=h;
	var rate=0.4*(0.5+Math.random()*0.5);
	
	var a=-Math.PI/2;
	var count=6;
	
	var str=["战狼2","哪吒之魔童降世","流浪地球","复仇者联盟4","终局之战","红海行动","美人鱼","唐人街探案2","我和我的祖国","我不是药神","中国机长","速度与激情8","西虹市首富","速度与激情7","捉妖记","复仇者联盟3:无限战争","捉妖记2","羞羞的铁拳","疯狂的外星人","海王","变形金刚4:绝迹重生","前任3:再见前任","毒液:致命守护者","功夫瑜伽","飞驰人生","侏罗纪世界2","寻龙诀","烈火英雄","西游伏妖篇","港囧",	"变形金刚5:最后的骑士","少年的你","疯狂动物城","魔兽","复仇者联盟2:奥创纪元","夏洛特烦恼","速度与激情:特别行动","芳华","侏罗纪世界","蜘蛛侠:英雄远征","头号玩家","后来的我们","一出好戏","阿凡达","摔跤吧!爸爸","扫毒2天地对决","人再囧途之泰囧","无双","西游降魔篇","美国队长3:英雄内战","碟中谍6:全面瓦解","寻梦环游记	","西游记之孙悟空三打白骨精","误杀","加勒比海盗5:死无对证","长城","湄公河行动","叶问4","心花路放金刚:骷髅岛煎饼侠","大黄蜂","极限特工:终极回归","澳门风云3","生化危机6:终章","攀登者","变形金刚3","西游记之大闹天宫","巨齿鲨","乘风破浪","神偷奶爸3","惊奇队长","盗墓笔记","功夫熊猫3","狂暴巨兽","奇幻森林","澳门风云2","西游记之大圣归来","泰坦尼克号3D版","比悲伤更悲伤的故事	","哥斯拉2:怪兽之王","老炮儿","超时空同居","绝地逃亡","阿丽塔:战斗天使","智取威虎山3D","十二生肖","智取威虎山","碟中谍5:神秘国度","银河补习班","冰雪奇缘2","星球大战:原力觉醒","蚁人2:黄蜂女现身","狮子王","从你的全世界路过","唐人街探案","叶问3","X战警:天启","反贪风暴4","无名之辈","北京遇上西雅图之不二情书,钢铁侠3","蜘蛛侠:英雄归来","霍比特人3:去而复归","大闹天竺","星际穿越","奇异博士","无问西东","天将雄师","神秘巨星","雷神3:诸神黄昏","猩球崛起:终极之战","金刚狼3:殊死一战","X战警:逆转未来","终结者:创世纪","美国队长2","西游记女儿国	","致我们终将逝去的青春","私人订制","猩球崛起2:黎明之战","熊出没·原始时代","画皮II","狼图腾","爸爸去哪儿","使徒行者2:谍影行动","铁道飞虎","环太平洋","悟空传","银河护卫队2","正义联盟	","鬼吹灯之九层妖塔","寒战2 宠爱","碟中谍4:幽灵协议","唐山大地震","蚁人","分手大师","摩天营救","让子弹飞","情圣","黑豹"];
    var sign=["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"];

function show(x0,y0,rate,a,count)
{
    //var L=L*rate*(Math.random()*0.5+0.5);
	var aL=a-Math.PI/4*(Math.random()*0.5+0.5);
	var aR=a+Math.PI/4*(Math.random()*0.5+0.5);

	var stri=str[0];
	for(var i=Math.pow(2,6-count)-1;i<Math.pow(2,7-count)-1;i++)
	{
		if(sign[i]=="1")
		{
			stri=str[i];
			sign[i]="0";
			i=Math.pow(2,7-count)-1;	
		}
	};
   	var fontsize=count*6;
	var L=stri.length*fontsize;
	var x1=x0;
	var y1=y0;
	var x2=x1+L*Math.cos(a);
	var y2=y1+L*Math.sin(a);
	var words=document.createElement("text");
	svg.appendChild(words);
	words.outerHTML="<text x="+x1+" y="+y1+" transform='rotate("+(a*180)/Math.PI+","+x1+","+y1+")' fill='steelblue' font-size="+fontsize+">"+stri+"</text>"

	if(count>0)
    {
		show(x2,y2,rate,aL,count-1);
		show(x2,y2,rate,aR,count-1);

		if(count==1)
		{
		var apple=document.createElement("circle");
		svg.appendChild(apple);
		apple.outerHTML="<circle cx="+x2+" cy="+y2+" r=4 fill='red'/>"
		}
    }
}

show(x0,y0,rate,a,count);
</script>
</body>
</html>

D3进行数据可视化(链接数据库)

D3绘制直方图

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
<meta charset="utf-8">
</head>
<body  charset="utf-8">
<div id="wc"></div>
<%@ page contentType="text/html; charset=gb2312" %> 
<%@ page language="java" %> 
<%@ page import="com.mysql.jdbc.Driver" %> 
<%@ page import="java.sql.*" %> 
<% 
                         out.print("<center><h1><font color=steelblue>2021年影视剧全平台播放量统计直方图-5月24日数据</h1></center>"); 
						 out.print("<center><h2><font color=steelblue>来源:骨朵数据</h2></center>"); 
						//驱动程序名 
						String driverName="com.mysql.jdbc.Driver"; 
						//数据库用户名 
						String userName="root"; 
						//密码 
						String userPasswd="password"; 
						//数据库名 
						String dbName="engword"; 
						//表名 
						String tableName="episoderank"; 
						String tableName1="nodeluxun"; 
						String tableName2="edgesluxun";
						//联结字符串 
						
						Class.forName("com.mysql.jdbc.Driver").newInstance(); 
						Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/engword?useUnicode=true&characterEncoding=utf8&useSSL=false","root","password"); 
						Statement statement = connection.createStatement(); 

						float charcount[]=new float[40];
                        String occu[]=new String[40];
						for(int i=1;i<41;i++){		
							String sql="SELECT * FROM "+tableName+" where id = '"+i+"'"; 
							
							String str="  ";
							float per=1;
							ResultSet rs = statement.executeQuery(sql);
							while(rs.next())
							{
								str=rs.getString(2);
							   per=rs.getFloat(3);
							  // out.print(per);
							   //out.print(str);
							}
							charcount[i-1]=per;
							occu[i-1]=str;
                            rs.close();								
						}
						
						
						
			  String name[]=new String[20];
						String image[]=new String[20];
						String intro[]=new String[20];
					    int source[]=new int[20];
						int target[]=new int[20];
						String relation[]=new String[20];
						
						for(int i=1;i<21;i++){		
							String sql="SELECT * FROM "+tableName1+" where id = '"+i+"'"; 
							
							String str="  ";
			                String str1=" ";
							String str2=" ";
							ResultSet rs = statement.executeQuery(sql);
							while(rs.next())
							{
								str=rs.getString(2);
			                    str1=rs.getString(3);
								str2=rs.getString(4);
							 
							}
							
							name[i-1]=str;
							image[i-1]=str1;
							intro[i-1]=str2;
                            rs.close();								
						}
						
						
						for(int i=1;i<21;i++){		
							String sql1="SELECT * FROM "+tableName2+" where id = '"+i+"'"; 
							
							int nums=0;
			                int numt=0;
							String str2=" ";
							ResultSet rs = statement.executeQuery(sql1);
							while(rs.next())
							{
								nums=rs.getInt(2);
			                    numt=rs.getInt(3);
								str2=rs.getString(4);
							
							}
							
							source[i-1]=nums;
							target[i-1]=numt;
							relation[i-1]=str2;
                            rs.close();								
						}
			 
						statement.close(); 
						connection.close(); 
%>
  
   <script src="d3.v4.js"></script>
	<script src="d3.layout.cloud.js"></script>
	
		<script>
	
		var color = d3.scaleOrdinal(d3.schemeCategory10);
		    var w=window.innerWidth;

			var h=window.innerHeight;
			w=w;
			h=h*2.5;
			
			/*-----------------------------------------------直方图------------------------------------------------------*/
//var color=d3.scale.category10();
			var dataset=new Array(14);
			//var dataAlphabet=new Array(14);
			var occupation=new Array(14);
			
			<%
			for (int i=0;i<14;i++){
			%>
				//dataset[i]=Math.floor(Math.random()*500);
				dataset[<%=i%>]=<%=charcount[i]%>;   //js的代码
				
				occupation[<%=i%>]='<%=occu[i]%>';
				
				<% }%>
			
			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 120+i*w*0.85/dataset.length})
						  .attr("y",function(d){return 0.4*h-d*10})
						  .attr("width",ww*0.7)
						  .attr("height",function(d){return d*10})
						  .attr("fill",function(d,i){return "steelblue"});
						  
			var rect=svg.selectAll("text")
			            .data(dataset)
				        .enter()
			            .append("text")
                          .attr("x",function(d,i){return 100+i*w*0.85/dataset.length})
						  .attr("y",function(d){return 0.4*h-10*d+8})
                          .text(function(d){return d+"亿"})
						  .attr("dx",ww/2)
						  .attr("dy","-1em")
						  .attr("text-anchor","middle")
						  .attr("font-size",15)
                          .attr("fill",'black');			
            				  
					  
			var rectA=svg.selectAll("text1")
			            .data(occupation)
				        .enter()
			            .append("text")
						
                          .attr("x",function(d,i){return 100+i*w*0.85/occupation.length})
						  .attr("y",function(d){return 0.4*h+23})
						  .attr("font-size",15)
                          .text(function(d){return d})
						  .attr("dx",ww/2)
						  .attr("dy","-1em")
						  .attr("text-anchor","middle")
						  .attr("font-size",10)
                          .attr("fill","black");	
						  
						  
						  
			</script>

	</body>
</html>

D3绘制饼图

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<body  charset="utf-8">
<div id="wc"></div>
<%@ page contentType="text/html; charset=utf-8" %> 
<%@ page language="java" %> 
<%@ page import="com.mysql.jdbc.Driver" %> 
<%@ page import="java.sql.*" %> 
<% 
                         out.print("<center><h1><font color=steelblue>2021年影视剧全平台播放量统计-5月24日数据</h1></center>"); 
						 out.print("<center><h2><font color=steelblue>来源:骨朵数据</h2></center>"); 
						//驱动程序名 
						String driverName="com.mysql.jdbc.Driver"; 
						//数据库用户名 
						String userName="root"; 
						//密码 
						String userPasswd="password"; 
						//数据库名 
						String dbName="engword"; 
						//表名 
						String tableName="episoderank"; 
						
						
						Class.forName("com.mysql.jdbc.Driver").newInstance(); 
						Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/engword?useUnicode=true&characterEncoding=utf8&useSSL=false","root","password"); 
						Statement statement = connection.createStatement(); 

						float charcount[]=new float[40];
                        String occu[]=new String[40];
						for(int i=1;i<41;i++){		
							String sql="SELECT * FROM "+tableName+" where id = '"+i+"'"; 
							
							String str="  ";
							float per=1;
							ResultSet rs = statement.executeQuery(sql);
							while(rs.next())
							{
								str=rs.getString(2);
							   per=rs.getFloat(3);
							  // out.print(per);
							   //out.print(str);
							}
							charcount[i-1]=per;
							occu[i-1]=str;
                            rs.close();								
						}
						
			
						statement.close(); 
						connection.close(); 
%>

	
<script src="d3.v4.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;
			var width = w*0.98;
			var height =h*0.96;
			
			var dataset=new Array(14);			  
			var total=0;
			<%
			for (int i=0;i<14;i++){
			%>
             dataset[<%=i%>]=['<%=occu[i]%>',<%=charcount[i]%>];	
			// total+=dataset1[<%=i%>][1];
			<% }%>
			//转化数据为适合生成饼图的对象数组		
			var pie = d3.pie()
						.value(function(d){return d[1];});
			
			innerRadius = 50;//圆环内半径
			
			var arc=d3.arc()//设置弧度的内外半径,等待传入的数据生成弧度
				.innerRadius(innerRadius)
				.outerRadius(function (d) {
					var value=d.value;
					return value*5+ innerRadius;
				});		

			var svg=d3.select("body")
					.append("svg")
					.attr("width",width)
					.attr("height",height);

			var color = d3.scaleOrdinal(d3.schemeCategory20c);
			
			//准备分组,把每个分组移到图表中心
			var arcs=svg.selectAll("g")
				.data(pie(dataset))
				.enter()
				.append("g")
				//移到图表中心
				.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");//translate(a,b)a表示横坐标起点,b表示纵坐标起点

			//为组中每个元素绘制弧形路路径
			arcs.append("path")//每个g元素都追加一个path元素用绑定到这个g的数据d生成路径信息
				.attr("fill",function(d,i){//填充颜色
					return color(i);
				})
				.attr("d",arc)//将角度转为弧度(d3使用弧度绘制
				.on('mouseover',function(d,i){
					d3.select(this)
					.attr("fill", d3.rgb(color(i)).brighter());	
					svg.append("text")
					   .attr("id","info")
					   .attr("x",width/2)
					   .attr("y",height/2)
					   .attr("text-anchor","middle")
					   .attr("font-size",20)
					   .text(d.data[0]);
					svg.append("text")
					   .attr("id","value")
					   .attr("x",width/2)
					   .attr("y",height/2+24)
					   .attr("text-anchor","middle")
					   .attr("font-size",20)
					   .text(d.value+"亿");
				})
				.on('mouseout',function(d,i){
					d3.select(this)
					.attr("fill",color(i));	
					d3.select("#info")
					.remove();
					d3.select("#value")
					.remove();
				});
				
			arcs.append("text")
				.attr("transform",function(d){
					var x = arc.centroid(d)[0];
					var y = arc.centroid(d)[1];
					return "translate(" + x + "," + y + ")";
				})
				.attr("text-anchor","middle")
				.attr("font-size",function(d) { 
					return d.data[1]*0.8 + "px"; 
				})
				.text(function(d){				
					return d.value;
				});
        </script>
	
	</body>
</html>

 

D3绘制力导向图

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta  meta charset="utf-8">
<h1 align="center"><font color=black > 影视剧觉醒年代人物鲁迅关系图</h1>

<h2  align="right">
来源:北京鲁迅博物馆
</h2>
<style>
			path{
			  fill: none;
			  stroke: #666;
			  stroke-width: 1.5px;
			}
			circle {
			  stroke: #333;
			  stroke-width: 1.5px;
			}
			text {
			  font: 10px sans-serif;
			  pointer-events: none;
			}
			.tooltip{  
				position: absolute;  
				width: 340px;  
				height: auto;  
				font-family: simsun;  
				font-size: 10px;
				text-align: left;  
				color: black;  
				border-width: 1px solid black;  
				background-color: 7FFF00;  
				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>

<body style=" opacity:1">



<div id="wc"></div>
<%@ page contentType="text/html; charset=gb2312" %> 
<%@ page language="java" %> 
<%@ page import="com.mysql.jdbc.Driver" %> 
<%@ page import="java.sql.*" %> 
<% 
        //驱动程序名 
						String driverName="com.mysql.jdbc.Driver"; 
						//数据库用户名 
						String userName="root"; 
						//密码 
						String userPasswd="password"; 
						//数据库名 
						String dbName="engword"; 
						//表名 
						//表名 
						String tableName1="nodeluxun"; 
						String tableName2="edgesluxun";
							
						Class.forName("com.mysql.jdbc.Driver").newInstance(); 
						Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/engword?useUnicode=true&characterEncoding=utf8&useSSL=false","root","password"); 
						Statement statement = connection.createStatement(); 
						
						//float charcount[]=new float[20];
                        String name[]=new String[20];
						String image[]=new String[20];
						String intro[]=new String[20];
					    int source[]=new int[20];
						int target[]=new int[20];
						String relation[]=new String[20];
						
						for(int i=1;i<21;i++){		
							String sql="SELECT * FROM "+tableName1+" where id = '"+i+"'"; 
							
							String str="  ";
			                String str1=" ";
							String str2=" ";
							ResultSet rs = statement.executeQuery(sql);
							while(rs.next())
							{
								str=rs.getString(2);
			                    str1=rs.getString(3);
								str2=rs.getString(4);
							  // out.print(per);
							//   out.print(str);
							}
							
							name[i-1]=str;
							image[i-1]=str1;
							intro[i-1]=str2;
							
						
						//	out.print(name[i-1]);
                            rs.close();								
						}
						
						
						for(int i=1;i<21;i++){		
							String sql1="SELECT * FROM "+tableName2+" where id = '"+i+"'"; 
							
							int nums=0;
			                int numt=0;
							String str2=" ";
							ResultSet rs = statement.executeQuery(sql1);
							while(rs.next())
							{
								nums=rs.getInt(2);
			                    numt=rs.getInt(3);
								str2=rs.getString(4);
							 //   out.print(str2);
							}
							
							source[i-1]=nums;
							target[i-1]=numt;
							relation[i-1]=str2;
							
						
						//	out.print(name[i-1]);
                            rs.close();								
						}
			 
						statement.close(); 
						connection.close(); 
						
						
%>
<script  src="https://d3js.org/d3.v3.min.js"></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=new Array(20);			  
			<%
			for (int i=0;i<20;i++){
			%>
             nodes[<%=i%>]={name:"<%=name[i]%>",image:"<%=image[i]%>",intro:"<%=intro[i]%>"};	
			// total+=dataset1[<%=i%>][1];
			<% }%>	
				
            var edges=new Array(20);			  
			<%
			for (int i=0;i<20;i++){
			%>
             edges[<%=i%>]={source:<%=source[i]%>,target:<%=target[i]%>,relation:"<%=relation[i]%>"};	
			// total+=dataset1[<%=i%>][1];
			<% }%>	
			
			var force=d3.layout.force()
                .nodes(nodes)
				.links(edges)
				.size([width,height])
				.linkDistance(150)
				.charge(-1200)
                .start();	
        //提示框部分
		var tooltip=d3.selectAll("body")  
                    .append("div")  
                    .attr("class","tooltip")  
                    .style("opacity",0.0); 

       //箭头绘制	
		var defs = svg.append("defs");
		var radius=10;
		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=50;
		var  img_w=50;
		var  radius=23;								
		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",1.0);  
					})
					.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", "#2F4F4F")
                 .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>
	
</body>

D3绘制词云图

<html>
<meta charset=utf-8>
<body>
<div id="wc"></div>
<%@ page contentType="text/html; charset=utf-8" %> 
<%@ page language="java" %> 
<%@ page import="com.mysql.jdbc.Driver" %> 
<%@ page import="java.sql.*" %> 
<% 
                        out.print("<center><h1><font color=steelblue>词云图</h1></center>"); 
						//驱动程序名 
						String driverName="com.mysql.jdbc.Driver"; 
						//数据库用户名 
						String userName="root"; 
						//密码 
						String userPasswd="password"; 
						//数据库名 
						String dbName="engword"; 
						//表名 
						String tableName="episoderank"; 
						//联结字符串 
						
						Class.forName("com.mysql.jdbc.Driver").newInstance(); 
						Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/engword?useUnicode=true&characterEncoding=utf8&useSSL=false","root","password"); 
						Statement statement = connection.createStatement(); 

                        String name[]=new String[100];
                        float rate[]=new float[100];
                       // int count[] = new int[26];
						for(int i=0;i<45;i++){
							

							//String sql="SELECT * FROM "+tableName+" where english like 'a%' "+"order by english"; 
							String sql="SELECT * FROM "+tableName+" where id = "+(i+1)+" "; 
							ResultSet rs = statement.executeQuery(sql);  
							// 输出每一个数据值 
							
							float per=0;
							String na="";
							while(rs.next()) { 
								per=rs.getFloat(3);
								na=rs.getString(2);
							}
							name[i]=na;
							rate[i]=per;
							//count[i]=j;
							//out.print(" "+j+" <br>"); 
							rs.close();
						}
						
						statement.close(); 
						connection.close(); 
						%>
		<script src="d3.v4.js" charset="utf-8"></script> 
		<script src="d3.layout.cloud.js"></script>

		<script>
	color = d3.scaleOrdinal(d3.schemeCategory10);
			var w = window.innerWidth
			|| document.documentElement.clientWidth
			|| document.body.clientWidth;

			var h = window.innerHeight
			|| document.documentElement.clientHeight
			|| document.body.clientHeight;
			var width = w * 0.98;
			var height = h * 0.9;	

			var words = new Array(45);
			<%
				for(int i=0;i<45;i++)
				{%>					
					words[<%=i%>]={name:"<%=name[i]%>",size:<%=rate[i]%>};
				<%}
			%>
		var wc=d3.layout.cloud()
				  .size([w, h])
				  .words(words)
				  .padding(5)
				  .rotate(function() { return ~~(Math.random() * 2) * 90; })
				  .font("Impact")
				  .fontSize(function(d) { return d.size; })
				  .on("end", draw)
				  .start();

		  function draw(words) {
			d3.select("body").append("svg")
				.attr("width", w)
				.attr("height", h)
			  .append("g")
				.attr("transform", "translate(300,200)")
			  .selectAll("text")
				.data(words)
			  .enter().append("text")
				.style("font-size", function(d) { return d.size+"px"; })
				.style("font-family", "Impact")
				.style("fill",function(d,i){return color(i);})
				.attr("text-anchor", "middle")
				.attr("transform", function(d) {
				  return "translate(" + [d.x+w/4, d.y+h/4] + ")rotate(" + d.rotate + ")";
				})
				.text(function(d) { return d.name; });
		  }
		  
		 
		</script>
</body>
</html>


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进