处理二维散点图

时间:2019-04-28 06:04:23

标签: processing

如何加载.csv文件并使用表中的数据创建二维散点图。

表中的数据为

Name             X   Y  Group Gender Year of Birth  Grade
Victor Anderson 627 705   2   Female      2000       6
Jack Scott       808    643 1   Male    2002    4
Sean Robinson   624 627 1   Male    2002    4
William Rodriguez   423 396 1   Female  2004    2
Aaron Kelly     775 181 0   Female  2005    1
Raymond Taylor  433 731 1   Female  2000    1
Alan Foster 635 580 2   Male    2002    4
Charles Watson  884 262 0   Female  2003    3
Lillian Perez   334 190 4   Male    2005    1
Betty Moore 727 524 1   Female  2003    3
Bruce Adams 503 684 0   Male    2001    2
Kathryn Sanchez 284 246 0   Male    2001    2
Chris Hall  189 223 3   Male    2000    6
Eugene Harris   196 220 3   Female  2000    5
Gary Baker  707 559 0   Female  2001    5
Michael Ramirez 299 657 2   Male    2000    1
Walter Smith    400 755 0   Male    2005    5
Ann Murphy  0   895 1   Male    2003    3
Lois Thompson   783 631 1   Female  2003    2
Louis Jones 674 589 1   Female  2003    3
Tammy Bell  828 263 3   Male    2002    4
Carolyn Bailey  557 23  4   Male    2004    2
Larry Campbell  444 627 2   Female  2004    2

1 个答案:

答案 0 :(得分:0)

要从csv中的数据绘制一个简单的散点图,我们需要:

  • 确保X和Y列可以读取为数字
  • 将X和Y值标准化或缩放为画布大小
  • 在每行的x和y缩放位置绘制一个点
  • 添加标签

对于第一个项目,我们可以添加代码以清除X和Y并将其转换为数字。下面我假设X和Y始终是整数,并删除了空格,因此我们可以仅调用row.getInt()

数据保存如下:

Name,X,Y,Group,Gender,Year of Birth,Grade
Victor Anderson,627,705,2,Female,2000,6
Jack Scott,808,643,1,Male,2002,4

请注意,多余的空格已删除,因此我们可以在不使用特殊清除代码的情况下调用表和行方法。

Table table;
  int xMin;
  int yMin;
  int xMax;
  int yMax;

void setup() {
  size(900, 900);
  table = loadTable("plot_data.csv", "header");
  background(0);
  fill(255);
  // we get the minimum and maximum values for X and Y so we can scale to our canvas
  xMin = getMin(table, "X");
  yMin = getMin(table, "Y");
  xMax = getMax(table, "X");
  yMax = getMax(table, "Y");

}

void draw(){
  background(0);
  boolean labelDrawn = false;
  for (TableRow row : table.rows()) {
    int x = row.getInt("X");
    // the map function takes our value and maps it to a value that fits on our canvas
    float xPos = map(x, xMin, xMax, 0, width);
    int y= row.getInt("Y");
    float yPos = map(y, yMin, yMax, 0, height);
    ellipse(xPos,yPos,10,10);
    // Here we put a name label on the plotted data when the mouse is over it
    if(dist(mouseX,mouseY,xPos,yPos)<10 && !labelDrawn){
      fill(255);
      text(row.getString("Name"),mouseX-10,mouseY-10);
      labelDrawn = true; // only draw one label at a time
   }
  }
}

  int getMin(Table table, String col){
    int min = Integer.MAX_VALUE;
    for (TableRow row : table.rows()){
      if (row.getInt(col)<min){
        min = row.getInt(col);
      }
    }
    return min;
  }

  int getMax(Table table, String col){
    int max = Integer.MIN_VALUE;
    for (TableRow row : table.rows()){
      if (row.getInt(col)>max){
        max = row.getInt(col);
      }
    }
    return max;
  }