数据可视化前后端分离——Nodejs+Vue+Vite+D3

(一) 软件安装

安装顺序:Node.js→Vue→Vite

在学习一个软件之前,我们先得知道所学软件是干什么用的?
接下来将简要介绍一下Node.js,Vue,Vite,D3都是些什么

  1. Node.js
    Node.js 是一个开源与跨平台的 JavaScript 运行时环境,是运行在服务端的 JavaScript,可以实现前后端分离
  2. Vue
    The Progressive JavaScript Framework 目前最为流行的前端框架之一
  3. Vite
    Native-ESM powered web dev build tool. It’s fast. ⾯向未来的前端构建⼯具
  4. D3
    Data-Driven Document,是用来做数据可视化的一个JavaScript的函数库

1.Node.js安装

官方安装包下载地址http://nodejs.cn/download/
安装环境:win10 x64

  1. 下载与安装

    选择对应版本下载安装包
    在这里插入图片描述

  2. 点击下载好的安装包并按提示选择安装

  3. 检验是否安装成功:命令行输入:node -v,显示出对应版本号即成功

  4. 简单测试

    创建一个.js文件,这里取名为helloworld.js,写入如下代码:

var http=require('http');
http.createServer(function (request,response){
	//发送HTTP头部
	//HTTP状态值:200:OK
	//内容类型:text/plain
	response.writeHead(200,{'Content-Type':'text/plain'});
	
	//发送响应数据"Hello World"
	response.end('Hello World\n');
}).listen(8888);
///终端打印	
console.log('Server running at http://127.0.0.1:8888/');

命令行在该文件路径下输入node helloworld.js,网页打开链接,显示Hello World即成功
在这里插入图片描述

2.Vue安装

安装:命令行输入npm install vue(已经安装了Node.js,自带包管理器NPM)

3.Vite安装

安装:命令行输入npm install vite

4.测试

创建一个vue空工程npm init vite-app hellovue

在这里插入图片描述
按提示依次在命令行输入,并打开返回的网址,打开如下页面

在这里插入图片描述

5.其它创建Vite+Vue工程的代码

  1. 用npm
    npm 6.x
    npm init @vitejs/app my-vue-app --template vue
    npm 7+,extra
    npm init @vitejs/app my-vue-app -- --template vue
  2. 用yarn:先执行npm install -g yarn安装yarn
    yarn create @vitejs/app my-vue-app --template vue

(二) 实例代码

目的: 用Vite+Vue实现D3直方图

步骤:

  1. 新建一个名为D3Hist的项目工程,用VSCode打开

    首先我们先来介绍以下内容的含义:
    node_modules:存放npm命令下载的开发环境和生产环境的依赖包
    public:静态资源目录,不会改变文件,多用来存放第三方插件
    src:存放项目源码及需要引用的资源文件
    assets:存放项目中需要用到的资源文件,css、js、images等
    components:存放vue开发中一些公共组件
    App.vue:应用入口,渲染工程
    main.js:入口js文件
    index.html:入口页面
    package.json:用于 node_modules资源部和启动、打包项目的 npm 命令管理
    

在这里插入图片描述

  1. 在组件里新建一个名为BarChart.vue的文件,并将我们要用到的数据的json文件(26个字母的频率)放入public目录下
    json文件:https://pan.baidu.com/s/1-KvxtPvnyV3x-zwfz_Vv3Q 提取码:0mjb

    在这里插入图片描述

  2. 因为我们是要用D3画图,所以在终端加载D3npm install d3

在这里插入图片描述

  1. axios安装:终端加载npm install axios
    Axios是一个基于promise的HTTP库,可以用在浏览器和node.js中,主要是用于向后台发起请求的,这里为请求数据

在这里插入图片描述

  1. BarChart.vue组件实现
<template>
  <h1>{{ msg }}</h1>
  <div id="bar-chart-container"></div>
  //<!--<p v-for="info in a">{{info.letter}},{{info.frequency}}</p>循环显示字母与对应频率-->
</template>

<script>
import { defineComponent } from "vue";
import axios from "axios";
import * as d3 from "d3";

// 显示字母与频率的数据
// export default {
//   name: 'BarChart',
//   props: {
//     msg: String
//   },
//   data() {
//     return {
//       a:""
//     }
//   },
//   mounted(){
//     axios.get("/alphabet.json").then((response)=>{
//       //console.log(response["data"]);
//       this.a=response["data"];
//       console.log(typeof(this.ldh[0]));
//     });
//   }
// }

export default defineComponent({
  name: 'BarChart',
  props: {
    msg: String
  },
  data() {
    return {
      color: "steelblue",
      margin: { top: 30, right: 0, bottom: 30, left: 40 },
    };
  },//在挂载后开始执行
  mounted(){
    axios.get("./alphabet.json").then((res)=>{
      const barChartData = Object.assign(this.formatData(res.data),{
        format:"%",
        y:"↑ Frequency",
      });
      this.drawBarChart(barChartData);
    });
  },
  methods:{
    formatData(data){//格式化数据
      return data //整个返回的数据为频率升序的字典{字母:频率}格式数据
        .map(({letter,frequency})=>{
          return {name:letter,value:frequency};
        })  //返回数据格式为字典形式{字母:频率}
        .sort((a,b)=>d3.ascending(a.value,b.value));  //将返回的数据按频率升序排列
    },
    drawBarChart(data){//画直方图
      const margin=this.margin;
      const width=800;
      const height=500;

      //初始化SVG元素
      const svg=d3.select("#bar-chart-container")
                  .append("svg")
                  .attr("class","bar-chart")
                  .attr("viewBox",`0 0 ${width} ${height}`)
                  .attr("width",width)
                  .attr("height",height)
                  .append("g");
      //X轴缩放比例尺
      const x = d3.scaleBand()
                  .domain(d3.range(data.length))
                  .range([margin.left,width-margin.right])
                  .padding(0,1);
      //Y轴缩放比例尺
      const y = d3.scaleLinear()
                  .domain([0,d3.max(data,(d)=>d.value)])
                  .nice()
                  .range([height-margin.bottom,margin.top]);
      
      //X轴
      const xAxis=(g)=>g.attr("transform",`translate(0,${height-margin.bottom})`)
                        .call(
        d3.axisBottom(x)
          .tickFormat((i)=>data[i].name)
          .tickSizeOuter(0) // tickSizeOuter(0) 移除 0 处初始的标记
      );
      //Y轴
      const yAxis=(g)=>g.attr("transform",`translate(${margin.left},0)`)
                        .call(d3.axisLeft(y).ticks(null,data.format))
                        .call((g)=>g.select(".domain").remove())// 移除区域间的竖线
                        .call((g)=>g.append("text")
                                    .attr("x",-margin.left)
                                    .attr("y",10)
                                    .attr("fill","currentColor")
                                    .attr("text-anchor","start")
                                    .text(data.y)
                        );
      svg.append("g")
         .attr("fill",this.color)
         .selectAll("rect")
         .data(data)
         .join("rect")
         .attr("x",(d,i)=>x(i))
         .attr("y",(d)=>y(d.value))
         .attr("height",(d)=>y(0)-y(d.value))
         .attr("width",x.bandwidth());
      //绘制到SVG
      svg.append("g").call(xAxis);
      svg.append("g").call(yAxis)
    },
  },
});
</script>

<style scoped>
a {
  color: #42b983;
}
</style>
  1. App.vue实现
<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <BarChart msg="Hello Vue 3 + Vite BarChart" />
</template>

<script>
import BarChart from './components/BarChart.vue'
export default {
  name: 'App',
  components: {
    BarChart
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

运行结果:
在这里插入图片描述

(三) 相关学习网站

Node.js: http://nodejs.cn/learn
Vue:https://cn.vuejs.org/v2/guide/index.html
Vite:https://vitejs.dev/guide/
D3:https://iowiki.com/d3js/d3js_index.html
刘德华数据:https://api.ownthink.com/kg/knowledge?entity=%E5%88%98%E5%BE%B7%E5%8D%8E

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值