我是 D3 的新手,遇到了一些问题。想知道是否有人可以提供帮助。
我正在尝试使用 d3 创建分组堆栈图。该图的性质是每组有 2 个柱,第二个柱的值取决于第一个柱。我希望第二个栏是我在第一个栏上的分割。一个简单的例子是,如果第一条上的值是 {x: 0, y: 3, y0: 0},第二条应该是 {x: 0, y: 1, y0: 0}, {x: 0, y: 1, y0: 1}, {x: 0, y: 1, y0: 2}
因此对于第一个条形图绘制的数据:
{
"series": "A",
"values": [{
"x": 0,
"y": 1,
},
{
"x": 1,
"y": 2,
},
{
"x": 2,
"y": 3,
},
{
"x": 3,
"y": 1,
},
{
"x": 4,
"y": 3,
}
]},
{
"series": "B",
"values": [{
"x": 0,
"y": 3,
},
{
"x": 1,
"y": 1,
},
{
"x": 2,
"y": 1,
},
{
"x": 3,
"y": 5,
},
{
"x": 4,
"y": 1,
}]
}
我将为第二个堆叠条形图设置这些值:
{
"series": "A",
"values":
[ { x: 0, y: 1, y0: 0 },
{ x: 1, y: 1, y0: 0 },
{ x: 1, y: 1, y0: 1 },
{ x: 2, y: 1, y0: 0 },
{ x: 2, y: 1, y0: 1 },
{ x: 2, y: 1, y0: 2 },
{ x: 3, y: 1, y0: 0 },
{ x: 4, y: 1, y0: 0 },
{ x: 4, y: 1, y0: 1 },
{ x: 4, y: 1, y0: 2 }]
},
{
"series": "B",
"values":
[
{ x: 0, y: 1, y0: 1 },
{ x: 0, y: 1, y0: 2 },
{ x: 0, y: 1, y0: 3 },
{ x: 1, y: 1, y0: 1 },
{ x: 2, y: 1, y0: 1 },
{ x: 3 y: 1, y0: 1 },
{ x: 3, y: 1, y0: 2 },
{ x: 3, y: 1, y0: 3 },
{ x: 3, y: 1, y0: 4 },
{ x: 3, y: 1, y0: 5 },
{ x: 4, y: 1, y0: 1 },
]
}
我使用了一些我可以从我看到的例子中找到的代码,并试图让它工作。这是我到目前为止能够做的:
如果有任何帮助,我将不胜感激。谢谢
最佳答案
这是我使用您提供的数据整理的 fiddle :https://jsfiddle.net/thatoneguy/nrjt15aq/8/
数据:
var data = [
{ x: 0, y: 1, yheight: 0 },
{ x: 1, y: 1, yheight: 0 },
{ x: 1, y: 1, yheight: 1 },
{ x: 2, y: 1, yheight: 0 },
{ x: 2, y: 1, yheight: 1 },
{ x: 2, y: 1, yheight: 2 },
{ x: 3, y: 1, yheight: 0 },
{ x: 4, y: 1, yheight: 0 },
{ x: 4, y: 1, yheight: 1 },
{ x: 4, y: 1, yheight: 2 }
];
需要对这些数据进行排序,以便将其正确地提供给堆积条形图。例如,来自此链接:https://bl.ocks.org/mbostock/3886208如您所见,数据看起来像这样(我将其转换为 json):
{
"State": "WA",
"Under 5 Years": 433119,
"5 to 13 Years": 750274,
"14 to 17 Years": 357782,
"18 to 24 Years": 610378,
"25 to 44 Years": 1850983,
"45 to 64 Years": 1762811,
"65 Years and Over": 783877
}
你的地方是分开的。所以,我编辑了你的(现在是手工编辑,但可以编写一个函数来执行此操作)。所以你的数据现在看起来像这样:
var data = [
{ x: 0, yHeight0: 1, yHeight1: 0, yHeight2: 0 },
{ x: 1, yHeight0: 1, yHeight1: 1, yHeight2: 0 },
{ x: 2, yHeight0: 1, yHeight1: 1, yHeight2: 2 },
{ x: 3, yHeight0: 1, yHeight1: 0, yHeight2: 0 },
{ x: 4, yHeight0: 1, yHeight1: 1, yHeight2: 2 }
]
注意不同的 yHeights。这些代表您数据中的不同高度,但我已将它们全部分组。根据具有相同的 x 值将它们分组。
现在我要花点时间解释一切,但我会解释基础知识。
切记,我已经脱离了上面链接的示例。该示例具有此颜色域:
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
他们知道他们将拥有多少不同的堆栈。我暂时保留了这些,但这些可以更改。然后使用此比例为数据提供更多属性:
color.domain(d3.keys(data[4]).filter(function(key) {
return key !== "x";
}));
上面的函数是返回所有不同的堆栈(在你的例子中是 yHeights)。以下函数使用这些属性并为您提供属性以帮助确定这些堆栈的高度和 y 位置。
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) {
return {
name: name,
y0: y0,
y1: y0 += +d[name]
};
});
d.total = d.ages[d.ages.length - 1].y1;
});
现在绘制它们:
var firstRects = state.selectAll("firstrect")
.data(function(d) {
return d.ages;
})
.enter().append("rect")
.attr("width", x.rangeBand() / 2)
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); })
.style('stroke', 'black');
这只为您提供了一个简单的堆叠条形图,但您想要另一个带有数字的条形图。所以我通过将另一个条形图附加到同一轴来做到这一点,如下所示:
var secondRects = state.selectAll("secondrect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", barWidth)
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) {
if (y(d.y0) - y(d.y1)) d.barHeight = y(d.y0) - y(d.y1); //this sets a height variable to be used later
return y(d.y0) - y(d.y1);
})
.style("fill", 'white')
.style('stroke', 'black')
.attr("transform", function(d) {
return "translate(" + (x.rangeBand() / 2) + ",0)";
});
现在是关于这个的数字:
var secondRectsText = state.selectAll("secondrecttext")
.data(function(d) {
for (i = 0; i < d.ages.length; i++) {
if (isNaN(d.ages[i].y0) || isNaN(d.ages[i].y1)) {
d.ages.splice(i--, 1);
}
}
console.log('dages', d.ages);
return d.ages;
})
.enter().append("text")
.attr("width", barWidth)
.attr("y", function(d) {
return y(d.y1);
})
.attr("transform", function(d) {
if(d.barHeight){ //if it hasnt got barheight it shouldnt be there
return "translate(" + (barWidth + barWidth / 2) + "," + d.barHeight/2 + ")";
} else {
return "translate(" + 5000 + "," + 5000 + ")";
}
})
.text(function(d, i) {
return i;
});
数据设置中的检查是为了不使用任何空值。我可以永远解释我所做的事情,但希望您能充分理解代码以将其实现到您的代码中。
从这里开始,我将继续创建一个函数来组织您的数据,即将具有相同 x 值的所有值分组,这样您就不必手动编辑。
希望对您有所帮助,再次为很长的回答道歉:P
以下是所有代码,以防 fiddle 崩溃:
var data3 = [
{ x: 0, y: 1, yheight: 0 },
{ x: 1, y: 1, yheight: 0 },
{ x: 1, y: 1, yheight: 1 },
{ x: 2, y: 1, yheight: 0 },
{ x: 2, y: 1, yheight: 1 },
{ x: 2, y: 1, yheight: 2 },
{ x: 3, y: 1, yheight: 0 },
{ x: 4, y: 1, yheight: 0 },
{ x: 4, y: 1, yheight: 1 },
{ x: 4, y: 1, yheight: 2 }
];
var data = [
{ x: 0, yHeight0: 1, yHeight1: 0, yHeight2: 0 },
{ x: 1, yHeight0: 1, yHeight1: 1, yHeight2: 0 },
{ x: 2, yHeight0: 1, yHeight1: 1, yHeight2: 2 },
{ x: 3, yHeight0: 1, yHeight1: 0, yHeight2: 0 },
{ x: 4, yHeight0: 1, yHeight1: 1, yHeight2: 2 }
]
//console.log(newArray)
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = 800 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#90C3D4", "#E8E8E8", "#DB9A9A", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("body").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 + ")");
//below i purposely pick data[4] as I know thats the longest dataset so it gets all the yHeights
color.domain(d3.keys(data[4]).filter(function(key) {
return key !== "x";
}));
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) {
return {
name: name,
y0: y0,
y1: y0 += +d[name]
};
});
d.total = d.ages[d.ages.length - 1].y1;
});
x.domain(data.map(function(d) {
return d.x;
}));
y.domain([0, d3.max(data, function(d) {
return d.total;
})]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Tally");
console.log('test')
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) {
return "translate(" + x(d.x) + ",0)";
});
var firstRects = state.selectAll("firstrect")
.data(function(d) {
return d.ages;
})
.enter().append("rect")
.attr("width", x.rangeBand() / 2)
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); })
.style('stroke', 'black');
var barWidth = x.rangeBand() / 2;
var barHeight;
var secondRects = state.selectAll("secondrect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", barWidth)
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) {
if (y(d.y0) - y(d.y1)) d.barHeight = y(d.y0) - y(d.y1);
return y(d.y0) - y(d.y1);
})
.style("fill", 'white')
.style('stroke', 'black')
.attr("transform", function(d) {
return "translate(" + (x.rangeBand() / 2) + ",0)";
});
var secondRectsText = state.selectAll("secondrecttext")
.data(function(d) {
for (i = 0; i < d.ages.length; i++) {
if (isNaN(d.ages[i].y0) || isNaN(d.ages[i].y1)) {
d.ages.splice(i--, 1);
}
}
console.log('dages', d.ages);
return d.ages;
})
.enter().append("text")
.attr("width", barWidth)
.attr("y", function(d) {
return y(d.y1);
})
.attr("transform", function(d) {
if(d.barHeight){ //if it hasnt got barheight it shouldnt be there
return "translate(" + (barWidth + barWidth / 2) + "," + d.barHeight/2 + ")";
} else {
return "translate(" + 5000 + "," + 5000 + ")";
}
})
.text(function(d, i) {
return i;
});
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 20 + ")";
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) {
return d;
});body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
编辑:
这是一个 fiddle ,它可以从所提供的图像中准确地为您提供您想要的东西(有点笨拙,但它有效:)):https://jsfiddle.net/thatoneguy/nrjt15aq/10/
var data3 = [
{ x: 0, y: 1, yheight: 0 },
{ x: 1, y: 1, yheight: 0 },
{ x: 1, y: 1, yheight: 1 },
{ x: 2, y: 1, yheight: 0 },
{ x: 2, y: 1, yheight: 1 },
{ x: 2, y: 1, yheight: 2 },
{ x: 3, y: 1, yheight: 0 },
{ x: 4, y: 1, yheight: 0 },
{ x: 4, y: 1, yheight: 1 },
{ x: 4, y: 1, yheight: 2 }
];
var data = [
{ x: 0, yHeight0: 1, yHeight1: 0, yHeight2: 0 },
{ x: 1, yHeight0: 1, yHeight1: 1, yHeight2: 0 },
{ x: 2, yHeight0: 1, yHeight1: 1, yHeight2: 2 },
{ x: 3, yHeight0: 1, yHeight1: 0, yHeight2: 0 },
{ x: 4, yHeight0: 1, yHeight1: 1, yHeight2: 2 }
]
//console.log(newArray)
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = 800 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#90C3D4", "#E8E8E8", "#DB9A9A", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("body").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 + ")");
//below i purposely pick data[4] as I know thats the longest dataset so it gets all the yHeights
color.domain(d3.keys(data[4]).filter(function(key) {
return key !== "x";
}));
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) {
return {
name: name,
y0: y0,
y1: y0 += +d[name]
};
});
d.total = d.ages[d.ages.length - 1].y1;
});
x.domain(data.map(function(d) {
return d.x;
}));
y.domain([0, d3.max(data, function(d) {
return d.total;
})]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Tally");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) {
return "translate(" + x(d.x) + ",0)";
});
var barWidth = x.rangeBand() / 2;
var barHeight;
var boolTest = true;
var firstRects = state.selectAll("firstrect")
.data(function(d) {
return d.ages;
})
.enter().append("rect")
.attr("width", x.rangeBand() / 2)
.attr("y", function(d) {
if(boolTest){ boolTest=false; barHeight = y(d.y0) - y(d.y1)}
if((y(d.y0) - y(d.y1)) != 0){
if(barHeight > (y(d.y0) - y(d.y1))){ barHeight = y(d.y0) - y(d.y1)}
}
return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); })
.style('stroke', 'black');
function getHigheset(thisArray){
var count = 0;
for(var i=0;i<thisArray.length;i++){
if(count<thisArray[i].y1){ count = thisArray[i].y1}
}
return count;
}
function makeArray(count){
var newArray = [];
for(i=0;i<count;i++){
newArray.push(i)
}
return newArray;
}
var secondRects = state.selectAll("secondrect")
.data(function(d) {
var thisData = makeArray(getHigheset(d.ages));
return makeArray(getHigheset(d.ages))
})
.enter().append("rect")
.attr("width", barWidth)
.attr("y", function(d,i) {
return y(d)
})
.attr("height", function(d) {
return barHeight
})
.style("fill", 'white')
.style('stroke', 'black')
.attr("transform", function(d) {
return "translate(" + (x.rangeBand() / 2) + "," + (-barHeight)+" )";
});
var secondRectsText = state.selectAll("secondrecttext")
.data(function(d) {
for (i = 0; i < d.ages.length; i++) {
if (isNaN(d.ages[i].y0) || isNaN(d.ages[i].y1)) {
d.ages.splice(i--, 1);
}
}
//return d.ages;
return makeArray(getHigheset(d.ages))
})
.enter().append("text")
.attr("width", barWidth)
.attr("y", function(d, i) {
return y(d);
})
.attr("transform", function(d) {
if(barHeight){ //if it hasnt got barheight it shouldnt be there
return "translate(" + (barWidth + barWidth / 2) + "," + (barHeight/2 -barHeight) + ")";
} else {
return "translate(" + 5000 + "," + 5000 + ")";
}
})
.text(function(d, i) {
return i;
});
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 20 + ")";
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) {
return d;
});body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
关于javascript - 使用 D3.js 的分组堆栈图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36742651/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h