# Using the SVG Coordinate Space

### The Goal

In this section, you will use D3.js to add SVG elements to specific coordinates in a graph based on data.

Our Goal is to take the following data set:

`1var spaceCircles = [30, 70, 110];`

and transform it to this data visualization using D3.js: ### Mathematical / Graph Coordinate Space

Before we get into using D3.js to add SVG elements to specific coordinates in a graph based on data, let us talk about the coordinate space.

We learned about basic mathematical graphs in basic mathematics.

These graphs are a 2-dimensional flat space represented as a rectangle.

These graphs have a coordinate space where x=0 and y=0 coordinates fall on the bottom left. These graphs have the X coordinate growing from left to right.

These graphs also have the Y coordinate growing from bottom to top.

Which means, when we talk about drawing a circle with x=30 and y=30 coordinates, we go 30 units from the bottom left to the right and then we go 30 units up. ### SVG Coordinate Space

SVG Coordinate Space works in the same way that mathematical graph coordinate space works except for two important features:

1 - SVG Coordinate space has x=0 and y=0 coordinates fall on the top left.

2 - SVG Coordinate space has the Y coordinate growing from top to bottom. Which means as Y increases, the coordinates move down, not up.

So when we talk about drawing a circle with x=30 and y=30 coordinates in SVG Coordinate Space, we go 30 units from the top left to the right and then we go down 30 units up. ### .append('svg') as a Coordinate Space

When we have created a D3.js visualization, so far we have started with the following code

```1var svgContainer = d3.select("body").append("svg")
2                                    .attr("width", 200)
3                                    .attr("height", 200);```

Which gives us this the following HTML SVG element: We can think of this SVG element as a graph 200 units wide and 200 units tall.

And with what we learned from the above section ( SVG Coordinate Space ), we now know that the X and Y zero coordinates are at the top left.

We also now know that as the Y coordinate grows, it will move from the top to the bottom of our graph.

To clarify what this looks like, we can style our SVG element by adding some style to it like this:

```1var svgContainer = d3.select("body").append("svg")
2                                    .attr("width", 200)
3                                    .attr("height", 200)
4                                    .style("border", "1px solid black");```

Which gives us this: This is useful for thinking about how the data visualization takes shape given the inverted Y coordinate system.

### Position SVG Elements in the SVG Coordinate Space

When we create an SVG Circle element in the following fashion:

```1<svg width="50" height="50">
2  <circle cx="25" cy="25" r="25" fill="purple" />
3</svg>```

The cx tells us to move 25 units from the left to the right of the SVG element.

The cy tells us to move 25 units from the top to the bottom of the SVG element.

Recall how we created an SVG circle with D3.js before:

```1var circleSelection = svgSelection.append("circle")
2                                  .attr("cx", 25)
3                                  .attr("cy", 25)
4                                  .attr("r", 25)
5                                  .style("fill", "purple");```

The .attr("cx", 25) and .attr("cy", 25) allow us to set the attributes of the SVG circle.

And as we saw later in the Creating SVG Elements Based on Data section, we can programmatically set these attributes:

```1var circleAttributes = circles
2                       .attr("cx", 50)
3                       .attr("cy", 50)
4                       .attr("r", function (d) { return d; });```

Except, this time, instead of using a function in the "radius" r attribute, we will use a function in the cx and cy attributes.

### Create an SVG Element to Hold SVG Elements

```1<!DOCTYPE html>
2<html>
4    <script type="text/javascript" src="d3.v2.min.js"></script>
6  <body>
7  </body>
8</html>```

Open the JavaScript Console with the HTML elements visible.

Then type the following into the JavaScript Console:

```1var spaceCircles = [30, 70, 110];
2
3var svgContainer = d3.select("body").append("svg")
4                                    .attr("width", 200)
5                                    .attr("height", 200);```

This gives us the data set and an SVG element to hold the SVG Circles we will add shortly: ### Bind Data to SVG Circles

The next step will be to take the data and bind it to our SVG Circle elements.

``` 1var spaceCircles = [30, 70, 110];
2
3var svgContainer = d3.select("body").append("svg")
4                                    .attr("width", 200)
5                                    .attr("height", 200);
6
7var circles = svgContainer.selectAll("circle")
8                          .data(spaceCircles)
9                          .enter()
10                          .append("circle");```

This gives us the three SVG circle elements in our webpage: Which is great - though the circles don't appear. This is because have not specified the attributes for each circle.

### Use Bound Data to Alter SVG Circle Coordinates

Now that the data is bound to the SVG Circle Elements, we can use it to specify the attributes for the x-coordinate and y-coordinate.

D3.js allows us to use a function in the "cx" and "cy" attributes:

``` 1var spaceCircles = [30, 70, 110];
2
3var svgContainer = d3.select("body").append("svg")
4                                    .attr("width", 200)
5                                    .attr("height", 200);
6
7var circles = svgContainer.selectAll("circle")
8                          .data(spaceCircles)
9                          .enter()
10                          .append("circle");
11
12var circleAttributes = circles
13                       .attr("cx", function (d) { return d; })
14                       .attr("cy", function (d) { return d; })
15                       .attr("r", 20 );```

As you can see from the above code, we added the attributes to our circle selection. The data set specifies the circle center's x-coordinate and y-coordinate, so we use D3.js to update the "cx" and "cy" SVG Circle Element attribute for each SVG Circle.

If we run this in the JavaScript Console we get: We are getting close. We now have three SVG Circle Elements and their coordinates correspond to the coordinates given in the the data set. The last thing we have to do is to color the SVG Circle based on the data.

### Styling SVG Elements Based on Data Revisited

If you recall the Creating SVG Elements Based on Data section, we used the bound data to alter the SVG element's style.

As we saw before, D3.js lets us use a function inside of the .style() operator - which means we can write the following:

``` 1var spaceCircles = [30, 70, 110];
2
3var svgContainer = d3.select("body").append("svg")
4                                    .attr("width", 200)
5                                    .attr("height", 200);
6
7var circles = svgContainer.selectAll("circle")
8                          .data(spaceCircles)
9                          .enter()
10                          .append("circle");
11
12var circleAttributes = circles
13                       .attr("cx", function (d) { return d; })
14                       .attr("cy", function (d) { return d; })
15                       .attr("r", 20 )
16                       .style("fill", function(d) {
17                         var returnColor;
18                         if (d === 30) { returnColor = "green";
19                         } else if (d === 70) { returnColor = "purple";
20                         } else if (d === 110) { returnColor = "red"; }
21                         return returnColor;
22                       });```

Running the above JavaScript code in the JavaScript Console gives us this: Congratulations - You created, styled, and placed SVG elements in the SVG Coordinate Space based on data from a data set!

If you found this D3 Tutorial helpful, you'll enjoy these FREE videos:
{"ft_lang_label":"__label__en","ft_lang_prob":0.6630361,"math_prob":0.9540021,"size":6926,"snap":"2019-51-2020-05","text_gpt3_token_len":1831,"char_repetition_ratio":0.15096793,"word_repetition_ratio":0.19794345,"special_character_ratio":0.29223216,"punctuation_ratio":0.14683369,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97416747,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22],"im_url_duplicate_count":[null,2,null,2,null,2,null,2,null,2,null,6,null,2,null,6,null,2,null,2,null,2,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-01-17T12:53:43Z\",\"WARC-Record-ID\":\"<urn:uuid:d0b1244e-ba9c-4da1-82a7-7576059013ea>\",\"Content-Length\":\"52027\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:4285720e-53e8-4af3-a0eb-a77e2b439e29>\",\"WARC-Concurrent-To\":\"<urn:uuid:4f9f9123-18b7-40e8-852b-0afddb6351e3>\",\"WARC-IP-Address\":\"34.236.27.247\",\"WARC-Target-URI\":\"https://www.dashingd3js.com/using-the-svg-coordinate-space\",\"WARC-Payload-Digest\":\"sha1:EPIODHYVWUIK4TWK5EHPFNQSFMTRQALD\",\"WARC-Block-Digest\":\"sha1:YVXNGXOICHQYMAP5UVAH5FEJOQL7DGJ3\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-05/CC-MAIN-2020-05_segments_1579250589560.16_warc_CC-MAIN-20200117123339-20200117151339-00250.warc.gz\"}"}