简体   繁体   中英

d3 word cloud specify individual word color

I'm using the JD word cloud d3 library. I understand how to change the colors of the cloud. For that, I use the following code:

  ProductDetailView.prototype._drawCloud = function() {
    function draw(words) {
      var colors = [
        '#3498DB', '#1478BB', '#00589B', '#54A8FB', '#74C8FF'
      ];

However, I want to be able to specify the color for certain words. It isn't clear to me how to do this, but I found an example on the net suggesting it is possible:

http://community.qlik.com/message/265261#265261

Can anyone explain how I would specify the color of certain words in the cloud? For example, I want all the republicans in my cloud to be colored red. I know which words are republicans. How do I specify their color?

I did it this way:

1) In loadWords() map any colour I want to assign to the specific object

function loadWords(){
    var word1 = {
            text: 'word',
            size: 32,
            color:'#FF00FF'
            };
    var word2 = {
            text: 'word2',
            size: 45,
            color:'#3498DB'
            };
    return [word,word2]
    }

  d3.layout.cloud().size([300, 300])
      .words(loadWords())
      ...
      .start();

2) Define mapping function

  function fillColor(d,i){
      return d.color;
  }

3) And to function draw(words) {... add this

        .style("fill", fillColor)

Easiest way to do it would be to modify the following line

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

to

      .style("fill", function(d, i) { if (check_for_republican) return republican_color ; else return democrat_color })

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