使用antv展示爬虫数据

今天我们组主要做的是在已经实现获取上万条数据之上,完成数据展示

1.折线统计图

(1)首先取出数据库的数据

public class TestServlet1 extends HttpServlet {


	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
		 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


		doPost(request, response);
	}


	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
		 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		taste2num();
        out.write(taste2num());
		out.flush();
		out.close();
	}
	private String Map2G2EasyJson(Map<String,Integer> map,String valuex,String valuey){
		StringBuffer buffer = new StringBuffer();
		buffer.append("{\"data\":[");
		//map key
		for (String key : map.keySet()) {
			buffer.append("{\""+valuex+"\":\""+key+"\",");
			buffer.append("\""+valuey+"\":"+map.get(key)+"},");
		}
		buffer.delete(buffer.length()-1, buffer.length()).append("],");
		buffer.append("\"valuex\":\""+valuex+"\",");
		buffer.append("\"valuey\":\""+valuey+"\"}");
		return buffer.toString();
	}
	private String taste2num() {
		List<String> moneys = new ArrayList<String>();
		Map<String,Integer> tmap = new HashMap<String,Integer>();
		//获取数据
		Connection con = null;
		PreparedStatement sql_statement = null;
		ResultSet set = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			 String mysqlurl = "jdbc:mysql://localhost:3306/user";
			String sql =  "select money from info"; 
			  String username = "root";
			  String password = "root";
			  con = DriverManager.getConnection(mysqlurl, username, password);
			 // System.out.println("数据库已连接");
			  sql_statement = con.prepareStatement(sql);
			  set = sql_statement.executeQuery();
			  
			  //循环遍历结果集,将取出的结果放到list容器中
			  while(set.next()){
				  
				  moneys.add(set.getString(1));
				  //System.out.println("--"+set);
				  
			  }
			  for (String money : moneys) {
				  
						 //System.out.println("moneyss="+moneyss.length);
						
						if(null!=money&&"null"!=money.trim()&& !money.contains("-")){
							
							int newmoney=Integer.parseInt(money.replace("人均:", "").replace("元", ""));
							//int newmoney1=Integer.parseInt(money.replace("人均:", ""));
							if(newmoney>=50&&newmoney<=60){ 
								tmap.put("人均在50-60之间",tmap.get("人均在50-60之间")+1);
						  }else if(newmoney>=60&&newmoney<=70){
							  tmap.put("人均在60-70之间",tmap.get("人均在60-70之间")+1);
							  
						  }else if(newmoney>=70&&newmoney<=80){
							  tmap.put("人均在70-80之间",tmap.get("人均在70-80之间")+1);
							  
						  }else if (newmoney>=80&&newmoney<=90) {
							  tmap.put("人均在80-90之间",tmap.get("人均在80-90之间")+1);
							
						}else if (newmoney>=90&&newmoney<=100) {
							tmap.put("人均在90-100之间",tmap.get("人均在90-100之间")+1);
						}else if(newmoney>=100){
							tmap.put("人均100以上",tmap.get("人均100以上")+1);
							
						}
							
					}
			}
			  
			  for (String string : tmap.keySet()) {
				System.out.println(string+" : "+tmap.get(string));
			}
			  return Map2G2EasyJson(tmap,"人均","数量");	  
			  
			  //Statement
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(set!=null){
					set.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(sql_statement!=null){
					sql_statement.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(con!=null){
					con.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
		return null;
	}
	 
	
}

(2)绘制条形统计图,建立html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,height=device-height">
    <title>基础折线图</title>
    <style>::-webkit-scrollbar{display:none;}html,body{overflow:hidden;height:100%;}</style>
</head>
<body>
<div id="mountNode"></div>
<script>/*Fixing iframe window.innerHeight 0 issue in Safari*/document.body.clientHeight;</script>
<script src="https://gw.alipayobjects.com/os/antv/assets/g2/3.0.4-beta.2/g2.min.js"></script>
<script src="https://gw.alipayobjects.com/os/antv/assets/data-set/0.8.3/data-set.min.js"></script>
<script
  src="http://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>

<script src="js/jquery-1.11.1.min.js"></script>
<script>
  $.ajax({
	   type: "POST",//请求方式  
	   url: "echar1",//地址,就是action请求路径  
	   data: "",//数据类型text xml json  script  jsonp
	   dataType:"json",
	   success: function(msg){//返回的参数就是 action里面所有的有get和set方法的参数  
	      const chart = new G2.Chart({
    container: 'mountNode',
    forceFit: true,
    height: window.innerHeight
  });
  chart.source(msg.data);
  chart.scale(msg.valuey, {
    min: 0
  });
  chart.scale(msg.valuex, {
    range: [ 0 , 1 ]
  });
  chart.tooltip({
    crosshairs: {
      type: 'line'
    }
  });
  chart.line().position(msg.valuex+"*"+msg.valuey);
  chart.point().position(msg.valuex+"*"+msg.valuey).size(4).shape('circle').style({
    stroke: '#fff',
    lineWidth: 1
  });
  chart.render();
  },error:function(msg)
	   {
		   console.info("error!!!");
		   console.info(msg);
	   }  
	});  
</script>
</body>
</html>
显示结果:


2.基础饼图

(1)取出数据库对应的信息

public class TestServlet2 extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		taste2num();
        out.write(taste2num());
		out.flush();
		out.close();
	}
	private String Map2G2EasyJson(Map<String,Integer> map,String valuex,String valuey){
		StringBuffer buffer = new StringBuffer();
		buffer.append("{\"data\":[");
		//map key
		for (String key : map.keySet()) {
			buffer.append("{\""+valuex+"\":\""+key+"\",");
			buffer.append("\""+valuey+"\":"+map.get(key)+"},");
		}
		buffer.delete(buffer.length()-1, buffer.length()).append("],");
		buffer.append("\"valuex\":\""+valuex+"\",");
		buffer.append("\"valuey\":\""+valuey+"\"}");
		return buffer.toString();
	}
	private String taste2num() {
		List<String> comments = new ArrayList<String>();
		Map<String,Integer> tmap = new HashMap<String,Integer>();
		//获取数据
		Connection con = null;
		PreparedStatement sql_statement = null;
		ResultSet set = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			 String mysqlurl = "jdbc:mysql://localhost:3306/user";
			String sql =  "select comment from info"; 
			  String username = "root";
			  String password = "root";
			  con = DriverManager.getConnection(mysqlurl, username, password);
			 // System.out.println("数据库已连接");
			  sql_statement = con.prepareStatement(sql);
			  set = sql_statement.executeQuery();
			  //Vector<Object> list = convertList( set);
			  
			  //循环遍历结果集,将取出的结果放到list容器中
			  while(set.next()){
				  
				  comments.add(set.getString(1));
				  //System.out.println("--"+set);
				  
			  }
			  for (String comment : comments) {
						
						if(null!=comment&&"null"!=comment.trim()/*&& !comment.contains("-")*/){
							
							int newcomment=Integer.parseInt(comment.replace("条评论", ""));
							if(newcomment<100){ 
								tmap.put("100条以下评论",tmap.get("100条以下评论")+1);
						  }else if(newcomment>=100&&newcomment<=500){
							  tmap.put("100-500条评论",tmap.get("100-500条评论")+1);
							  
						  }else if(newcomment>=500&&newcomment<=1000){
							  tmap.put("500-1000条评论",tmap.get("500-1000条评论")+1);
							  
						  }else if (newcomment>=1000&&newcomment<=2000) {
							  tmap.put("1000-2000条评论",tmap.get("1000-2000条评论")+1);
							
						}else if (newcomment>=2000) {
							tmap.put("2000条以上评论",tmap.get("2000条以上评论")+1);
						}
							
					}
			}
			  
			  for (String string : tmap.keySet()) {
				 
				System.out.println(string+" : "+tmap.get(string));
			}
			  return Map2G2EasyJson(tmap,"评论","数量");	  
			  
			  //Statement
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(set!=null){
					set.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(sql_statement!=null){
					sql_statement.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(con!=null){
					con.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
		return null;
	}
	 
	
}

(2)绘制饼图,建立html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,height=device-height">
    <title>基础饼图</title>
    <style>::-webkit-scrollbar{display:none;}html,body{overflow:hidden;height:100%;}</style>
</head>
<body>
<div id="mountNode"></div>
<script>/*Fixing iframe window.innerHeight 0 issue in Safari*/document.body.clientHeight;</script>
<script src="https://gw.alipayobjects.com/os/antv/assets/g2/3.0.4-beta.2/g2.min.js"></script>
<script src="https://gw.alipayobjects.com/os/antv/assets/data-set/0.8.3/data-set.min.js"></script>
<script
  src="http://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>

<script src="js/jquery-1.11.1.min.js"></script>
<script>
$.ajax({
	   type: "POST",//请求方式  
	   url: "echar2",//地址,就是action请求路径  
	   data: "",//数据类型text xml json  script  jsonp
	   dataType:"json",
	   success: function(msg){
	   var valuex = msg.valuex;
  const { DataView } = DataSet;
 
  const dv = new DataView();
  dv.source(msg.data).transform({
    type: 'percent',
    field: msg.valuey,
    dimension: msg.valuex,
    as: 'percent'
  });
  const chart = new G2.Chart({
    container: 'mountNode',
    forceFit: true,
    height: window.innerHeight,
  });
  chart.source(dv, {
    percent: {
      formatter: val => {
         val= parseFloat(val).toFixed(4);
        val = (val * 100) + '%';
        return val;
      }
    }
  });
  chart.coord('theta');
   
 
  chart.tooltip({
    showTitle: false,
    itemTpl: '<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
  });
  chart.intervalStack()
    .position('percent')
    .color(msg.valuex)
    .label('percent', {
      formatter: (val, item) => {
      console.info(item);
      console.info(valuex);
        return item.point.评论 + ': ' + val;
      }
    })
    .tooltip(msg.valuex+"*percent",(item,percent) => {
     percent= parseFloat(percent).toFixed(4);
      percent = percent * 100 + '%';
      
      return {
        name: item,
        value: percent
      };
    })
    .style({
      lineWidth: 1,
      stroke: '#fff'
    });
  chart.render();
  },error:function(msg)
	   {
		   console.info("error!!!");
		   console.info(msg);
	   }  
	});  
</script>
</body>
</html>
展示效果:







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值