Add attribute data from a CSV to an SVG


/ Published in: Python
Save to your folder(s)

Take attribute data stored in a CSV and insert it into an SVG based on unique ID field.

The final bit of code adds an 'onmouseover' effect to animate the map in javascript.


Copy this code and paste it in your HTML
  1. #! python3
  2. import csv
  3. import xml.etree.ElementTree as ET
  4.  
  5. dataFile = open('pharmData.csv', encoding="UTF-8")
  6. dataReader = csv.DictReader(dataFile)
  7. tree = ET.parse('pharmacies.xml')
  8. root = tree.getroot()
  9.  
  10. #create list to store dat
  11. dataSet = []
  12.  
  13. #extract data from csv
  14. for row in dataReader:
  15. comuna = {}
  16. comuna.update({'comId':row['COMUNA']})
  17. comuna.update({'name':row['NOM_COMUNA']})
  18. comuna.update({'income':row['avg_income_tot']})
  19. comuna.update({'pharmCount':row['Join_Count']})
  20. comuna.update({'popRatio':row['POB_per_STORE']})
  21. dataSet.append(comuna)
  22.  
  23. #push data into xml
  24. for polygon in root:
  25. polygon.set('class','comuna')
  26. code = polygon.get('id')
  27. for item in dataSet:
  28. if code == item['comId']:
  29. polygon.set('label',item['name'])
  30. polygon.set('income',item['income'])
  31. polygon.set('pharmacies',item['pharmCount'])
  32. polygon.set('popRatio', item['popRatio'])
  33.  
  34. #add script tag
  35. for polygon in root:
  36. label = polygon.get('label')
  37. popRatio = polygon.get('popRatio')
  38. # amend data for comunas where no pharmacy was found
  39. if popRatio == '0':
  40. popRatio = 'no data'
  41. income = polygon.get('income')
  42. polygon.set('onmouseover','displayName(\''+label+'\',\''+popRatio+'\',\''+income+'\')')
  43.  
  44. #write xml
  45. tree.write('output.xml')

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.