Skip to content

Instantly share code, notes, and snippets.

@phil-pedruco
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phil-pedruco/9032348 to your computer and use it in GitHub Desktop.
Save phil-pedruco/9032348 to your computer and use it in GitHub Desktop.
Bar chart with mouseover event
letter frequency
A .08167
B .01492
C .02782
D .04253
E .12702
F .02288
G .02015
H .06094
I .06966
J .00153
K .00772
L .04025
M .02406
N .06749
O .07507
P .01929
Q .00095
R .05987
S .06327
T .09056
U .02758
V .00978
W .02360
X .00150
Y .01974
Z .00074
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bar Chart with Manipulation</title>
<style>
.axis {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.y.axis path {
display: none;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
</body>
<script>
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.rangeRoundBands([0, height], .1);
var x = d3.scale.linear()
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(10, "%");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var color = d3.scale.category20c();
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([0, d3.max(data, function(d) {
return d.frequency;
})]);
y.domain(data.map(function(d) {
return d.letter;
}));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("transform", "rotate(0)")
.attr("y", 6)
.attr("dy", "1.91em")
.style("text-anchor", "start")
.text("Frequency");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var bars = svg.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar");
bars.attr("y", function(d) {
return y(d.letter);
})
.attr("height", y.rangeBand())
.attr("x", 0)//function(d) {
//return x(d.frequency);
//})
.attr("width", function(d) {
return x(d.frequency);
})
.attr("fill", function(d, i) {
return color(i);
})
.attr("id", function(d, i) {
return i;
})
.on("mouseover", function() {
d3.select(this)
.attr("fill", "red");
})
.on("mouseout", function(d, i) {
d3.select(this).attr("fill", function() {
return "" + color(this.id) + "";
});
});
bars.append("title")
.text(function(d) {
return d.letter;
});
});
function type(d) {
d.frequency = +d.frequency;
return d;
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment