TheMonkeyMan TheMonkeyMan - 1 year ago 81
CSS Question

D3 Chart Range SafeZone

I currently have a simple D3 Chart looking like this.
enter image description here

And what i want simply is to have a range box inside the chart. Basically semi transparent.

Imagine if inside the grey box was semi - transparent.

enter image description here



var configuration = {"xtitle":"X"};

var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - - margin.bottom;

var parseDate = d3.time.format("%Y%m%d").parse;

var x = d3.time.scale()
.range([0, width]);

var y = d3.scale.linear()
.range([height, 0]);

var xAxis = d3.svg.axis()

var yAxis = d3.svg.axis()

var line = d3.svg.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });

var line2 = d3.svg.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });

var svg ="body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + + margin.bottom)
.attr("transform", "translate(" + margin.left + "," + + ")");

d3.json("data.json", function(error, data) {
if (error) throw error;

data.forEach(function(d) {
d.x = parseDate(d.x);
d.y = d.y;

x.domain([data[0].x, data[data.length - 1].x]);
y.domain(d3.extent(data, function(d) { return d.y; }));

var meanx = [{x:parseDate("20111001"),y:25},{x:parseDate("20111002"),y:60},{x:parseDate("20111003"),y:25}];

.attr("id", "temperature-gradient")
.attr("gradientUnits", "userSpaceOnUse")
.attr("x1", 0).attr("y1", y(50))
.attr("x2", 0).attr("y2", y(60))
{offset: "0%", color: "green"},
{offset: "50%", color: "gray"},
{offset: "100%", color: "red"}
.attr("offset", function(d) { return d.offset; })
.attr("stop-color", function(d) { return d.color; });

.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")

.attr("class", "y axis")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")

.attr("class", "line")
.attr("d", line);

.attr("class", "line")
.attr("d", line);

.attr('class', 'area upper outer')
.attr('d', upperOuterArea)
.attr('clip-path', 'url(#rect-clip)');



Answer Source

At the very bottom of your script, append a rectangle:

svg.append("rect").attr("x", 0)
    .attr("y", y(45))
    .attr("width", width)
    .attr("height", y(25) - y(45))
    .attr("fill", "white")
    .attr("opacity", 0.6);

This goes from 45 to 25 in your y axis. The rectangle is white, and its opacity changes the appearance of the lines behind it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download