来自JSON的D3颜色十六进制

时间:2019-04-11 15:54:15

标签: javascript json d3.js

我正在尝试用$(document).ready(function() { $(".item-gallery a").fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 800, 'speedOut' : 200, 'overlayShow' : false, 'cyclic' : true, }).click(function(e){ var image_name = $(this).attr('href'); $(".img-big-wrap div a img").attr('src',image_name); }) }); //END OF DOCUMENT READY function calcular(){ let select_value = document.getElementById("selector").value; let amount = select_value*29.99; $('#big_valor').html(amount); } 中的3D.js颜色填充hexdecimal中的节点。因此,这里是json文件的示例。

json

{"nodes":[{"name":"GCF_000008865.1", "choose":"1", "organism_name":"Escherichia coli O157:H7 str. Sakai", "classification":"cellular organisms; Bacteria; Proteobacteria; Gammaproteobacteria; Enterobacterales; Enterobacteriaceae; Escherichia; Escherichia coli; Escherichia coli O157:H7;", "lineage":"bacteria>proteobacteria>gammaproteobacteria", "genera":"Escherichia", "colorsamp":"#E7298A", "id":"GCF_000008865.1"}, {"name":"GCF_000006945.2", "choose":"1", "organism_name":"Salmonella enterica subsp. enterica serovar Typhimurium str. LT2","classification":"cellular organisms; Bacteria; Proteobacteria; Gammaproteobacteria; Enterobacterales; Enterobacteriaceae; Salmonella; Salmonella enterica; Salmonella enterica subsp. enterica; Salmonella enterica subsp. enterica serovar Typhimurium;", "lineage":"bacteria>proteobacteria>gammaproteobacteria", "genera":"Salmonella", "colorsamp":"#CCEBC5", "id":"GCF_000006945.2"}, 字段具有十六进制的颜色代码,因此我尝试以这种方式填充:

colorsamp

除非// draw circles for each node var node = svg.append("g") .attr("class","nodes") .selectAll("circle") .data(graph.nodes) // circle .enter().append("circle") // radius of the circle .attr("r", (d) => { if (d.choose == 0 ) {return 5;} if (d.choose == 1) {return 8;} }) .attr("fill", function(d) { d.colorsamp; }) .call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); // add text of mouse over, show name and value (% or raw?) node.append("title") .text(function(d) { return (d.name+ "\n" + d.lineage + " (" + d.genera +")"); }); 函数不会用颜色填充节点,否则所有接缝都可以正常工作。

不好意思:我正在使用fill,因为D3.js v4无法使用我的代码。

预先感谢

1 个答案:

答案 0 :(得分:2)

您不会在填充函数中返回colorsamp

.attr("fill", function(d) { d.colorsamp; })

应该是

.attr("fill", function(d) { return d.colorsamp; })

.style("fill", function(d) { return d.colorsamp; })

如果您不想与CSS冲突。

const pinkHex = '#E7298A';

const colors = ['#E7298A', 'orange', 'green'];

d3.select('body').append('svg')
  .selectAll('circle')
  .data(colors)
  .enter()
  .append('circle')
  .attr('cx', (d, i) => (i * 50) + 25)
  .attr('cy', (d, i) => (i * 30) + 25)
  .attr('r', 5)
  .attr('fill', (d) => d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>