如何自定义 D3 折线图中的色阶? [英] How to customize the color scale in a D3 line chart?

查看:38
本文介绍了如何自定义 D3 折线图中的色阶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改 d3 折线图中线条的颜色,例如 Mike Bostock 的多系列 D3 折线图.

How do I change the color of lines in a d3 line chart, for example in Mike Bostock's multi-series D3 line chart.

在他的示例图表中,Mike Bostock 使用 D3 的内置category10"色标,按照这行代码:

In his example chart, Mike Bostock uses D3's built-in "category10" color scale, as per this line of code:

var color = d3.scale.category10();

但是假设,我们希望奥斯汀的线条为蓝色,纽约的线条为红色,旧金山的线条为绿色,而不是内置比例尺.应该够简单了吧?只需定义一个自定义色标:

But suppose, instead of the built-in scale, we wanted the line for Austin to be blue, the line for New York to be red, and the line for San Francisco to be green. Should be simple enough, right? Just define a custom color scale:

var color = d3.scale.ordinal()
    .domain(["New York", "San Francisco", "Austin"])
    .range("#FF0000", "#009933" , "#0000FF");

我认为这可能会奏效 - 但它会将所有系列都变成黑色.我已经尝试通过向每个系列添加类来为每个系列设置 CSS 样式,但这没有用.

I thought that might do the trick – but it turns all the series black. I've tried CSS styling each series by appending classes to them, but that didn't work.

推荐答案

您只是缺少 .range() 中值周围的方括号——它接受一个数组作为参数.所以代码应该是

You're only missing the square brackets around the values in .range() -- it takes an array as argument. So the code should be

var color = d3.scaleOrdinal() // D3 Version 4
  .domain(["New York", "San Francisco", "Austin"])
  .range(["#FF0000", "#009933" , "#0000FF"]);

完整示例此处.

这篇关于如何自定义 D3 折线图中的色阶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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