3

Language: JavaScript
Framework: Plotly

I have a requirement where i want x-Axis values to be colored individually instead of coloring all the values in x-Axis.

I tried below code, but it does the same thing to all the values on axis.

Here the color 'red' gets applied to all the values on x-Axis. I need each value to be colored based on the colors mentioned in the array 'col' in below code.

var data = [{
  x: ['giraffes', 'orangutans', 'monkeys'],
  y: [20, 14, 23],
  type: 'bar'
}];

var col = ['red','black','yellow'];

var layout = {

  xaxis : {
    tickangle : -45,
    tickfont : {
      size : 16,
      color : 'red'
    }
  }

};

Plotly.newPlot('myDiv', data,layout);
Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99
Mahaveer Jangir
  • 597
  • 7
  • 15

1 Answers1

8
  • If you want to color the bars individually you would need to assign the colors to the color attribute of the marker object inside your data.
  • If you want to color the axis' ticks individually there is no way of doing it directly in plotly. tickfont color only takes a single color but this should not stop us. The tick text is inside a SVG element with the class name xtick. We can select it and override its fill aka color with our colors.

var col = ['red','black','yellow'];
var data = [{
  x: ['giraffes', 'orangutans', 'monkeys'],
  y: [20, 14, 23],
  type: 'bar',
  marker: {color: col}
}];

var layout = {
  xaxis : {
    tickangle : -45,
    tickfont : {
      size : 16,
      color : 'red'
    }
  }
};

Plotly.newPlot('myDiv', data,layout);

var ticks = document.getElementsByClassName('xtick');
for (var i = 0; i < ticks.length; i += 1) {
  ticks[i].getElementsByTagName('text')[0].style.fill = col[i % col.length];  
}
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='myDiv'></div>
Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99
  • I am not looking to color the bars . I need to color the x-Axis tick values. Like here 'giraffes', 'orangutans', 'monkeys' . So I want the tick value giraffes in 'red' , orangutans in 'black' and monkeys in 'yellow'.. – Mahaveer Jangir May 10 '17 at 11:27
  • 1
    @MahaveerJangir: Thanks for the clarification. Updated the answer accordingly. – Maximilian Peters May 10 '17 at 18:15