条件填充面积图的d3.js [英] conditional fill in d3.js for area chart

查看:467
本文介绍了条件填充面积图的d3.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个面积图(应该代表一个时间序列)。我想基于y值对图进行着色,使得对于其中y> c是一种颜色并且对于其中y

I have an area graph (supposed to represent a time series). I want to color the graph based on the y value such that for regions where the y > c it is one color and for the area where y<=c it is another color. Is this possible in D3?

这是我生成单一颜色图表的代码:

This is the code I have that generates a single color graph:


var width = 700,
    height = 400;

var vis = d3.select("#chart")
    .append("svg")
    .attr("width",width)
    .attr("height",height); 

var mpts = [{"x":0,"val":15}];
var n = 200;
for(var i=0;i<n;i++)
{
    if(Math.random()>.5)
    {
        mpts = mpts.concat({"x":i+1,"val":mpts[i].val*(1.01)});
    }
    else
    {
        mpts = mpts.concat({"x":i+1,"val":mpts[i].val*(.99)});
    }
}

var x = d3.scale.linear().domain([0,n]).range([10,10+width]);
var y = d3.scale.linear().domain([10,20]).range([height-10,0]);

var area = d3.svg.area()
        .interpolate("linear")
        .x(function(d) { return x(d.x); })
        .y1(function(d) { return y(d.val); })
        .y0(function(d) { return y(0); });

vis.append("svg:path")
            .attr("class", "area")
            .attr("d",area(mpts))
        .attr("fill","orange");

</script>


推荐答案

更改添加区域到

    vis.selectAll("path").data(mpts).enter().append("svg:path")
        .attr("class", "area")
        .attr("d", area)
        .attr("fill", function(d) { return (d.val > c ? "orange" : "yellow"); });

这篇关于条件填充面积图的d3.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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