D3.js 将对象绑定到数据并附加每个键 [英] D3.js binding an object to data and appending for each key

查看:23
本文介绍了D3.js 将对象绑定到数据并附加每个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 D3.js 新手,我正在学习如何处理数据.

I'm a D3.js newbie and I'm learning how to play around with data.

假设我有一个以名称为键的对象,每个键都有一个数字数组,如下所示:

Let's say I have an object with names as keys, and each key has an array of numbers like this:

var userdata = {
    'John' : [0, 1, 3, 9, 8, 7],
    'Harry': [0, 10, 7, 1, 1, 11],
    'Steve': [3, 1, 4, 4, 4, 17],
    'Adam' : [4, 77, 2, 13, 11, 13]
};

对于每个用户,我想附加一个 SVG 对象,然后用该用户的值数组绘制线条.

For each user, I would like to append an SVG object and then plot the line with the array of values for that user.

所以这是我根据教程对它的外观的假设,但我知道这是不正确的.这是为了展示我有限的知识并更好地了解我在做什么:

So here is my assumption of how that would look based on tutorials, but I know it is incorrect. This is to show my limited knowledge and give better understanding of what I'm doing:

首先我应该创建这条线

var line = d3.svg.line().interpolate('basis');

然后我想将数据绑定到我的正文并为每个键附加一个 svg 元素:

Then I want to bind the data to my body and append an svg element for each key:

d3.select('body')
    .selectAll('svg')
    .data(userdata)
    .enter()
    .append('svg')
    .append(line)
    .x(function(d, i) { return i; })
    .y(function(d) { return d[i]; });

所以我很亲近吗??

推荐答案

这是另一个类似于 mbeasley 的示例:http://jsfiddle.net/2N2rt/15/ 添加轴、颜色,并将图表右侧向上翻转.首先,我稍微调整了您的数据.如果您有一组值并且我使用键来使获取 namevalues 属性变得更容易,则效果最佳.

Here's another example similar to mbeasley's: http://jsfiddle.net/2N2rt/15/ which adds axis, colors, and flips the chart right side up. First, I massaged your data just a little bit. Works the best if you have an array of values and I used keys to make getting to the name and values properties easier.

var data = [
    {name: 'John', values: [0,1,3,9, 8, 7]},
    {name: 'Harry', values: [0, 10, 7, 1, 1, 11]},
    {name: 'Steve', values: [3, 1, 4, 4, 4, 17]},
    {name: 'Adam', values: [4, 77, 2, 13, 11, 13]}
];

通常在 d3 中,您可以像这样设置图表,这决定了实际图表的大小和周围的边距.

Generally in d3 you set up the chart like this which determines the size of the actual graph and the surrounding margins.

var margin = {top: 20, right: 80, bottom: 30, left: 50},
    width = 640 - margin.left - margin.right,
    height = 380 - margin.top - margin.bottom;

然后您可以根据您的数据创建您的比例.尽管您不必创建它们,但它们通过将值转换为点使图表上的元素定位变得更加容易.domain 是数据的最小值和最大值,而 range 是图形大小的最小值和最大值.请注意,y 轴range 被反转,将 (0,0) 放在左下角(通常 y 轴的 0 位于顶部).

Then you can create your scales based on your data. Though you don't have to create them, they make positioning elements on the chart much easier by converting values to points. The domain is the min and max values that your data has, while the range is the min and max values of the size of your graph. Note that the range for the y axis gets reversed which puts (0,0) in the bottom left hand corner (usually 0 for the y axis is at the top).

var x = d3.scale.linear()
    .domain([0, d3.max(data, function(d) { return d.values.length - 1; })])
    .range([0, width]);

var y = d3.scale.linear()
    .domain([d3.min(data, function(d) { return d3.min(d.values); }),
             d3.max(data, function(d) { return d3.max(d.values); })])
    .range([height, 0]);

d3 有几个功能可以为您自动创建色阶.只需使用您要使用的键和颜色数量进行设置(我认为有 10 和 20 种颜色选项).

d3 has a couple of features for automatically creating color scales for you. Just set it up with the keys that you want to use and the number of colors (I think there are 10 and 20 color options).

var color = d3.scale.category10()
    .domain(d3.keys(data[0]).filter(function(key) { return key === "name"; }));

这里我们使用我们的比例来设置 x 和 y 轴.轴有很多不同的选项.TickFormat 可以方便地更改刻度的外观,d3.format 有很多不同的选项,因此您很少需要创建自定义格式化程序.

Here we use our scales to setup the x and y axis. There are lots of different options for the axes. TickFormat is handy to change how the ticks look, d3.format has lots of different options so that you rarely have to create a custom formatter.

var xAxis = d3.svg.axis()
    .scale(x)
    .tickFormat(d3.format('d'))
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

这里我们创建了一个可重用的函数,它知道如何画一条线.稍后我们会将每个人的每个数据点传递到 line 函数中.请注意,d 保存了我们正在绘制的当前值集,而 i 是我们原始数据数组中当前值的索引.

Here we create a reusable function that knows how to draw a line. We'll pass each datapoint for each person into the line function later on. Note that d holds the current set of values that we are graphing and i is the index of the current values within our original data array.

var line = d3.svg.line()
    .interpolate("basis")
    .x(function(d, i) { return x(i); })
    .y(function(d, i) { return y(d); });

最后,我们可以开始向图表添加内容,首先创建和定位主要的 svg 元素.

Finally we can start adding things to our chart, first creating and positioning the main svg element.

var svg = d3.select("#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

然后附加每个轴.

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);

我们为每个人附加一个组 (g) 并将数据与该组相关联.我们将在绘制线条时使用这些数据.我们提供了一个 class 以便我们以后可以根据需要设置图表样式.

We append a group (g) for each person and associate the data with the group. We'll use this data when we draw the lines. We provide a class so that we can style the chart later if we want to.

  var people = svg.selectAll(".people")
      .data(data)
    .enter().append("g")
      .attr("class", "people");

然后最后为每个人画线.

Then finally draw the lines for each person.

  people.append("path")
      .attr("class", "line")
      .attr("d", function(d) { return line(d.values); })
      .style("stroke", function(d) { return color(d.name); });

我使用您的数据回答了另一个关于在您有负值时绘制网格的问题.您可以在 http://jsfiddle.net/2y3er/2/ 上看到该图表.

I used your data to answer another question about drawing a grid when you have negative values. You can see that graph at http://jsfiddle.net/2y3er/2/.

这篇关于D3.js 将对象绑定到数据并附加每个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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