简体   繁体   中英

D3 javascript color from JSON attribute

Using D3 Javascript and JSON, I need to create something very similar to:

http://bl.ocks.org/mbostock/4063550

The JSON file (copied from website) looks something like:

{
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "size": 3938},
      {"name": "CommunityStructure", "size": 3812},
      {"name": "HierarchicalCluster", "size": 6714},
      {"name": "MergeEdge", "size": 743}
     ]
    },

Now instead of the "size" in the code above, I have "score" (ie "score": 3).

What I want to achieve is the diagram similar to the website, but the difference is that is the score is over a certain threshold (eg >5), I want the small blue circle to be of a certain color (ie red).

I know this needs to be updated in the index.html file, but I just don't know how to get around to doing that. Any pointers would be appreciated!

Thanks!

All you need to do this is to slightly modify the code that appends the circle s. You need to change the snippet

node.append("circle")
  .attr("r", 4.5);

to

node.append("circle")
  .style("stroke", function(d) { return d.score > 5 ? "red" : "steelblue"; })
  .attr("r", 4.5);

You can obviously apply something like this to eg the fill colour in the same way. If you have a larger number of different colours and thresholds, it might be worth investigating using a scale instead of a conditional statement.

Change your JSON like so:

{
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "score": 3938},
      {"name": "CommunityStructure", "score": 3812},
      {"name": "HierarchicalCluster", "score": 6714},
      {"name": "MergeEdge", "score": 743}
     ]
    },

Now use a function to check for the condition in the data and set the style for the circle:

node.append("circle")
      .attr("r", 4.5)
      .style("fill",function(d){
          return ((d.score > 5)?"red":"blue");
      });

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM