基本上,我正在尝试重新创建在Excel中创建的图表:
到目前为止,我的代码就是这个......
var theData = [
{
'FB':4,
'Mv':4,
'CB':5,
'SL':3,
'CH':2,
'OT':2,
'Ctrl':6,
'Cmd':6,
'Del':5,
'AA':6,
},
{
'FB':2,
'Mv':3,
'CB':4,
'SL':5,
'CH':4,
'OT':3,
'Ctrl':5,
'Cmd':6,
'Del':6,
'AA':5,
},
etc...
];
var margin = {top:10, right:10, bottom:30, left:40},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(d3.keys(theData[0]))
.rangeRoundBands([0, width]);
var y = d3.scale.linear()
.domain([2,8])
.range([height,0]);
var xAx = d3.svg.axis()
.scale(x)
.orient('bottom')
var yAx = d3.svg.axis()
.scale(y)
.orient('left')
.ticks(3);
var svgContainer = d3.select('#d3Stuff').append('svg')
.attr('width',width + margin.left + margin.right)
.attr('height',height + margin.top + margin.bottom)
.style('border','1px solid black')
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svgContainer.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAx)
.append("text")
.attr("class", "label")
.attr("x", width)
.attr("y", -6)
.style("text-anchor", "end");
svgContainer.append("g")
.attr("class", "y axis")
.call(yAx)
.append("text")
.attr("class", "label")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end");
我在尝试为数据对象中的值显示圆圈时遇到问题。显然,我希望它们与x轴键对齐。如果我至少可以显示初始值,我可以稍后计算最小值/最大值/平均值。
以下是代码创建的内容:
任何帮助都会很棒!
答案 0 :(得分:1)
您可以使用序数比例使用键找到任何圆的x位置(因为序数域由键组成)。例如x("FB")
,x("Mv")
等
要创建圆圈,您需要使用enter,update,exit stuff以典型的d3方式绑定到数组。
由于您的数据是散列而不是数组,因此您需要先将其转换为数组形式。使用d3.map()
与theData
一起使用[]
非常容易(我建议删除theData
内部哈希周围的数组d3.map(theData[0]).entries()
/* returns [
{
"key": "FB",
"value": 4
},
{
"key": "Mv",
"value": 4
},
{
"key": "CB",
"value": 5
},
{
"key": "SL",
"value": 3
},
{
"key": "CH",
"value": 2
},
...
]"
,因为它并不是data(...)
。做什么,但仍然):
.attr("x", function(d) { return x(d.key); })
获得此关联数组后,您可以执行常规的{{1}}绑定,附加圆圈,然后使用类似
的方式对其进行定位{{1}}