我们正在尝试创建组件/模块/等。获取自定义数据属性的值并创建基于D3的饼图,显示基于该数据属性的百分比。
具有自定义数据属性的div元素示例:
////// HTML
<div class="donut" data-donut="22"></div>
<div class="donut" data-donut="48"></div>
<div class="donut" data-donut="75></div>
以下是CSS:
////// CSS
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
width: 960px;
padding-top: 20px;
background-color: #012647;
}
text {
font-family: "RamaGothicM-Heavy",Impact,Haettenschweiler,"Franklin Gothic Bold",Charcoal,"Helvetica Inserat","Bitstream Vera Sans Bold","Arial Black",sans-serif;
font-size: 7rem;
font-weight: 400;
line-height: 16rem;
fill: #1072b8;
}
.donut {
width: 29rem;
height: 29rem;
margin: 0 auto;
}
path.color0 {
fill: #1072b8;
}
path.color1 {
fill: #35526b;
}
我们尝试转换为可重用的compunent的D3.js / jQuery示例如下。 (要查看完整的工作示例,请转到此链接 - http://codepen.io/anon/pen/JgyCz)
////// D3.js
var duration = 500,
transition = 200;
drawDonutChart(
'.donut',
$('.donut').data('donut'),
290,
290,
".35em"
);
function drawDonutChart(element, percent, width, height, text_y) {
width = typeof width !== 'undefined' ? width : 290;
height = typeof height !== 'undefined' ? height : 290;
text_y = typeof text_y !== 'undefined' ? text_y : "-.10em";
var dataset = {
lower: calcPercent(0),
upper: calcPercent(percent)
},
radius = Math.min(width, height) / 2,
pie = d3.layout.pie().sort(null),
format = d3.format(".0%");
var arc = d3.svg.arc()
.innerRadius(radius - 20)
.outerRadius(radius);
var svg = d3.select(element).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset.lower))
.enter().append("path")
.attr("class", function(d, i) { return "color" + i })
.attr("d", arc)
.each(function(d) { this._current = d; }); // store the initial values
var text = svg.append("text")
.attr("text-anchor", "middle")
.attr("dy", text_y);
if (typeof(percent) === "string") {
text.text(percent);
}
else {
var progress = 0;
var timeout = setTimeout(function () {
clearTimeout(timeout);
path = path.data(pie(dataset.upper)); // update the data
path.transition().duration(duration).attrTween("d", function (a) {
// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by d3.interpolate.
var i = d3.interpolate(this._current, a);
var i2 = d3.interpolate(progress, percent)
this._current = i(0);
return function(t) {
text.text( format(i2(t) / 100) );
return arc(i(t));
};
}); // redraw the arcs
}, 200);
}
};
function calcPercent(percent) {
return [percent, 100-percent];
};
答案 0 :(得分:0)
我尝试将Backbone.js
与我的图表一起使用(我使用了NVD3.js)。
这是关于此
的question on SO@jtuulos的
D3 + Backbone(我个人认为这个链接对于理解扩展父类和实例化的整个概念非常有用)
- 醇>
我能够为我使用的常用图表类型创建父图表类,然后只需创建该图表的实例,以便我可以随时重复使用它。在尝试维护图表时让生活更轻松。
可能不是最好的方法,但我发现这种方式非常有用。