The code below requires the JSON object to specify "value" and "label". I want to make this so that a pie chart can be created with any key names.
//Regular pie chart example
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.showLabels(true);
d3.select("#chart svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
The above function can be modified to return d.fruit and d.number to create a pie chart of a JSON object [{"fruit": "apple", "number": 1}], but I would like this to work for any JSON object, regardless of the key names.
#chart svg {
height: 400px;
}
</style>
<div id="chart">
<svg></svg>
</div>
</head>
<body>
<script>
//Regular pie chart example
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.showLabels(true);
d3.select("#chart svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
//Donut chart example
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.showLabels(true) //Display pie labels
.labelThreshold(.05) //Configure the minimum slice size for labels to show up
.labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
.donut(true) //Turn on Donut mode. Makes pie chart look tasty!
.donutRatio(0.35) //Configure how big you want the donut hole size to be.
;
d3.select("#chart2 svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
//Pie chart example data. Note how there is only a single array of key-value pairs.
function exampleData() {
return [
{"value":"1","label":"apples"},{"value":"2","label":"bananas"}
];
}
</script>
</body>
</html>