I am very new to d3 charts. I have this code that creates donut charts. However, unable to change colors. could some one help ?
<body>
<div id="chart"></div>
<script src="d3.v3.min.js"></script>
<script>
(function(d3) {
'use strict';
var dataset = [
{ label: 'Abulia', count: 10 },
{ label: 'Betelgeuse', count: 20 },
{ label: 'Cantaloupe', count: 30 },
{ label: 'Dijkstra', count: 40 }
];
var width = 360;
var height = 360;
var radius = Math.min(width, height) / 3.5;
var donutWidth = 50; // NEW
var color = d3.scale.category20b();
var svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var arc = d3.svg.arc()
.innerRadius(radius - donutWidth) // NEW
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function(d) { return d.count; })
.sort(null);
var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(d.data.label);
});
})(window.d3);
</script>
</body>
</html>
I would like to get donut with these colors #65C400 , #2290EE , #FFC096 .
Is there any other way to create a donut chart with custom values and colors ?? someone pls help.
thanks in advance.
Use ordinal color scales.
var color = d3.scale.ordinal()
.domain(["Abulia", "Betelgeuse", "Cantaloupe","Dijkstra"])
.range(["#65C400" , "#2290EE" , "#FFC096", "#5e5e5e"]);
var dataset = [{ label: 'Abulia', count: 10 }, { label: 'Betelgeuse', count: 20 }, { label: 'Cantaloupe', count: 30 }, { label: 'Dijkstra', count: 40 }]; var color = d3.scale.ordinal() .domain(["Abulia", "Betelgeuse", "Cantaloupe","Dijkstra"]) .range(["#65C400" , "#2290EE" , "#FFC096", "#5e5e5e"]); var width = 360; var height = 360; var radius = Math.min(width, height) / 3.5; var donutWidth = 50; // NEW var svg = d3.select('#chart') .append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')'); var arc = d3.svg.arc() .innerRadius(radius - donutWidth) // NEW .outerRadius(radius); var pie = d3.layout.pie() .value(function(d) { return d.count; }) .sort(null); var path = svg.selectAll('path') .data(pie(dataset)) .enter() .append('path') .attr('d', arc) .attr('fill', function(d, i) { return color(d.data.label); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <div id="chart"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.