我需要使用d3.js为3个城市3年的降雨分类数据制作散点图:
Year1 Year2 Year3
NY CA TX NY CA TX NY CA TX
17 20 15 23 10 11 14 15 17
16 18 12 15 21 22 20 18 19
13 22 16 17 25 18 17 25 18
19 18 13 16 21 20 22 15 16
(注意:数据和图表在这里不匹配,它只是解释我的查询) 我是d3.js的新手。我尝试过一些简单散点图和条形图的教程,但我无法弄清楚如何显示像这样的分类图。
任何帮助我入门的人都将不胜感激。
[编辑] 我重新安排了tsv文件中的数据,看起来像这样:
year state rain
1 NY 17
1 NY 16
1 NY 13
1 CA 20
1 TX 15
2 NY 23
3 CA 10
3 TX 14
3 NY 13
似乎有些问题。我得到"意外的值NaN解析cx属性。"和cy一样我知道如何解决它?
var newArray = new Array();
// draw the scatterplot
svg.selectAll("dot") // provides a suitable grouping for the svg elements that will be added
.data(data) // associates the range of data to the group of elements
.enter().append("circle") // adds a circle for each data point
.attr("r", 5) // with a radius of 3.5 pixels
.attr("cx", function (d) {
newArray = data.filter( function (el) {
return el.category == "NY";
});
return xScale(newArray.rain);
}) // at an appropriate x coordinate
.attr("cy", function (d) {
return yScale(newArray.year);
}) // and an appropriate y coordinate
.style("fill", color(9));
答案 0 :(得分:0)
在d3中有多种方法可以做到这一点,有自己的优点和缺点。
坦率地说,这个问题对于这个论坛来说太模糊了,但我发现你提出的挑战很有意思。所以我嘲笑了一种做Y轴的方法。 http://jsfiddle.net/7Jpw2/2/它使用状态的序数比例和覆盖在第一个之上的年份的另一个序数比例
这可能不是一个完整的答案,但它应该让你走得很远。
var categories = [
{ year:3, state:'NY' },
{ year:3, state:'CA' },
{ year:3, state:'TX' },
{ year:2, state:'NY' },
{ year:2, state:'CA' },
{ year:2, state:'TX' },
{ year:1, state:'NY' },
{ year:1, state:'CA' },
{ year:1, state:'TX' }
];
// IMPORTANT! This is a way to make each state @ year unique, by returning a concatenation of state and year
categories.forEach(function(cat) {
cat.toString = function() { return this.state + '_' + this.year }
});
// These year values should ideally be extracted from categories array above, not hardcoded as below
var years = ['Year 1', 'Year 2', 'Year 3'];
var svg = d3.select('body').append('svg');
// Create 2 axes:
// First a state-name axis
// Then a year axis, in which everything except the text is invisible (via css fill:none)
var statesScale = d3.scale.ordinal()
.domain(categories)
.rangeBands([50,300]);
var statesAxis = d3.svg.axis()
.orient('left')
.tickFormat(function(d) { return d.state; })
.scale(statesScale)
var yearsScale = d3.scale.ordinal()
.domain(years)
.rangeBands([50,300]);
var yearsAxis = d3.svg.axis()
.orient('left')
.tickSize(50) // Distances the year label from state labels
.scale(yearsScale)
svg.append('g')
.attr('class', 'states-axis')
.attr('transform', 'translate(150,0)')
.call(statesAxis);
svg.append('g')
.attr('class', 'years-axis')
.attr('transform', 'translate(150,0)')
.call(yearsAxis);