Skip to content

Instantly share code, notes, and snippets.

@iwan
Last active March 31, 2016 15:18
Show Gist options
  • Select an option

  • Save iwan/fe6e6108d07a4b74c576 to your computer and use it in GitHub Desktop.

Select an option

Save iwan/fe6e6108d07a4b74c576 to your computer and use it in GitHub Desktop.
Drawing histogram based on table row values

Visualize the magnitude of table row values

The goal is to visualize the magnitude of table row values using histogram bars.

Languages and libraries:

  • html + css
  • coffescript / javascript
  • d3 library

Features:

  • on 'hover' event
  • d3 transition

Live example: http://jsbin.com/qabavo/2/

$("table#flakka tbody tr").hover(
-> hover_row_in(this),
-> hover_row_out(this)
)
hover_row_in: (el) ->
maxHeight = 60
heights = $(el).children("td[data-value]").map( -> Math.abs($(this).data('value')))
max = Math.max.apply(Math, heights)
if max==0
maxHeight = 1.0
else
maxHeight = maxHeight/max
dataset = $(el).children("td[data-value]").map( ->
offset = $(this).offset()
{'left': offset.left, 'top': offset.top, 'width': $(this).outerWidth(), 'height': $(this).data('value')*maxHeight}
)
leftMargin = 2 # 2 pixels
d3.select("body")
.selectAll("div.cell-bar")
.data(dataset)
.enter()
.append("div")
.attr("class", "cell-bar")
.style("left", (d) ->
d.left+"px")
.style("top", (d) ->
d.top+"px")
.style("height", "0px")
.style("width", (d) ->
(d.width-leftMargin)+"px")
.transition()
.style("height", (d) ->
Math.abs(d.height)+"px")
.style("top", (d) ->
if d.height>=0.0 then (d.top-d.height)+"px" else d.top+"px")
$(el).addClass("hover-row")
hover_row_out: (el) ->
$("div.cell-bar").remove()
$(el).removeClass("hover-row")
.hover-row {
background-color: rgba(255,0,0,0.1);
}
div.cell-bar {
background-color: rgba(255,0,0,0.3);
position: absolute;
margin-left: 2px;
z-index: 10;
}
.right {
text-align: right;
}
<table class='table table-bordered table-condensed' id='flakka'>
<thead>
<tr>
<th>Fascia</th>
<th class='right'>1</th>
<th class='right'>2</th>
<th class='right'>3</th>
<th class='right'>4</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td class='right' data-value='73.91'>73.91</td>
<td class='right' data-value='75.97'>75.97</td>
<td class='right' data-value='29.53'>29.53</td>
<td class='right' data-value='61.33'>61.33</td>
</tr>
<tr>
<td>B</td>
<td class='right' data-value='24.04'>24.04</td>
<td class='right' data-value='20.09'>20.09</td>
<td class='right' data-value='75.15'>75.15</td>
<td class='right' data-value='56.95'>56.95</td>
</tr>
</tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment