2

I am trying create a bar chart for top 10 among n number of entities. What I am trying to achieve is to give unique color to each bar. I am able to get the expected results when number of entities is 10 or less. This is what I am getting.

I want to use colors from d3.schemeCategory10 only. Here is my plunker code.

    bar_svg.selectAll("#bar_chart")
    .data(TOP_TEN_CHANNELS)
    .enter().append("rect")
    .attr("rx", 2)         // set the x corner curve radius
    .attr("ry", 2)
    .attr("class", "bar")
    .style("fill", function(d,i){ return color(d.channel);})
    .attr("x", 35)
    .transition() 
    .ease(d3.easePoly)          // apply a transition
    .duration(500)
    .attr("height", y.bandwidth()-5)
    .attr("y", function(d) { return y(d.channel); })
    .attr("width", function(d) { return x(d.views); });
aniket mule
  • 91
  • 10
  • That's what happens when you use a `for` loop in a D3 code... – Gerardo Furtado Apr 09 '18 at 07:41
  • @GerardoFurtado I had the same concern but could not get find way to achieve as I am new to d3. – aniket mule Apr 09 '18 at 07:44
  • 1
    Sorry, my mistake: I read your plunker too fast, just skimmed over it. Despite the `for` loop the problem here is different: you're passing an array of 20 values (that is, more than 10) to the scale which has only 10 colours in the range. The solution is passing your array of 10 top channels: https://plnkr.co/edit/rrAqlfRY21ZO6Wx2WsLO?p=preview. If you pass an array with more elements than the range the colours will repeat, that's the expected behaviour. – Gerardo Furtado Apr 09 '18 at 08:19
  • @GerardoFurtado Thanks for reviewing my code. I had used the code and commented out that statement. What i need to do is randomize sequence of colors after every change in duration. – aniket mule Apr 09 '18 at 08:39

1 Answers1

1

You can change schemeCategory10 to schemeCategory20 in order to have 20 different colors. There are also other prebuilt color schemas using schemeCategory20b or schemeCategory20c. Here is your code modified:

https://plnkr.co/edit/IsGQC75RIqoBijgcenu3

If you want even more colors you can follow the recipe I gave on another answer: How can I generate as many colors as I want using d3?

David Lemon
  • 1,560
  • 10
  • 21