Skip to content

Instantly share code, notes, and snippets.

@abhishekpolavarapu
Last active February 17, 2016 08:56
Show Gist options
  • Save abhishekpolavarapu/2cb911e07b96b852002f to your computer and use it in GitHub Desktop.
Save abhishekpolavarapu/2cb911e07b96b852002f to your computer and use it in GitHub Desktop.
magnitude as a position

I have taken a simple dataset which contains positive and negative value.This graph plots the positive values from dataset towards right side and negative values towards left side.All the positive values are represented in blue color and negative values are given red colors.

Channel used: Magnitude channel.(magnitude as position)

Marks : Bars.

R image

The discriminability is maintained here as the common scale is used for representing the both type of values and magnitude of bar changes with change in position along the axis

name value
A 15
B -20
C 22
D -18
E 2
F 6
G -26
H 30
<!DOCTYPE html>
<meta charset="utf-8">
<title>Magnitude as a position</title>
<style>
.bar.positive {
fill: steelblue;
}
.bar.negative {
fill: brown;
}
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var margin = {top: 30, right: 10, bottom: 10, left: 10},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.ordinal()
.rangeRoundBands([0, height], .2);
var xAxis = d3.svg.axis()
.scale(x)
.orient("top");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("data.tsv", type, function(error, data) {
x.domain(d3.extent(data, function(d) { return d.value; })).nice();
y.domain(data.map(function(d) { return d.name; }));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function(d) { return d.value < 0 ? "bar negative" : "bar positive"; })
.attr("x", function(d) { return x(Math.min(0, d.value)); })
.attr("y", function(d) { return y(d.name); })
.attr("width", function(d) { return Math.abs(x(d.value) - x(0)); })
.attr("height", y.rangeBand());
svg.append("g")
.attr("class", "x axis")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.append("line")
.attr("x1", x(0))
.attr("x2", x(0))
.attr("y2", height);
});
function type(d) {
d.value = +d.value;
return d;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment