如何在VueJS上绘制图形 [英] How to make a Graph on VueJS

查看:79
本文介绍了如何在VueJS上绘制图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用从API接收的数据制作图表并将其放在图表上( https: //bl.ocks.org/mbostock/4062045 )-力向图

Am trying to make a graph with data received from an API and put this on a graph (https://bl.ocks.org/mbostock/4062045) - Force-Directed Graph

但是我不确定如何在VueJ上完成此操作,或者不确定是否有更简单的工具来执行此操作?

However I am unsure on how this is done on VueJs or if there is a simpler tool to do this?

D3力导向图似乎有点复杂,也许已经有一个库可以直接使用?

D3 Force-Directed Graph seems a bit complicated, maybe there is a library already that does this out of the box?

推荐答案

注释中提到的vue-d3软件包只是将D3添加到Vue原型中,因此可以通过this.$d3进行访问.

The mentioned vue-d3 package from the comment is just adding D3 to the Vue prototype so it is accessible with this.$d3.

我已经测试了该程序包,但不适用于我的D3版本.看起来像是大小写问题(D3而不是d3).所以我手动添加了原型.

I've tested that package but it wasn't working with my D3 version. Looks like a casing issue (D3 instead of d3). So I've added the prototype manually.

我不知道是否有用于创建力图的更简单的库,但请查看下面的演示或此

I don't know if there is an easier library for creating a force graph but please have a look at the demo below or this fiddle.

我已经从您的链接中修改了示例,以创建一个力向图.该演示正在运行,但是正如您所提到的,它非常复杂. 从SVG到Vue.js模型的绑定也可以改善.但是我找不到更好的方法.

I've modified the example from your link to create a force directed graph. The demo is working but as you've mentioned it's pretty complicated. Also binding from SVG to Vue.js model could be improved. But I couldn't find a better way to do it.

例如,单击时添加新节点并不能仅将新节点添加到数组中,但这应该是Vue.js组件的目标.数据更改后,SVG图形应自动更新.

For example adding a new node on click is not working with just adding a new node to the array but this should be the goal for a Vue.js component. The SVG graph should automatically update once the data changes.

目前,组件中未使用Vue.js中的节点和链接,因为我不知道如何添加图的更新.

At the moment, nodes and links in Vue.js are not used in the component because I don't know how to add the updating of the graph.

如果您想出了如何添加模型数据的更新,请告诉我.通过删除SVG并重新创建它,可以很轻松地刷新整个图表. (请参阅重新加载按钮)

If you figured out how to add the updating with the model data, please let me know. Refreshing the whole chart is pretty easy by deleting the SVG and re-create it. (see reload button)

// https://unpkg.com/vue-d3@0.1.0 --> only adds d3 to Vue.prototype but it wasn't working as expected (d3 is lower case)
Vue.prototype.$d3 = d3;
const URL = 'https://demo5147591.mockable.io/miserables'; // data copied from below link because of jsonp support

//'https://bl.ocks.org/mbostock/raw/4062045/5916d145c8c048a6e3086915a6be464467391c62/miserables.json';
//console.log(window.d3);
const d3ForceGraph = {
  template: `
  <div>
    {{mousePosition}}
    <button @click="reload">reload</button>
    <svg width="600" height="600" 
    	@mousemove="onMouseMove($event)"></svg>
  </div>
  `,
  data() {
    return {
      nodes: [],
      links: [],
      simulation: undefined,
      mousePosition: {
        x: 0,
        y: 0
      }
    }
  },
  mounted() {
    this.loadData(); // initially load json
  },
  methods: {
    // load data
    loadData() {
    		this.$svg = $(this.$el).find('svg');
        let svg = this.$d3.select(this.$svg.get(0)), //this.$d3.select("svg"),
          width = +svg.attr("width"),
          height = +svg.attr("height");
        //console.log($(this.$el).find('svg').get(0));

        this.simulation = this.$d3.forceSimulation()
          .force("link", this.$d3.forceLink().id(function(d) {
            return d.id;
          }))
          .force("charge", this.$d3.forceManyBody())
          .force("center", this.$d3.forceCenter(width / 2, height / 2));
        let color = this.$d3.scaleOrdinal(this.$d3.schemeCategory20);
        $.getJSON(URL, (graph) => {
          //d3.json("miserables.json", function(error, graph) { // already loaded
          //if (error) throw error; // needs to be implemented differently
          let nodes = graph.nodes;
          let links = graph.links;
          
          let link = svg.append("g")
            .attr("class", "links")
            .selectAll("line")
            .data(links) //graph.links)
            .enter().append("line")
            .attr("stroke-width", function(d) {
              return Math.sqrt(d.value);
            });

          let node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("circle")
            .data(nodes) //graph.nodes)
            .enter().append("circle")
            .attr("r", 5)
            .attr("fill", function(d) {
              return color(d.group);
            })
            .call(this.$d3.drag()
              .on("start", this.dragstarted)
              .on("drag", this.dragged)
              .on("end", this.dragended));

          node.append("title")
            .text(function(d) {
              return d.id;
            });

          this.simulation
            .nodes(graph.nodes)
            .on("tick", ticked);

          this.simulation.force("link")
            .links(links); //graph.links);

          function ticked() {
            link
              .attr("x1", function(d) {
                return d.source.x;
              })
              .attr("y1", function(d) {
                return d.source.y;
              })
              .attr("x2", function(d) {
                return d.target.x;
              })
              .attr("y2", function(d) {
                return d.target.y;
              });

            node
              .attr("cx", function(d) {
                return d.x;
              })
              .attr("cy", function(d) {
                return d.y;
              });
          }
        })
      },
      reload() {
        //console.log('reloading...');
        this.$svg.empty(); // clear svg --> easiest way to re-create the force graph.
        this.loadData();
      },
      // mouse events
      onMouseMove(evt) {
        //console.log(evt, this)
        this.mousePosition = {
          x: evt.clientX,
          y: evt.clientY
        }
      },
      // drag event handlers
      dragstarted(d) {
        if (!this.$d3.event.active) this.simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
      },
      dragged(d) {
        d.fx = this.$d3.event.x;
        d.fy = this.$d3.event.y;
      },
      dragended(d) {
        if (!this.$d3.event.active) this.simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
      }
  }
};

new Vue({
  el: '#app',
  data() {
    return {}
  },
  components: {
    d3ForceGraph
  }
});

.links line {
  stroke: #999;
  stroke-opacity: 0.6;
}

.nodes circle {
  stroke: #fff;
  stroke-width: 1.5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.8.0/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
  <d3-force-graph></d3-force-graph>
</div>

这篇关于如何在VueJS上绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆