d3 word cloud specify individual word color

4.1k views Asked by At

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?

2

There are 2 answers

0
Babu On BEST ANSWER

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)
0
Vivek Kumar On

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 })