• fullscreen
  • CSVloader.pde
  • USUnemp.pde
  • dataGather.pde
  • myParser.pde
  • import java.io.File;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class CSVloader
    {
        private double theRate;
        private String theFips;
        private Vector values = new Vector();
        private dataGather dg;
        private String currentPeriod = "M0";
    
        public CSVloader(double r, String f)
        {
            this.theRate = r;
            this.theFips = f;
        }
    
        public CSVloader(String fName)
        {
    
            try
            {
                File file = new File(fName);
    
                BufferedReader bufRdr = new BufferedReader(new FileReader(file));
    
                String line = null;
                String full_fips = "";
                double rate = 0;
    
                while((line = bufRdr.readLine()) != null)
                {
                    StringTokenizer st = new StringTokenizer(line,",");
                    String s = "";
                    int col = 0;
    
                    while(st.hasMoreTokens())
                    {
                        s = st.nextToken();
    
                        if (!(s.startsWith("\"")))
                        {
                            if (col == 1 || col == 2)
                            {
                                full_fips = full_fips + s;
                            }
                            if (col == 8)
                            {
                                String r = "";
                                String g = "0123456789";
                                for (int j = 0; j < s.length(); j++)
                                {
                                    if (g.indexOf(s.charAt(j)) >= 0)
                                        r += s.charAt(j);
                                }
                                rate = Double.parseDouble(r)/10;
                            }
                            col++;
                        }
                    }
    
                    values.add(new CSVloader(rate,full_fips));
                    rate = 0;
                    full_fips = "";
                }
                bufRdr.close();
            }
            catch(Exception e)
            {
                System.err.println("It failed!");
                System.err.println(e.toString());
            }
        }
    
        public CSVloader(int year, String period)
        {
              if (currentPeriod != period)
              {
                dg = new dataGather(year+period+"unemp.xml");
                currentPeriod = period;
              }
            
              this.values = dg.getData(period);
        }
    
        public Vector getValues()
        {
            return values;
        }
    
        public double getRate()
        {
            return this.theRate;
        }
    
        public String getFips()
        {
            return this.theFips;
        }
    }
    
    myParser p;
    CSVloader details;
    Vector counties, lines;
    PFont font, font_larger;
    PImage Play, Pause;
    boolean go = false;
    
    String[] months = new String[]
    {
      new String("Jan"),
      new String("Feb"),
      new String("Mar"),
      new String("Apr"),
      new String("May"),
      new String("Jun"),
      new String("Jul"),
      new String("Aug"),
      new String("Sep"),
      new String("Oct"),
      new String("Nov"),
      new String("Dec")
    };
    
    int period = 0;
    int max_year = 2009;
    int min_year = 2005;
    int the_year = min_year;
    String the_period = "M01";
    String max_period = "M12";
    boolean cease = false;
    
    
    void setup()
    {
      
      p = new myParser("USA_Counties.svg");
      
      font = createFont("Helvetica",10);
      font_larger = createFont("Helvetica",12);
      Play = loadImage("play4.jpg");
      Pause = loadImage("pause3.jpg");
      
      size(800,500);
      stroke(255);
      background(#6699CC);
      colorMode(RGB);
      smooth();
      noLoop();
    }
    
    void draw()
    {
      background(#6699CC);
      startButton();
      drawLegend();
      drawSlider(the_year,the_period);
      createCounty(the_year,the_period);
      drawStateLines();
      
      if (go)
      {     
         if (Integer.parseInt(the_period.substring(1,3)) >= 12)
         {
            the_period = "M01";
            the_year++;
         }
         else
         {
            int t = Integer.parseInt(the_period.substring(1,3));
            t++;
            if (t < 10)
            {
                the_period = the_period.substring(0,2) + String.valueOf(t);
            }
            else
           {
                the_period = the_period.substring(0,1) + String.valueOf(t);
           } 
         }
         
         if (the_year == max_year && the_period.equalsIgnoreCase(max_period))
         {
            go = !go;
            startButton();
         }
      }
    }
    
    void drawStateLines()
    {
       lines = p.getStateLines();
       for (int i = 0; i < lines.size(); i++)
       {
          Vector t = ((Counties)lines.get(i)).getcoords();
          boolean firstM = true;
          strokeWeight(1);
          stroke(#FFFFFF);
    
          beginShape();
            for (int j = 0; j < t.size(); j++)
            {
                noFill();
                coordinates cr = (coordinates)t.get(j);
                stroke(#FFFFFF);           
                if (cr.getAction().equalsIgnoreCase("M"))
                {
                  if (!firstM)
                  {
                    endShape();
                    beginShape();
                  }
                  else
                  {
                     firstM = !firstM; 
                  }
                  vertex((float)cr.getX(),(float)cr.getY());
                }
                else 
                {
                  vertex((float)cr.getX(),(float)cr.getY());
                }
          }
          endShape();
          
          stroke(255);
       }
      
    }
    
    void createCounty(int y, String m)
    {
      counties = p.getCountyStats(y,m);
      
      for (int i = 0; i < counties.size(); i++)
      {
              Vector t = ((Counties)counties.get(i)).getcoords();
              boolean firstM = true;
              beginShape();
                strokeWeight(0);
                stroke(#999999);
                for (int j = 0; j < t.size(); j++)
                {
                   coordinates c0 = (coordinates)t.get(j);
                   String h = ((Counties)counties.get(i)).getFill();
                   if (h.equals("99"))
                   {
                      fill(#980043);
                   }
                   else if (h.equals("DD"))
                   {
                      fill(#DD1C77);
                   }
                   else if (h.equals("DF"))
                   {
                      fill(#DF65B0);
                   }
                   else if (h.equals("C9"))
                   {
                      fill(#C994C7);
                   }
                   else if (h.equals("D4"))
                   {
                      fill(#D4B9DA);
                   }
                   else if (h.equals("F1"))
                   {
                      fill(#F1EEF6);
                   }
                   if (c0.getAction().equalsIgnoreCase("M"))
                   {
                      if (!firstM)
                      {
                          endShape();
                          beginShape();
                      }
                      else
                      {
                          firstM = !firstM; 
                      }              
                      vertex((float)c0.getX(),(float)c0.getY());
                   }
                   else 
                   {
                      vertex((float)c0.getX(),(float)c0.getY());
                   }
              }
              endShape();
              stroke(255);
    }
    
    }
    
    void drawLegend()
    {
        textFont(font);
        stroke(255);
        fill(255);
        
        text("Unemployment Levels",640,190);
        text(">= 10%",710, 208);
        text(">= 8%", 710, 228);
        text(">= 6%", 710, 248);
        text(">= 4%", 710, 268);
        text(">= 2%", 710, 288);
        text("< 2%", 710, 308);
        fill(#980043);
        rect(600,200,100,10);
        fill(#DD1C77);
        rect(600,220,100,10);
        fill(#DF65B0);
        rect(600,240,100,10);
        fill(#C994C7);
        rect(600,260,100,10);
        fill(#D4B9DA);
        rect(600,280,100,10);
        fill(#F1EEF6);
        rect(600,300,100,10);
    }
    
    void startButton()
    {
       if (!go)
       {
           image(Play,600,440);
       }
       else
       {
           if (the_year == max_year && the_period.equalsIgnoreCase(max_period)) 
           {
               the_year = min_year;
               the_period = "M01"; 
           }
           image(Pause,600,440);
       }
    }
    
    void drawSlider(int y, String m)
    {
       stroke(255);
       int s = ((max_year+1)-min_year)*12;
       for (int i = 1; i < s+1; i++)
       {
           int j = i;
           line(20+(j*7),450,20+(j*7),460);
       }
       int p = Integer.parseInt(m.substring(1,3));
       drawButton(y,p);   
    }
    
    void drawButton(int y, int m)
    {
       int f = (y - min_year)*12;
       int xpos = (f + m)*7;
       fill(#9E0508);
       ellipse(20+xpos,454,10,10);
       strokeWeight(1);
       stroke(#7CFC00);
       fill(255);
       textFont(font_larger);
       text(months[m-1]+", "+y,((max_year+1-min_year)*12)*7,436);
       stroke(255);
    }
    
    void mousePressed()
    {
       if ((mouseX >= 590 && mouseX <= 640) && (mouseY >=440 && mouseY <= 470))
       {
         go = !go;
         if (go) loop();
         else noLoop();
       }
       
    }
    
    
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import java.io.File;
    import java.io.IOException;
    import java.io.*;
    import java.util.Vector;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import java.net.URL;
    
    public class dataGather
    {
        private Document previous = null;
    
        protected Document myDom = null;
        protected DocumentBuilderFactory dbf = null;
        protected DocumentBuilder db = null;
        protected InputStream in = null;
    
        private TransformerFactory tranFact = TransformerFactory.newInstance();
    
        public dataGather(String fileName)
        {
            dbf = DocumentBuilderFactory.newInstance();
    
            try
            {
                in = createInput(fileName);
                db = dbf.newDocumentBuilder();
                myDom = db.parse(in);
            }
            catch (Exception e)
            {
                System.err.println(e.toString());
            }
        }
    
        public Vector List(String tag)
        {
            Vector a = new Vector();
            NodeList t = myDom.getElementsByTagName("unemp");
            
            if (t.getLength() > 0)
            {
                NodeList nodes = t.item(0).getChildNodes();
    
                double rate = 0.0;
                String full_fips = "";
                int theYear = 2005;
                String thePeriod = "";
                int counter = 0;
    
                for (int i = 0; i < nodes.getLength(); i++)
                {
                    if (nodes.item(i).getNodeName().equalsIgnoreCase("month"))
                    {
                        thePeriod = nodes.item(i).getTextContent();
                    }
                    if (nodes.item(i).getNodeName().equalsIgnoreCase("value"))
                    {
                        rate = Double.parseDouble(nodes.item(i).getTextContent());
                    }
                    if (nodes.item(i).getNodeName().equalsIgnoreCase("fips"))
                    {
                        full_fips = nodes.item(i).getTextContent();
                    }
    
                    counter++;
    
                    if (counter == 4)
                    {
                        a.add(new CSVloader(rate,full_fips));
                        rate = 0.0;
                        full_fips = "";
                        thePeriod = "";
                        counter = 0;
                    }
                }
    
            }
            return a;
        }
    
        public Vector getData(String period)
        {
            Vector a = new Vector();
            NodeList t = myDom.getElementsByTagName("unemp");
    
            if (t.getLength() > 0)
            {
    
                NodeList nodes = t.item(0).getChildNodes();
    
                double rate = 0.0;
                String full_fips = "";
                int theYear = 2005;
                String thePeriod = "";
                int counter = 0;
    
                for (int i = 0; i < nodes.getLength(); i++)
                {
                    if (nodes.item(i).getNodeName().equalsIgnoreCase("value"))
                    {
                        rate = Double.parseDouble(nodes.item(i).getTextContent());
                        counter++;
                    }
                    if (nodes.item(i).getNodeName().equalsIgnoreCase("fips"))
                    {
                        full_fips = nodes.item(i).getTextContent();
                        counter++;
                    }
                    if (counter == 2)
                    {                
                        a.add(new CSVloader(rate,full_fips));
                        rate = 0.0;
                        full_fips = "";
                        thePeriod = "";
                        counter = 0;
                    }
                 }
            }
            return a;
        }
    }
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    import org.w3c.dom.*;
    import java.io.File;
    import java.io.InputStream;
    import java.util.Vector;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import java.net.URL;
    
    public class myParser
    {
        private String path_style = "font-size:12px;fill-rule:nonzero;stroke:#FFFFFF;stroke-opacity:1;stroke-width:0.1;stroke-miterlimit:4;stroke-dasharray:none;stroke-linecap:butt;marker-start:none;stroke-linejoin:bevel;fill:";
        private String fName;
        private Document theDomain;
        private Transformer transformer;
        private DOMSource source;
        private StreamResult result;
        private NodeList path;
        private CSVloader details;
        private URL myUrl;
        private InputStream in;
    
        public myParser(String fName)
        {
          
            this.fName = fName;
    
            try
            {
                in = createInput(fName);
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                theDomain = db.parse(in);
                source = new DOMSource(theDomain);
                path = theDomain.getElementsByTagName("path");
            }
            catch (Exception e)
            {
                System.err.println(e.toString());
            }
        }
    
        public void update(Vector csv, String extension)
        {
            int counter = 0;
            String colour_code = "#666666";
            boolean found = false;
            System.out.println(this.fName.substring(0,this.fName.indexOf("."))+extension+this.fName.substring(this.fName.indexOf(".")));
            File xmlres = new File(this.fName.substring(0,this.fName.indexOf("."))+extension+this.fName.substring(this.fName.indexOf(".")));
            result = new StreamResult(xmlres);
    
    
            for (int i = 0; i < path.getLength(); i++)
            {
                NamedNodeMap a = path.item(i).getAttributes();
                String v = a.getNamedItem("id").getNodeValue();
                if ( !(v.equalsIgnoreCase("State_Lines")) && !(v.equalsIgnoreCase("separator")))
                {
                    for (int j = 0; j < csv.size() && !found; j++ )
                    {
                        CSVloader c = (CSVloader)csv.get(j);
    
                        if (c.getFips().equalsIgnoreCase(v))
                        {
                            found = true;
                            counter++;
                            if (c.getRate() > 10)
                            {
                                colour_code = "#980043";
                            }
                            else if (c.getRate() > 8)
                            {
                                colour_code = "#DD1C77";
                            }
                            else if (c.getRate() > 6)
                            {
                                colour_code = "#DF65B0";
                            }
                            else if (c.getRate() > 4)
                            {
                                colour_code = "#C994C7";
                            }
                            else if (c.getRate() > 2)
                            {
                                colour_code = "#D4B9DA";
                            }
                            else
                            {
                                colour_code = "#F1EEF6";
                            }
                        }
                    }
                    found = false;
                    a.getNamedItem("style").setNodeValue(path_style+colour_code);
                    colour_code = "#666666";
                }
            }
            try
            {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                transformer = tFactory.newTransformer();
    
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.transform(source, result);
            }
            catch(TransformerException e)
            {
                System.out.println("Transformation failed!");
                System.out.println(e.toString());
            }
        }
        
        
    
        public Vector getCountyStats(int year, String period)
        {
            Vector t = new Vector();
            details = new CSVloader(year,period);
            Vector csv = details.getValues();
            
            boolean found = false;
            int counter = -1;
            String colour_code = null;
    
            for (int i = 0; i < path.getLength(); i++)
            {
                NamedNodeMap attribs = path.item(i).getAttributes();
                String theId = attribs.getNamedItem("id").getNodeValue();
    
                if ( !(theId.equalsIgnoreCase("State_Lines")) && !(theId.equalsIgnoreCase("separator")))
                {
                    String label = attribs.getNamedItem("inkscape:label").getNodeValue();
                    String d = attribs.getNamedItem("d").getNodeValue();
    
                    for (int j = 0; j < csv.size() && !found; j++ )
                    {
                        if (((CSVloader)csv.get(j)).getFips().equalsIgnoreCase(theId))
                        {
                            found = true;
                            counter++;
                            if (((CSVloader)csv.get(j)).getRate() > 10)
                            {
                                colour_code = "99"; //"#980043"
                            }
                            else if (((CSVloader)csv.get(j)).getRate() > 8)
                            {
                                colour_code = "DD"; //"#DD1C77"
                            }
                            else if (((CSVloader)csv.get(j)).getRate() > 6)
                            {
                                colour_code = "DF"; //"#DF65B0"
                            }
                            else if (((CSVloader)csv.get(j)).getRate() > 4)
                            {
                                colour_code = "C9"; //"#C994C7"
                            }
                            else if (((CSVloader)csv.get(j)).getRate() > 2)
                            {
                                colour_code = "D4"; //"#D4B9DA"
                            }
                            else
                            {
                                colour_code = "F1"; //"#F1EEF6"
                            }                        
                        }
                    }
                    
                    if (!found)
                    {
                      colour_code = "F1"; //"F1EEF6";  //#
                    }
                    found = false;
                    t.add(new Counties(theId,colour_code,d,label));
                    
                }
            }
            return t;
        }
        
        public Vector getStateLines()
        {
            Vector t = new Vector();
            boolean found = false;
            int counter = -1;
            String colour_code = "FF";
    
            for (int i = 0; i < path.getLength(); i++)
            {
                NamedNodeMap attribs = path.item(i).getAttributes();
                String theId = attribs.getNamedItem("id").getNodeValue();
                
                if (theId.equalsIgnoreCase("State_Lines"))
                {
                    found = true;
                    String label = attribs.getNamedItem("inkscape:label").getNodeValue();
                    String d = attribs.getNamedItem("d").getNodeValue();
                    t.add(new Counties(theId,colour_code,d,label));
                }
            }
            
            return t;
        }
    
    }
    

    code

    tweaks (0)

    about this sketch

    This sketch is running as Java applet, exported from Processing.

    This sketch is saved as a draft and it is not published on the homepage and browse page.

    license

    advertisement

    Anthony Smee

    The US is bleeding

    Add to Faves Me Likey@! 8
    You must login/register to add this sketch to your favorites.

    I converted this Python based tutorial (http://flowingdata.com/2009/11/12/how-to-make-a-us-county-thematic-map-using-free-tools/) into this Processing app.

    (Feb 2010) : I have updated the dataset to include the last quarter, things aren't getting better (and don't I know it!).

    shaocong zhou
    27 Dec 2009
    Nice!
    May be a 3D version could be more powerful.
    Jon Spring
    23 Jun 2010
    Great work. This would could even better if the colors adjusted smoothly, e.g. using Ben Fry's Integrator class.
    bob
    2 Jan 2013
    Great work Anthony! Hey, i wish to talk to you regarding similar problem. if its okay, is there any other id i can contact you on? You can email me at - shawn144441 (at) gmail(dot)com

    Thanks :)
    Lolly Lawson
    20 Mar 2014
    Hey Adam,

    I was just trying out the codes on processing to get a better view , but the following error messages keep coming up:
    No library found for org.w3c.dom
    No library found for org.xml.sax
    No library found for org.w3c.dom
    Display 0 does not exist, using the default display instead.
    java.lang.IllegalArgumentException: InputStream cannot be null
    The file "play4.jpg" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable.
    The file "pause3.jpg" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable.
    java.lang.NullPointerException
    at processing.core.PApplet.main(PApplet.java:6797)
    You need to login/register to comment.