哪个数据结构发送到d3.js脚本
Which datastructure to send to d3.js script?
所以我将需要迭代我从数据库中提取的一些信息,并在D3图表中动态渲染它。我需要的两个信息是答案的标题和票数。我现在是这样做的:
def show
@poll = Poll.find(params[:id])
# Mappning answer titles with their votes
gon.poll = @poll.questions[0].answers.map{|answer| [answer.title, answer.votes]}
给出如下结果:
[["Probably not", 4],
["But you're saying there's a chance", 10],
["I just added this...", 7]]
并传递给这个脚本
$(document).ready(function() {
var w = 500;
var h = 420;
var barPadding = 1;
// var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
// 11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var dataset [gon.poll];
// function drawSurvey(){
var svg = d3.select('div.graph')
.append("svg")
.attr("width", w)
.attr("height",h);
// .attr("class", "bar")
// });
svg.selectAll("rect")
.data(dataset)
// Each data point entered into enter() for processing
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length); //Bar width of 20 plus 1 for padding
// tying of each bar as a function to length of set, never runs off screen
})
.attr("y", function(d){
return h-d
})
// Less bars == more width
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d){
return d
})
.attr("fill", "teal");
// }
});
我想知道这是否是处理数据的最有效的方法?我希望每个条都有其投票的高度,其"标题"在x轴上。什么好主意吗?
我将使用的数据结构将是一个对象数组:
[{title: "Probably not", votes: 4},
{title: "But you're saying there's a chance", votes: 10},
{title: "I just added this...", votes: 7}]
然后,在代码的后面:
.attr("y", function(d) {return d.votes;})
和
.attr("height", function(d) {return d.votes;})
对于标题,您可以使用d.title
访问正确的值
相关文章:
- 如何在d3.js中返回路径的y坐标
- 有条件更新d3.js力图中节点的最佳方法
- 使用D3.js计算带有字母间距的文本长度
- D3.js模式不适用于弧形或圆环图
- d3.js Chord图的动态工具提示
- 在D3.js中,有没有任何方法可以将x和y方向上的滚动事件绑定到平移svg
- HTML5FileReader输出到D3.js图表
- D3.js生成有效的SVG,但不显示任何内容
- d3.js:限制画笔的大小
- d3.js用按钮更新条形图工具提示
- 如何为d3.js图表输出组织/嵌套数据
- d3-js快速事件调用问题
- D3.JS向rect添加缩放和列表项
- d3.js圆的半径是否可以由样式属性指定
- 如何在d3.js中自定义事件侦听器
- 在新窗口上使用d3.js
- 如何用d3.js绘制折线图
- 使用dc.js、d3.js和crossfilter引用错误
- D3.js剪辑路径截断了我的图的边缘
- D3.js和坐标系