Skip to content

Instantly share code, notes, and snippets.

@hexatridecimal
Created November 3, 2011 18:19
Show Gist options
  • Save hexatridecimal/1337264 to your computer and use it in GitHub Desktop.
Save hexatridecimal/1337264 to your computer and use it in GitHub Desktop.
Color an SVG Map of the United States with Data
#!/usr/bin/env ruby
require 'carmen'
require 'nokogiri'
nok = Nokogiri::XML(File.open("usmap.svg"))
states = {}
max = 0
min = 99999
File.open("unemployment.tsv").each_line do |l|
next if l =~ /^Rank/
l.chomp!
row = l.split("\t")
state = row[1]
abbv = Carmen::state_code(state)
next if abbv == nil
states[abbv] = row[2].to_f
max = states[abbv] if states[abbv] > max
min = states[abbv] if states[abbv] < min
end
max = max - min
states.each_key do |abbv|
pct = (states[abbv] - min) / max.to_f
amount = (255 * pct)
blue = "%02x" % amount
color = "0000#{blue}"
nok.xpath("//*[@id='#{abbv}']").each do |obj|
style = obj.attr('style')
style.gsub!(/fill:#(?:[A-Fa-f0-9][A-Fa-f0-9]){3}/, "fill:##{color}")
obj.set_attribute('style', style)
obj.children.each do |chld|
style = obj.attr('style')
style.gsub!(/fill:#(?:[A-Fa-f0-9][A-Fa-f0-9]){3}/, "fill:##{color}")
obj.set_attribute('style', style)
end
end
end
File.open('unemployment.svg','w') {|f| nok.write_xml_to f}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment