After last week’s Angular+Svg+Html blog entry, here’s another version of the same US States incarceration rates data. Bar-charts in SVG this time.

Click here to see the result as stand alone (best for mobile devices)

Here it is running in an iFrame:

Again, it’s interactive. You can sort alphabetically, or by rate. It’s the SVG rectangles that Angular is mutating, and the DOM (in modern browsers) just makes that view correctly.

You really want to view the source, because as always, I’ve done a low-JavaScript usage of Angular. I greatly prefer that style and recommend it.

Snafus

1. I have to do two ng-repeat loops – one for the rectangles, and one for the text written (at 90 degrees) in the rectangles:

<svg ... >
<g>
  <rect ng-repeat="state in states | orderBy:order" ng-attr-x="{​{2+($index *16)}​}" 
      ng-attr-y="{​{170 - (state.inc/10)}​}" width="14" height="{​{state.inc/10}​}" 
	  fill="#F0F8FF" stroke="black" stroke-linecap="round" 
	  stroke-linejoin="round" stroke-width="1">
    <title>{​{state.inc}​}</title>
  </rect>
  <text ng-repeat="state in states | orderBy:order" 
      ng-attr-transform="{​{ 'translate(' + (12 + ($index *16)) + ' 165) rotate(-90)' }​}" 
      fill="black">
    <tspan font-family="Helvetica Neue" font-size="11" font-weight="500">{​{state.name}​}</tspan>
  </text>
</g>
</svg>

If you’re new to Angular, note how little SVG is being used for a multi-bar chart :)

2. The nature of the data, has to change from the last blog entry, so that ordering can be supported. It is an array now:

$scope.states = [
	{ name: "Louisiana", "inc" : 1619},
	{ name: "Alabama", "inc" : 735},
	...
];

And in the previous blog entry, it was a dictionary:

$scope.states = {
	"la": {"inc" : 1619},
	"al": {"inc" : 735},
	...
};

This is because of this issue in Angular. It is marked as “won’t fix” which I disagree with for the record. At least the workaround offered, I believe should be in the framework by default.



blog comments powered by Disqus

Published

February 26th, 2014

Tags