0

How could i draw pie chart or bar chart in d3js with json data like these ?

{"ratings": {"2": 1, "3": 3, "4": 12, "1": 8, "5": 33} }

or these:

{"languages": {"1": 35, "2": 22}}

please help!

3
  • What have you tried? There are lots and lots of examples of both pie charts and bar charts. Commented Dec 14, 2015 at 0:51
  • i get these data from url in angularjs by $http.get, access the object ratings and trying to draw these ratings in d3 pie chart but i need to assign the keys and values for functions x,y how could i do that. If i get the ratings data and edit it to be like this : [ {key: "2",y: 1}, {key: "3",y: 3}, {key: "4",y: 12}, {key: "1",y: 8}, {key: "5",y: 33} ] it works but i need a way to edit data to be like this. @LarsKotthoff Commented Dec 14, 2015 at 1:13
  • So you could do something like data = []; for(key in json) { data.push({key: key, value json[key]}); } Commented Dec 14, 2015 at 2:50

1 Answer 1

2

Convert data as shown below and use in pie chart.

var actualData = {
  "ratings": {
    "2": 1,
    "3": 3,
    "4": 12,
    "1": 8,
    "5": 33
  }
};

var data = d3.values(actualData.ratings).map(function(v, i) {
  return {
    key: i + 1,
    value: v
  }
});

var width = 960,
  height = 500,
  radius = Math.min(width, height) / 2;

var color = d3.scale.ordinal()
  .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var arc = d3.svg.arc()
  .outerRadius(radius - 10)
  .innerRadius(0);

var labelArc = d3.svg.arc()
  .outerRadius(radius - 40)
  .innerRadius(radius - 40);

var pie = d3.layout.pie()
  .sort(null)
  .value(function(d) {
    return d.value;
  });

var svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var actualData = {
  "ratings": {
    "2": 1,
    "3": 3,
    "4": 12,
    "1": 8,
    "5": 33
  }
};

var data = d3.values(actualData.ratings).map(function(v, i) {
  return {
    key: i + 1,
    value: v
  }
});

console.log(data)

var g = svg.selectAll(".arc")
  .data(pie(data))
  .enter().append("g")
  .attr("class", "arc");

g.append("path")
  .attr("d", arc)
  .style("fill", function(d) {
    return color(d.data.key);
  });

g.append("text")
  .attr("transform", function(d) {
    return "translate(" + labelArc.centroid(d) + ")";
  })
  .attr("dy", ".35em")
  .text(function(d) {
    return d.data.key;
  });

function type(d) {
  d.value = +d.value;
  return d;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

thaaank yoooou <33333

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.