Plotly - 我想根据条件用不同的颜色为每个 X 轴值着色 [英] Plotly - I want to color each X Axis value in different color based on condition

查看:47
本文介绍了Plotly - 我想根据条件用不同的颜色为每个 X 轴值着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

语言:JavaScript
框架:Plotly

Language: JavaScript
Framework: Plotly

我有一个要求,我希望 x 轴值单独着色,而不是为 x 轴中的所有值着色.

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.

这里颜色红色"应用于 x 轴上的所有值.我需要根据下面代码中数组col"中提到的颜色对每个值进行着色.

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

推荐答案

  • 如果要单独为条形着色,则需要将颜色分配给数据中 marker 对象的颜色属性.
  • 如果您想单独为轴的刻度着色,则无法直接在绘图中进行.tickfont color 只需要一种颜色,但这不应该阻止我们.刻度线 text 位于类名为 xtick 的 SVG 元素内.我们可以选择它并用我们的颜色覆盖它的填充颜色.
    • 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>

      这篇关于Plotly - 我想根据条件用不同的颜色为每个 X 轴值着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆