本文介绍了d3.js-将不同的颜色添加到堆积条形图中的一个条形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用d3.js创建了堆叠的条形图,因为我想显示一个具有不同颜色的条形图以突出显示特定x轴值的数据,如下所示.

I have created the stacked bar chart by using d3.js.In that I would like to display a single bar with different colors to highlight the data for particular x axis value like below.

我用来绘制堆积图的脚本如下:

The script i have used to plot stacked chart is below:

// Set the dimensions of the canvas / graph
var svg = d3.select("#svgID"),
    margin = {top: 80, right: 140, bottom: 100, left: 100},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var padding = -100;
//set the ranges
var x = d3.scaleBand()
    .rangeRound([0, width])
    .paddingInner(0.20)
    .align(0.1);

var y = d3.scaleLinear()
    .rangeRound([height, 0]);

var z = d3.scaleOrdinal()
    .range(["#008000", "#C00000", "#404040", "#4d4d4d"]);    

var data = $("#svgID").data("values");

var keys = ["Pass", "Fail", "Average", "Worst"];

var legendKeysbar = ["Pass", "Fail", "Average", "Worst"];
var legendColorsbar = d3.scaleOrdinal()
    .range(["#008000", "#C00000", "#404040", "#4d4d4d"]);

// Scale the range of the data
x.domain(data.map(function (d) {
    return d.year;
}));
y.domain([0, d3.max(data, function (d) {
    return d.total;
})]).nice();
z.domain(keys);

// add the Y gridlines
g.append("g").selectAll(".hline").data(y.ticks(10)).enter()
    .append("svg:line")
    .attr("x1", 0)
    .attr("y1", function(d){ return y(d);})
    .attr("x2", width)
    .attr("y2", function(d){ return y(d);})
    .style("stroke", "white")
    .style("stroke-width", 1);    

// append the rectangles for the bar chart
g.append("g")
    .selectAll("g")
    .data(d3.stack().keys(keys)(data))
    .enter().append("g")
    .attr("fill", function (d) {
        return z(d.key);
    })
    .selectAll("rect")
    .data(function (d) {
        return d;
    })
    .enter().append("rect")
    .attr("x", function (d) {
        return x(d.data.year);
    })
    .attr("y", function (d) {
        return y(d[1]);
    })
    .attr("height", function (d) {
        return y(d[0]) - y(d[1]);
    })

您能帮我更新单个条形的颜色吗? d3.js可以实现吗?

Can you help me to update colors for single bar? is that possible by d3.js

推荐答案

创建第二个色标,然后在分配颜色的方法中,执行检查以确定要使用的色标,例如:

Create a second color scale, then in the method where you assign color, perform a check to determine which color scale to use, e.g.,:

var z2 = d3.scaleOrdinal().range(<your color array here>)

...

   .attr("fill", function (d) {
        return d.data.year === "Dec" ? z2(d.key) : z(d.key);
    })

这篇关于d3.js-将不同的颜色添加到堆积条形图中的一个条形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 20:28