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

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

问题描述

对超级基本问题抱歉,但我正在努力解决最简单的事情:如何改变线条的颜色,在Mike Bostock的简单多系列D3 折线图

Apologies for the super-basic question, but I'm grappling with the simplest thing: how to change the color of the lines, in Mike Bostock's simple multi-series D3 line chart.

(我知道 - 我是个白痴。花费几个小时用不同的解决方案,通过D3文档和Googling愤怒地翻查,但我失败了可怕。在他的示例图中,Mike Bostock使用D3的内置category10颜色标度,按照这行代码:

(I know – I'm an idiot.) I've spent hours fiddling with different solutions, rummaging through the D3 documentation and Googling furiously, but I'm failing horribly. 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();

但是假设不是内置的scale,我们想让Austin的行为蓝色,纽约的线为红色,旧金山的线为绿色。应该足够简单,对吧?只需定义自定义颜色标度:

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. So... total failure. I'm sure I'm missing something really obvious here – but I'm completely stuck. I've tried CSS styling each series by appending classes to them, but that didn't work.

对于缺乏这个查询的jsfiddle抱歉,顺便说一句,但是Mike Bostock的例子使用了一个.tsv数据集(和我自己的代码一样),我不知道如何用外部数据集创建一个jsfiddle。

Apologies for the lack of a jsfiddle with this query, by the way, but Mike Bostock's example uses a .tsv dataset (as does my own code based on his), and I have no idea at all how to create a jsfiddle with an external dataset.

任何帮助都将非常感激。

Any help would be hugely appreciated.

推荐答案

$ c> .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.scale.ordinal()
  .domain(["New York", "San Francisco", "Austin"])
  .range(["#FF0000", "#009933" , "#0000FF"]);

完成示例这里

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

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