chore(i18n,curriculum): update translations (#43018)
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa6367417b2b2512bc2
|
||||
title: Add Document Elements with D3
|
||||
title: Adicionar elementos de documento com D3
|
||||
challengeType: 6
|
||||
forumTopicId: 301474
|
||||
dashedName: add-document-elements-with-d3
|
||||
@@ -8,23 +8,23 @@ dashedName: add-document-elements-with-d3
|
||||
|
||||
# --description--
|
||||
|
||||
D3 has several methods that let you add and change elements in your document.
|
||||
O D3 tem vários métodos que permitem adicionar e alterar elementos ao documento.
|
||||
|
||||
The `select()` method selects one element from the document. It takes an argument for the name of the element you want and returns an HTML node for the first element in the document that matches the name. Here's an example:
|
||||
O método `select()` seleciona um elemento do documento. Ele recebe um argumento para o nome do elemento que você deseja e retorna um nó de HTML para o primeiro elemento do documento que corresponde ao nome. Exemplo:
|
||||
|
||||
```js
|
||||
const anchor = d3.select("a");
|
||||
```
|
||||
|
||||
The above example finds the first anchor tag on the page and saves an HTML node for it in the variable `anchor`. You can use the selection with other methods. The `d3` part of the example is a reference to the D3 object, which is how you access D3 methods.
|
||||
O exemplo acima encontra a primeira tag de âncora na página e salva um nó de HTML para ela na variável `anchor`. Você pode usar a seleção com outros métodos. A parte que diz `d3` do exemplo é uma referência ao objeto do D3, que é a maneira de acessar os métodos do D3.
|
||||
|
||||
Two other useful methods are `append()` and `text()`.
|
||||
Dois outros métodos úteis são `append()` e `text()`.
|
||||
|
||||
The `append()` method takes an argument for the element you want to add to the document. It appends an HTML node to a selected item, and returns a handle to that node.
|
||||
O método `append()` tem um argumento para o elemento que você deseja adicionar ao documento. Ele anexa um nó de HTML a um item selecionado e retorna um identificador para esse nó.
|
||||
|
||||
The `text()` method either sets the text of the selected node, or gets the current text. To set the value, you pass a string as an argument inside the parentheses of the method.
|
||||
O método `text()` define o texto do nó selecionado ou obtém o texto atual. Para definir o valor, você passa uma string como um argumento dentro dos parênteses do método.
|
||||
|
||||
Here's an example that selects an unordered list, appends a list item, and adds text:
|
||||
Aqui está um exemplo que seleciona uma lista não ordenada, associa um item de lista e adiciona texto:
|
||||
|
||||
```js
|
||||
d3.select("ul")
|
||||
@@ -32,45 +32,45 @@ d3.select("ul")
|
||||
.text("Very important item");
|
||||
```
|
||||
|
||||
D3 allows you to chain several methods together with periods to perform a number of actions in a row.
|
||||
O D3 permite que você encadeie vários métodos juntamente com períodos para realizar várias ações em sequência.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `select` method to select the `body` tag in the document. Then `append` an `h1` tag to it, and add the text `Learning D3` into the `h1` element.
|
||||
Use o método `select` para selecionar a tag `body` do documento. Em seguida, use o método `append` em uma tag `h1` e adicione o texto `Learning D3` no elemento `h1`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `body` should have one `h1` element.
|
||||
A tag `body` deve ter um elemento `h1`.
|
||||
|
||||
```js
|
||||
assert($('body').children('h1').length == 1);
|
||||
```
|
||||
|
||||
The `h1` element should have the text `Learning D3` in it.
|
||||
O elemento `h1` deve conter o texto `Learning D3`.
|
||||
|
||||
```js
|
||||
assert($('h1').text() == 'Learning D3');
|
||||
```
|
||||
|
||||
Your code should access the `d3` object.
|
||||
O código deve acessar o objeto `d3`.
|
||||
|
||||
```js
|
||||
assert(code.match(/d3/g));
|
||||
```
|
||||
|
||||
Your code should use the `select` method.
|
||||
O código deve usar o método `select`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.select/g));
|
||||
```
|
||||
|
||||
Your code should use the `append` method.
|
||||
O código deve usar o método `append`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.append/g));
|
||||
```
|
||||
|
||||
Your code should use the `text` method.
|
||||
O código deve usar o método `text`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.text/g));
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa7367417b2b2512bc6
|
||||
title: Add Inline Styling to Elements
|
||||
title: Adicionar estilo em linha aos elementos
|
||||
challengeType: 6
|
||||
forumTopicId: 301475
|
||||
dashedName: add-inline-styling-to-elements
|
||||
@@ -8,9 +8,9 @@ dashedName: add-inline-styling-to-elements
|
||||
|
||||
# --description--
|
||||
|
||||
D3 lets you add inline CSS styles on dynamic elements with the `style()` method.
|
||||
O D3 permite adicionar estilos CSS em linha em elementos dinâmicos com o método `style()`.
|
||||
|
||||
The `style()` method takes a comma-separated key-value pair as an argument. Here's an example to set the selection's text color to blue:
|
||||
O método `style()` receb um par chave-valor separado por vírgulas como argumento. Aqui está um exemplo para definir a cor do texto da seleção como azul:
|
||||
|
||||
```js
|
||||
selection.style("color","blue");
|
||||
@@ -18,17 +18,17 @@ selection.style("color","blue");
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the `style()` method to the code in the editor to make all the displayed text have a `font-family` of `verdana`.
|
||||
Adicione o método `style()` ao código no editor para fazer com que todo o texto exibido tenha a `font-family` `verdana`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `h2` elements should have a `font-family` of `verdana`.
|
||||
Os elementos `h2` devem ter a propriedade `font-family` `verdana`.
|
||||
|
||||
```js
|
||||
assert($('h2').css('font-family') == 'verdana');
|
||||
```
|
||||
|
||||
Your code should use the `style()` method.
|
||||
O código deve usar o método `style()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.style/g));
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7faa367417b2b2512bd2
|
||||
title: Add Labels to D3 Elements
|
||||
title: Adicionar etiquetas aos elementos D3
|
||||
challengeType: 6
|
||||
forumTopicId: 301476
|
||||
dashedName: add-labels-to-d3-elements
|
||||
@@ -8,69 +8,69 @@ dashedName: add-labels-to-d3-elements
|
||||
|
||||
# --description--
|
||||
|
||||
D3 lets you label a graph element, such as a bar, using the SVG `text` element.
|
||||
O D3 permite adicionar etiquetas a um elemento gráfico, como uma barra, usando o elemento `text` do SVG.
|
||||
|
||||
Like the `rect` element, a `text` element needs to have `x` and `y` attributes, to place it on the SVG canvas. It also needs to access the data to display those values.
|
||||
Assim como o elemento `rect`, um elemento `text` precisa ter atributos `x` e `y` para ser inserido no canvas do SVG. Ele também precisa de ter acesso aos dados para exibir esses valores.
|
||||
|
||||
D3 gives you a high level of control over how you label your bars.
|
||||
O D3 dá a você um alto nível de controle sobre como você etiqueta suas barras.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code in the editor already binds the data to each new `text` element. First, append `text` nodes to the `svg`. Next, add attributes for the `x` and `y` coordinates. They should be calculated the same way as the `rect` ones, except the `y` value for the `text` should make the label sit 3 units higher than the bar. Finally, use the D3 `text()` method to set the label equal to the data point value.
|
||||
O código no editor já vincula os dados a cada novo elemento `text`. Primeiro, insira nós `text` no `svg`. Em seguida, adicione atributos às coordenadas `x` e `y`. Eles devem ser calculados da mesma forma que os atributos de `rect`, exceto pelo fato de que o valor de `y` para `text` fará com que a etiqueta fique 3 unidades acima da barra. Por fim, use o método `text()` do D3 para definir a nova etiqueta como o valor do ponto de dados.
|
||||
|
||||
**Note:** For the label to sit higher than the bar, decide if the `y` value for the `text` should be 3 greater or 3 less than the `y` value for the bar.
|
||||
**Observação:** para a etiqueta ficar mais alta do que a barra, decida se o valor de `y` para o `text` deve ser 3 a mais ou 3 a menos do que o valor de `y` da barra.
|
||||
|
||||
# --hints--
|
||||
|
||||
The first `text` element should have a label of `12` and a `y` value of `61`.
|
||||
O primeiro elemento `text` deve ter uma etiqueta com o valor `12` e um `y` com o valor de `61`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(0).text() == '12' && $('text').eq(0).attr('y') == '61');
|
||||
```
|
||||
|
||||
The second `text` element should have a label of `31` and a `y` value of `4`.
|
||||
O segundo elemento `text` deve ter uma etiqueta com o valor `31` e um `y` com o valor de `4`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(1).text() == '31' && $('text').eq(1).attr('y') == '4');
|
||||
```
|
||||
|
||||
The third `text` element should have a label of `22` and a `y` value of `31`.
|
||||
O terceiro elemento `text` deve ter uma etiqueta com o valor `22` e um `y` com o valor de `31`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(2).text() == '22' && $('text').eq(2).attr('y') == '31');
|
||||
```
|
||||
|
||||
The fourth `text` element should have a label of `17` and a `y` value of `46`.
|
||||
O quarto elemento `text` deve ter uma etiqueta com o valor `17` e um `y` com o valor de `46`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(3).text() == '17' && $('text').eq(3).attr('y') == '46');
|
||||
```
|
||||
|
||||
The fifth `text` element should have a label of `25` and a `y` value of `22`.
|
||||
O quinto elemento `text` deve ter uma etiqueta com o valor `25` e um `y` com o valor de `22`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(4).text() == '25' && $('text').eq(4).attr('y') == '22');
|
||||
```
|
||||
|
||||
The sixth `text` element should have a label of `18` and a `y` value of `43`.
|
||||
O sexto elemento `text` deve ter uma etiqueta com o valor `18` e um `y` com o valor de `43`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(5).text() == '18' && $('text').eq(5).attr('y') == '43');
|
||||
```
|
||||
|
||||
The seventh `text` element should have a label of `29` and a `y` value of `10`.
|
||||
O sétimo elemento `text` deve ter uma etiqueta com o valor `29` e um `y` com o valor de `10`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(6).text() == '29' && $('text').eq(6).attr('y') == '10');
|
||||
```
|
||||
|
||||
The eighth `text` element should have a label of `14` and a `y` value of `55`.
|
||||
O oitavo elemento `text` deve ter uma etiqueta com o valor `14` e um `y` com o valor de `55`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(7).text() == '14' && $('text').eq(7).attr('y') == '55');
|
||||
```
|
||||
|
||||
The ninth `text` element should have a label of `9` and a `y` value of `70`.
|
||||
O nono elemento `text` deve ter uma etiqueta com o valor `9` e um `y` com o valor de `70`.
|
||||
|
||||
```js
|
||||
assert($('text').eq(8).text() == '9' && $('text').eq(8).attr('y') == '70');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fab367417b2b2512bd9
|
||||
title: Add Labels to Scatter Plot Circles
|
||||
title: Adicionar etiquetas aos círculos do diagrama de dispersão
|
||||
challengeType: 6
|
||||
forumTopicId: 301477
|
||||
dashedName: add-labels-to-scatter-plot-circles
|
||||
@@ -8,25 +8,25 @@ dashedName: add-labels-to-scatter-plot-circles
|
||||
|
||||
# --description--
|
||||
|
||||
You can add text to create labels for the points in a scatter plot.
|
||||
Você pode adicionar texto para criar etiquetas para os pontos em um diagrama de dispersão.
|
||||
|
||||
The goal is to display the comma-separated values for the first (`x`) and second (`y`) fields of each item in `dataset`.
|
||||
O objetivo é exibir os valores separados por vírgula para o primeiro (`x`) e para o segundo (`y`) campo de cada item do `dataset`.
|
||||
|
||||
The `text` nodes need `x` and `y` attributes to position it on the SVG canvas. In this challenge, the `y` value (which determines height) can use the same value that the `circle` uses for its `cy` attribute. The `x` value can be slightly larger than the `cx` value of the `circle`, so the label is visible. This will push the label to the right of the plotted point.
|
||||
Os nós de `text` precisam de atributos `x` e `y` para posicioná-los no canvas do SVG. Neste desafio, o valor de `y` (que determina a altura) pode usar o mesmo valor que `circle` usa para o seu atributo `cy`. O valor de `x` pode ser ligeiramente maior que do que o valor de `cx` de `circle`. Assim, a etiqueta estará visível. Isto empurrará a etiqueta para a direita do ponto traçado.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Label each point on the scatter plot using the `text` elements. The text of the label should be the two values separated by a comma and a space. For example, the label for the first point is `34, 78`. Set the `x` attribute so it's `5` units more than the value you used for the `cx` attribute on the `circle`. Set the `y` attribute the same way that's used for the `cy` value on the `circle`.
|
||||
Dê uma etiqueta a cada ponto no diagrama de dispersão usando o elemento `text`. O texto da etiqueta deve ter os dois valores separados por uma vírgula e um espaço. Por exemplo, a etiqueta para o primeiro ponto será `34, 78`. Defina o atributo `x` para que seja de `5` unidades a mais do que o valor usado para o atributo `cx` em `circle`. Defina o atributo `y` para que seja igual ao valor de `cy` em `circle`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should have 10 `text` elements.
|
||||
O código deve ter 10 elementos `text`.
|
||||
|
||||
```js
|
||||
assert($('text').length == 10);
|
||||
```
|
||||
|
||||
The first label should have text of `34, 78`, an `x` value of `39`, and a `y` value of `422`.
|
||||
A primeira etiqueta deve ter o texto `34, 78`, um valor de `x` de `39` e um valor de `y` de `422`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -36,7 +36,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The second label should have text of `109, 280`, an `x` value of `114`, and a `y` value of `220`.
|
||||
A segunda etiqueta deve ter o texto `109, 280`, um valor de `x` de `114` e um valor de `y` de `220`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -46,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The third label should have text of `310, 120`, an `x` value of `315`, and a `y` value of `380`.
|
||||
A terceira etiqueta deve ter o texto `310, 120`, um valor de `x` de `315` e um valor de `y` de `380`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -56,7 +56,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fourth label should have text of `79, 411`, an `x` value of `84`, and a `y` value of `89`.
|
||||
A quarta etiqueta deve ter o texto `79, 411`, um valor de `x` de `84` e um valor de `y` de `89`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -66,7 +66,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fifth label should have text of `420, 220`, an `x` value of `425`, and a `y` value of `280`.
|
||||
A quinta etiqueta deve ter o texto `420, 220`, um valor de `x` de `425` e um valor de `y` de `280`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -76,7 +76,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The sixth label should have text of `233, 145`, an `x` value of `238`, and a `y` value of `355`.
|
||||
A sexta etiqueta deve ter o texto `233, 145`, um valor de `x` de `238` e um valor de `y` de `355`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -86,7 +86,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The seventh label should have text of `333, 96`, an `x` value of `338`, and a `y` value of `404`.
|
||||
A sétima etiqueta deve ter o texto `333, 96`, um valor de `x` de `338` e um valor de `y` de `404`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -96,7 +96,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The eighth label should have text of `222, 333`, an `x` value of `227`, and a `y` value of `167`.
|
||||
A oitava etiqueta deve ter o texto `222, 333`, um valor de `x` de `227` e um valor de `y` de `167`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -106,7 +106,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The ninth label should have text of `78, 320`, an `x` value of `83`, and a `y` value of `180`.
|
||||
A nona etiqueta deve ter o texto `78, 320`, um valor de `x` de `83` e um valor de `y` de `180`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -116,7 +116,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The tenth label should have text of `21, 123`, an `x` value of `26`, and a `y` value of `377`.
|
||||
A décima etiqueta deve ter o texto `21, 123`, um valor de `x` de `26` e um valor de `y` de `377`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa7367417b2b2512bc7
|
||||
title: Change Styles Based on Data
|
||||
title: Alterar estilos com base nos dados
|
||||
challengeType: 6
|
||||
forumTopicId: 301479
|
||||
dashedName: change-styles-based-on-data
|
||||
@@ -8,9 +8,9 @@ dashedName: change-styles-based-on-data
|
||||
|
||||
# --description--
|
||||
|
||||
D3 is about visualization and presentation of data. It's likely you'll want to change the styling of elements based on the data. You can use a callback function in the `style()` method to change the styling for different elements.
|
||||
O D3 tem a ver com a visualização e a apresentação dos dados. Você provavelmente vai querer alterar o estilo de elementos com base nos dados. Você pode usar uma função de callback no método `style()` para mudar a estilização para elementos diferentes.
|
||||
|
||||
For example, you may want to color a data point blue if it has a value less than 20, and red otherwise. You can use a callback function in the `style()` method and include the conditional logic. The callback function uses the `d` parameter to represent the data point:
|
||||
Por exemplo, pode ser que você queira colorir um ponto dos dados em azul se ele tiver um valor inferior a 20, ou em vermelho se for igual ou superior. Você pode usar uma função de callback no método `style()` e incluir uma lógica condicional. A função de callback usa o parâmetro `d` para representar o ponto de dados:
|
||||
|
||||
```js
|
||||
selection.style("color", (d) => {
|
||||
@@ -18,65 +18,65 @@ selection.style("color", (d) => {
|
||||
});
|
||||
```
|
||||
|
||||
The `style()` method is not limited to setting the `color` - it can be used with other CSS properties as well.
|
||||
O método `style()` não é limitado a definir `color` - ele também pode ser usado com outras propriedades do CSS.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the `style()` method to the code in the editor to set the `color` of the `h2` elements conditionally. Write the callback function so if the data value is less than 20, it returns red, otherwise it returns green.
|
||||
Adicione o método `style()` ao código no editor para definir `color` para os elementos `h2` de modo condicional. Escreva a função de callback de modo que, se o valor do dado for inferior a 20, ela retornará "red" (vermelho). Do contrário, retornará "green" (verde).
|
||||
|
||||
**Note:** You can use if-else logic, or the ternary operator.
|
||||
**Observação:** você pode usar a lógica de if-else ou o operador ternário.
|
||||
|
||||
# --hints--
|
||||
|
||||
The first `h2` should have a `color` of red.
|
||||
O primeiro `h2` deve ter `color` definido como "red".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(0).css('color') == 'rgb(255, 0, 0)');
|
||||
```
|
||||
|
||||
The second `h2` should have a `color` of green.
|
||||
O segundo `h2` deve ter `color` definido como "green".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(1).css('color') == 'rgb(0, 128, 0)');
|
||||
```
|
||||
|
||||
The third `h2` should have a `color` of green.
|
||||
O terceiro `h2` deve ter `color` definido como "green".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(2).css('color') == 'rgb(0, 128, 0)');
|
||||
```
|
||||
|
||||
The fourth `h2` should have a `color` of red.
|
||||
O quarto `h2` deve ter `color` definido como "red".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(3).css('color') == 'rgb(255, 0, 0)');
|
||||
```
|
||||
|
||||
The fifth `h2` should have a `color` of green.
|
||||
O quinto `h2` deve ter `color` definido como "green".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(4).css('color') == 'rgb(0, 128, 0)');
|
||||
```
|
||||
|
||||
The sixth `h2` should have a `color` of red.
|
||||
O quinto `h2` deve ter `color` definido como "red".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(5).css('color') == 'rgb(255, 0, 0)');
|
||||
```
|
||||
|
||||
The seventh `h2` should have a `color` of green.
|
||||
O sétimo `h2` deve ter `color` definido como "green".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(6).css('color') == 'rgb(0, 128, 0)');
|
||||
```
|
||||
|
||||
The eighth `h2` should have a `color` of red.
|
||||
O oitavo `h2` deve ter `color` definido como "red".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(7).css('color') == 'rgb(255, 0, 0)');
|
||||
```
|
||||
|
||||
The ninth `h2` should have a `color` of red.
|
||||
O nono `h2` deve ter `color` definido como "red".
|
||||
|
||||
```js
|
||||
assert($('h2').eq(8).css('color') == 'rgb(255, 0, 0)');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa9367417b2b2512bd1
|
||||
title: Change the Color of an SVG Element
|
||||
title: Alterar a cor de um elemento do SVG
|
||||
challengeType: 6
|
||||
forumTopicId: 301480
|
||||
dashedName: change-the-color-of-an-svg-element
|
||||
@@ -8,17 +8,17 @@ dashedName: change-the-color-of-an-svg-element
|
||||
|
||||
# --description--
|
||||
|
||||
The bars are in the right position, but they are all the same black color. SVG has a way to change the color of the bars.
|
||||
As barras estão na posição certa, mas são todas iguais, da cor preta. O SVG tem uma forma de alterar a cor das barras.
|
||||
|
||||
In SVG, a `rect` shape is colored with the `fill` attribute. It supports hex codes, color names, and rgb values, as well as more complex options like gradients and transparency.
|
||||
No SVG, uma forma `rect` é colorida com o atributo `fill`. Esse atributo tem suporte de código hexadecimal, nomes de cores e valores rgb, bem como opções mais complexas, como gradientes e transparência.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add an `attr()` method to set the `fill` of all the bars to the color navy.
|
||||
Adicione um método `attr()` para definir a propriedade `fill` de todas as barras com a cor "navy" (azul-marinho).
|
||||
|
||||
# --hints--
|
||||
|
||||
The bars should all have a `fill` color of navy.
|
||||
As barras devem ter a propriedade `fill` com a cor "navy".
|
||||
|
||||
```js
|
||||
assert($('rect').css('fill') == 'rgb(0, 0, 128)');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa8367417b2b2512bca
|
||||
title: Change the Presentation of a Bar Chart
|
||||
title: Alterar a apresentação de um gráfico de barras
|
||||
challengeType: 6
|
||||
forumTopicId: 301481
|
||||
dashedName: change-the-presentation-of-a-bar-chart
|
||||
@@ -8,21 +8,21 @@ dashedName: change-the-presentation-of-a-bar-chart
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge created a bar chart, but there are a couple of formatting changes that could improve it:
|
||||
No último desafio, criamos um gráfico de barras, mas há algumas mudanças de formatação que poderiam melhorá-lo:
|
||||
|
||||
1) Add space between each bar to visually separate them, which is done by adding a margin to the CSS for the `bar` class
|
||||
1) Adicione espaço entre cada barra para separá-las visualmente. Isso é feito adicionando uma margem ao CSS para a classe `bar`
|
||||
|
||||
2) Increase the height of the bars to better show the difference in values, which is done by multiplying the value by a number to scale the height
|
||||
2) Aumente a altura das barras para mostrar melhor a diferença dos valores. Isso é feito multiplicando o valor por um número para dimensionar a altura
|
||||
|
||||
# --instructions--
|
||||
|
||||
First, add a `margin` of `2px` to the `bar` class in the `style` tag. Next, change the callback function in the `style()` method so it returns a value `10` times the original data value (plus the `px`).
|
||||
Primeiro, adicione uma `margin` de `2px` à classe `bar` na tag `style`. Depois, altere a função de callback no método `style()` para que retorne um valor `10` vezes maior que o valor original dos dados (e a expressão `px`).
|
||||
|
||||
**Note:** Multiplying each data point by the *same* constant only alters the scale. It's like zooming in, and it doesn't change the meaning of the underlying data.
|
||||
**Observação:** multiplicar cada ponto dos dados pela *mesma* constante somente altera a escala. É como fazer um zoom. Isso não altera o significado dos dados subjacentes.
|
||||
|
||||
# --hints--
|
||||
|
||||
The first `div` should have a `height` of `120` pixels and a `margin` of `2` pixels.
|
||||
A primeira `div` deve ter uma `height` de `120` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -31,7 +31,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The second `div` should have a `height` of `310` pixels and a `margin` of `2` pixels.
|
||||
A segunda `div` deve ter uma `height` de `310` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -40,7 +40,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The third `div` should have a `height` of `220` pixels and a `margin` of `2` pixels.
|
||||
A terceira `div` deve ter uma `height` de `220` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -49,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fourth `div` should have a `height` of `170` pixels and a `margin` of `2` pixels.
|
||||
A quarta `div` deve ter uma `height` de `170` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -58,7 +58,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fifth `div` should have a `height` of `250` pixels and a `margin` of `2` pixels.
|
||||
A quinta `div` deve ter uma `height` de `250` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -67,7 +67,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The sixth `div` should have a `height` of `180` pixels and a `margin` of `2` pixels.
|
||||
A sexta `div` deve ter uma `height` de `180` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -76,7 +76,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The seventh `div` should have a `height` of `290` pixels and a `margin` of `2` pixels.
|
||||
A sétima `div` deve ter uma `height` de `290` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -85,7 +85,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The eighth `div` should have a `height` of `140` pixels and a `margin` of `2` pixels.
|
||||
A oitava `div` deve ter uma `height` de `140` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -94,7 +94,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The ninth `div` should have a `height` of `90` pixels and a `margin` of `2` pixels.
|
||||
A nona `div` deve ter uma `height` de `90` pixels e uma `margin` de `2` pixels.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa8367417b2b2512bcd
|
||||
title: Create a Bar for Each Data Point in the Set
|
||||
title: Criar uma barra para cada ponto de dados no conjunto
|
||||
challengeType: 6
|
||||
forumTopicId: 301482
|
||||
dashedName: create-a-bar-for-each-data-point-in-the-set
|
||||
@@ -8,9 +8,9 @@ dashedName: create-a-bar-for-each-data-point-in-the-set
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge added only one rectangle to the `svg` element to represent a bar. Here, you'll combine what you've learned so far about `data()`, `enter()`, and SVG shapes to create and append a rectangle for each data point in `dataset`.
|
||||
O último desafio adicionou apenas um retângulo ao elemento `svg` para representar uma barra. Aqui, você vai combinar o que você aprendeu até agora sobre `data()`, `enter()` e formas do SVG para criar e incluir um retângulo para cada ponto de dados no `dataset`.
|
||||
|
||||
A previous challenge showed the format for how to create and append a `div` for each item in `dataset`:
|
||||
Um desafio anterior mostrou o formato para criar e acrescentar um `div` para cada item no `dataset`:
|
||||
|
||||
```js
|
||||
d3.select("body").selectAll("div")
|
||||
@@ -19,33 +19,33 @@ d3.select("body").selectAll("div")
|
||||
.append("div")
|
||||
```
|
||||
|
||||
There are a few differences working with `rect` elements instead of `div` elements. The `rect` elements must be appended to an `svg` element, not directly to the `body`. Also, you need to tell D3 where to place each `rect` within the `svg` area. The bar placement will be covered in the next challenge.
|
||||
Existem algumas diferenças ao trabalhar com elementos `rect` em vez de elementos `div`. Os elementos `rect` devem ser incluídos em um elemento `svg`, não diretamente no `body`. Além disso, você precisa dizer ao D3 onde colocar cada `rect` na área do `svg`. O posicionamento da barra será tratado no próximo desafio.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `data()`, `enter()`, and `append()` methods to create and append a `rect` for each item in `dataset`. The bars should display all on top of each other; this will be fixed in the next challenge.
|
||||
Use os métodos `data()`, `enter()` e `append()` para criar e incluir um `rect` para cada item no `dataset`. As barras devem ser exibidas em cima umas das outras. Isto será corrigido no próximo desafio.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your document should have 9 `rect` elements.
|
||||
O documento deve ter 9 elementos `rect`.
|
||||
|
||||
```js
|
||||
assert($('rect').length == 9);
|
||||
```
|
||||
|
||||
Your code should use the `data()` method.
|
||||
O código deve usar o método `data()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.data/g));
|
||||
```
|
||||
|
||||
Your code should use the `enter()` method.
|
||||
O código deve usar o método `enter()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.enter/g));
|
||||
```
|
||||
|
||||
Your code should use the `append()` method.
|
||||
O código deve usar o método `append()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.append/g));
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fab367417b2b2512bda
|
||||
title: Create a Linear Scale with D3
|
||||
title: Criar uma escala linear com o D3
|
||||
challengeType: 6
|
||||
forumTopicId: 301483
|
||||
dashedName: create-a-linear-scale-with-d3
|
||||
@@ -8,41 +8,41 @@ dashedName: create-a-linear-scale-with-d3
|
||||
|
||||
# --description--
|
||||
|
||||
The bar and scatter plot charts both plotted data directly onto the SVG canvas. However, if the height of a bar or one of the data points were larger than the SVG height or width values, it would go outside the SVG area.
|
||||
O gráfico de barras e o diagrama de dispersão traçam os dados diretamente no canvas do SVG. No entanto, se a altura de uma barra ou de um dos pontos de dados for maior que os valores de altura ou de largura do SVG, acabaria saindo dá área do SVG.
|
||||
|
||||
In D3, there are scales to help plot data. `scales` are functions that tell the program how to map a set of raw data points onto the pixels of the SVG canvas.
|
||||
No D3, há escalas para ajudar a traçar os dados. As `scales` são funções que dizem ao programa como mapear um conjunto de pontos de dados brutos para os pixels do canvas do SVG.
|
||||
|
||||
For example, say you have a 100x500-sized SVG canvas and you want to plot Gross Domestic Product (GDP) for a number of countries. The set of numbers would be in the billion or trillion-dollar range. You provide D3 a type of scale to tell it how to place the large GDP values into that 100x500-sized area.
|
||||
Por exemplo, digamos que você tem um canvas de SVG de 100x500 de tamanho e que deseja representar o produto interno bruto (PIB) de vários países. O conjunto dos números estaria na faixa de bilhões ou trilhões de dólares. Você fornece ao D3 um tipo de escala para dizer como colocar os grandes valores do PIB naquela área de tamanho de 100x500.
|
||||
|
||||
It's unlikely you would plot raw data as-is. Before plotting it, you set the scale for your entire data set, so that the `x` and `y` values fit your canvas width and height.
|
||||
É improvável que você trace os dados brutos como estão. Antes de desenhá-los, defina a escala de todo o seu conjunto de dados, de modo que os valores de `x` e `y` se ajustem à largura e à altura do canvas.
|
||||
|
||||
D3 has several scale types. For a linear scale (usually used with quantitative data), there is the D3 method `scaleLinear()`:
|
||||
O D3 tem vários tipos de escala. Para uma escala linear (geralmente usada com dados quantitativos), existe o método `scaleLinear()` do D3:
|
||||
|
||||
```js
|
||||
const scale = d3.scaleLinear()
|
||||
```
|
||||
|
||||
By default, a scale uses the identity relationship. The value of the input is the same as the value of the output. A separate challenge covers how to change this.
|
||||
Por padrão, uma escala usa a relação de identidade. O valor de entrada é o mesmo que o valor de saída. Um desafio separado trata da maneira de alterar esta situação.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `scale` variable to create a linear scale. Then set the `output` variable to the scale called with an input argument of `50`.
|
||||
Altere a variável `scale` para criar uma escala linear. Em seguida, defina a variável `output` como a escala chamada com um argumento de entrada de `50`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The text in the `h2` should be `50`.
|
||||
O texto no `h2` deve ser `50`.
|
||||
|
||||
```js
|
||||
assert($('h2').text() == '50');
|
||||
```
|
||||
|
||||
Your code should use the `scaleLinear()` method.
|
||||
O código deve usar o método `scaleLinear()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.scaleLinear/g));
|
||||
```
|
||||
|
||||
The `output` variable should call `scale` with an argument of `50`.
|
||||
A variável `output` deve chamar a `scale` com um argumento de `50`.
|
||||
|
||||
```js
|
||||
assert(output == 50 && code.match(/scale\(\s*?50\s*?\)/g));
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fab367417b2b2512bd7
|
||||
title: Create a Scatterplot with SVG Circles
|
||||
title: Criar um diagrama de dispersão com círculos do SVG
|
||||
challengeType: 6
|
||||
forumTopicId: 301484
|
||||
dashedName: create-a-scatterplot-with-svg-circles
|
||||
@@ -8,19 +8,19 @@ dashedName: create-a-scatterplot-with-svg-circles
|
||||
|
||||
# --description--
|
||||
|
||||
A scatter plot is another type of visualization. It usually uses circles to map data points, which have two values each. These values tie to the `x` and `y` axes, and are used to position the circle in the visualization.
|
||||
Um diagrama de dispersão é outro tipo de visualização. Ele geralmente usa círculos para mapear pontos de dados, que têm dois valores cada. Esses valores estão relacionados aos eixos `x` e `y`, sendo usados para posicionar o círculo na visualização.
|
||||
|
||||
SVG has a `circle` tag to create the circle shape. It works a lot like the `rect` elements you used for the bar chart.
|
||||
O SVG tem uma tag `circle` para criar a forma do círculo. Funciona muito parecido com os elementos `rect` que você usou para o gráfico de barras.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `data()`, `enter()`, and `append()` methods to bind `dataset` to new `circle` elements that are appended to the SVG canvas.
|
||||
Use os métodos `data()`, `enter()` e `append()` para associar o `dataset` aos novos elementos de `circle` que são incluídos no canvas do SVG.
|
||||
|
||||
**Note:** The circles won't be visible because we haven't set their attributes yet. We'll do that in the next challenge.
|
||||
**Observação:** os círculos não serão visíveis porque ainda não definimos seus atributos. Faremos isso no próximo desafio.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should have 10 `circle` elements.
|
||||
O código deve ter 10 elementos `circle`.
|
||||
|
||||
```js
|
||||
assert($('circle').length == 10);
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa8367417b2b2512bcc
|
||||
title: Display Shapes with SVG
|
||||
title: Exibir formas com o SVG
|
||||
challengeType: 6
|
||||
forumTopicId: 301485
|
||||
dashedName: display-shapes-with-svg
|
||||
@@ -8,47 +8,47 @@ dashedName: display-shapes-with-svg
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge created an `svg` element with a given width and height, which was visible because it had a `background-color` applied to it in the `style` tag. The code made space for the given width and height.
|
||||
O último desafio criou um elemento `svg` com uma determinada largura e altura, que era visível porque tinha uma `background-color` aplicada a ele na tag `style`. O código criou espaço para a largura e altura fornecidas.
|
||||
|
||||
The next step is to create a shape to put in the `svg` area. There are a number of supported shapes in SVG, such as rectangles and circles. They are used to display data. For example, a rectangle (`<rect>`) SVG shape could create a bar in a bar chart.
|
||||
O próximo passo é criar uma forma para colocar na área do `svg`. Há várias formas suportadas no SVG, como retângulos e círculos. Elas são usadas para exibir dados. Por exemplo, a forma do retângulo (`<rect>`) do SVG pode criar uma barra em um gráfico de barras.
|
||||
|
||||
When you place a shape into the `svg` area, you can specify where it goes with `x` and `y` coordinates. The origin point of (0, 0) is in the upper-left corner. Positive values for `x` push the shape to the right, and positive values for `y` push the shape down from the origin point.
|
||||
Quando você coloca uma forma na área do `svg`, você pode especificar onde ela vai com as coordenadas `x` e `y`. O ponto de origem (0, 0) está no canto superior esquerdo. Valores positivos para `x` empurram a forma para a direita, enquanto valores positivos para `y` empurram a forma para baixo do ponto de origem.
|
||||
|
||||
To place a shape in the middle of the 500 (width) x 100 (height) `svg` from last challenge, the `x` coordinate would be 250 and the `y` coordinate would be 50.
|
||||
Para colocar uma forma no meio do `svg` de 500 (largura) x 100 (altura) do último desafio, a coordenada `x` seria 250 e a coordenada `y` seria 50.
|
||||
|
||||
An SVG `rect` has four attributes. There are the `x` and `y` coordinates for where it is placed in the `svg` area. It also has a `height` and `width` to specify the size.
|
||||
Uma forma `rect` do SVG tem quatro atributos. Existem as coordenadas `x` e `y`, para onde elas são colocadas na área do `svg`. Ela também tem `height` e `width` para especificar o tamanho.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a `rect` shape to the `svg` using `append()`, and give it a `width` attribute of `25` and `height` attribute of `100`. Also, give the `rect` `x` and `y` attributes each set to `0`.
|
||||
Adicione uma forma `rect` ao `svg` usando `append()`. Dê a ele um atributo `width` de `25` e uma `height` de `100`. Além disso, dê aos atributos de `rect`, `x` e `y`, o valor de `0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your document should have 1 `rect` element.
|
||||
O documento deve ter 1 elemento `rect`.
|
||||
|
||||
```js
|
||||
assert($('rect').length == 1);
|
||||
```
|
||||
|
||||
The `rect` element should have a `width` attribute set to `25`.
|
||||
O elemento `rect` deve ter um atributo `width` com o valor de `25`.
|
||||
|
||||
```js
|
||||
assert($('rect').attr('width') == '25');
|
||||
```
|
||||
|
||||
The `rect` element should have a `height` attribute set to `100`.
|
||||
O elemento `rect` deve ter um atributo `height` com o valor de `100`.
|
||||
|
||||
```js
|
||||
assert($('rect').attr('height') == '100');
|
||||
```
|
||||
|
||||
The `rect` element should have an `x` attribute set to `0`.
|
||||
O elemento `rect` deve ter um atributo `x` com o valor de `0`.
|
||||
|
||||
```js
|
||||
assert($('rect').attr('x') == '0');
|
||||
```
|
||||
|
||||
The `rect` element should have a `y` attribute set to `0`.
|
||||
O elemento `rect` deve ter um atributo `y` com o valor de `0`.
|
||||
|
||||
```js
|
||||
assert($('rect').attr('y') == '0');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa9367417b2b2512bcf
|
||||
title: Dynamically Change the Height of Each Bar
|
||||
title: Alterar dinamicamente a altura de cada barra
|
||||
challengeType: 6
|
||||
forumTopicId: 301486
|
||||
dashedName: dynamically-change-the-height-of-each-bar
|
||||
@@ -8,7 +8,7 @@ dashedName: dynamically-change-the-height-of-each-bar
|
||||
|
||||
# --description--
|
||||
|
||||
The height of each bar can be set to the value of the data point in the array, similar to how the `x` value was set dynamically.
|
||||
A altura de cada barra pode ser definida como o valor do ponto de dados no array, de modo semelhante a como o valor de `x` foi definido dinamicamente.
|
||||
|
||||
```js
|
||||
selection.attr("property", (d, i) => {
|
||||
@@ -16,65 +16,65 @@ selection.attr("property", (d, i) => {
|
||||
})
|
||||
```
|
||||
|
||||
Here `d` would be the data point value, and `i` would be the index of the data point in the array.
|
||||
Aqui, `d` seria o valor do ponto de dados, enquanto `i` seria o índice do ponto de dados no array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the callback function for the `height` attribute to return the data value times 3.
|
||||
Altere a função de callback para o atributo `height` para que retorne o valor dos dados vezes 3.
|
||||
|
||||
**Note:** Remember that multiplying all data points by the same constant scales the data (like zooming in). It helps to see the differences between bar values in this example.
|
||||
**Observação:** lembre-se de que multiplicar todos os dados redimensiona os dados (como se déssemos um zoom). Neste exemplo, ajuda a ver as diferenças entre os valores da barra.
|
||||
|
||||
# --hints--
|
||||
|
||||
The first `rect` should have a `height` of `36`.
|
||||
O primeiro `rect` deve ter uma `height` de `36`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(0).attr('height') == '36');
|
||||
```
|
||||
|
||||
The second `rect` should have a `height` of `93`.
|
||||
O segundo `rect` deve ter uma `height` de `93`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(1).attr('height') == '93');
|
||||
```
|
||||
|
||||
The third `rect` should have a `height` of `66`.
|
||||
O terceiro `rect` deve ter uma `height` de `66`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(2).attr('height') == '66');
|
||||
```
|
||||
|
||||
The fourth `rect` should have a `height` of `51`.
|
||||
O quarto `rect` deve ter uma `height` de `51`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(3).attr('height') == '51');
|
||||
```
|
||||
|
||||
The fifth `rect` should have a `height` of `75`.
|
||||
O quinto `rect` deve ter uma `height` de `75`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(4).attr('height') == '75');
|
||||
```
|
||||
|
||||
The sixth `rect` should have a `height` of `54`.
|
||||
O sexto `rect` deve ter uma `height` de `54`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(5).attr('height') == '54');
|
||||
```
|
||||
|
||||
The seventh `rect` should have a `height` of `87`.
|
||||
O sétimo `rect` deve ter uma `height` de `87`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(6).attr('height') == '87');
|
||||
```
|
||||
|
||||
The eighth `rect` should have a `height` of `42`.
|
||||
O oitavo `rect` deve ter uma `height` de `42`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(7).attr('height') == '42');
|
||||
```
|
||||
|
||||
The ninth `rect` should have a `height` of `27`.
|
||||
O nono `rect` deve ter uma `height` de `27`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(8).attr('height') == '27');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa9367417b2b2512bce
|
||||
title: Dynamically Set the Coordinates for Each Bar
|
||||
title: Definir dinamicamente as coordenadas para cada barra
|
||||
challengeType: 6
|
||||
forumTopicId: 301487
|
||||
dashedName: dynamically-set-the-coordinates-for-each-bar
|
||||
@@ -8,13 +8,13 @@ dashedName: dynamically-set-the-coordinates-for-each-bar
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge created and appended a rectangle to the `svg` element for each point in `dataset` to represent a bar. Unfortunately, they were all stacked on top of each other.
|
||||
No último desafio, você criou e anexou um retângulo ao elemento `svg` para cada ponto do `dataset` para representar uma barra. Infelizmente, todos eles ficaram empilhados um sobre o outro.
|
||||
|
||||
The placement of a rectangle is handled by the `x` and `y` attributes. They tell D3 where to start drawing the shape in the `svg` area. The last challenge set them each to 0, so every bar was placed in the upper-left corner.
|
||||
O posicionamento de um retângulo é realizado pelos atributos `x` e `y`. Eles dizem ao D3 onde começar a desenhar a forma na área `svg`. O último desafio os definiu como 0. Então, todas as barras foram colocadas no canto superior esquerdo.
|
||||
|
||||
For a bar chart, all of the bars should sit on the same vertical level, which means the `y` value stays the same (at 0) for all bars. The `x` value, however, needs to change as you add new bars. Remember that larger `x` values push items farther to the right. As you go through the array elements in `dataset`, the `x` value should increase.
|
||||
Para um gráfico de barras, todas as barras devem ficar no mesmo nível vertical, o que significa que o valor de `y` permanece o mesmo (0) para todas as barras. O valor de `x`, no entanto, precisa ser alterado conforme você adiciona novas barras. Lembre-se de que valores de `x` maiores empurram os itens mais para a direita. À medida que você passa pelos elementos do array no `dataset`, o valor de `x` deve aumentar.
|
||||
|
||||
The `attr()` method in D3 accepts a callback function to dynamically set that attribute. The callback function takes two arguments, one for the data point itself (usually `d`) and one for the index of the data point in the array. The second argument for the index is optional. Here's the format:
|
||||
O método `attr()` do D3 aceita uma função de callback para definir dinamicamente esse atributo. A função de callback recebe dois argumentos, um para os dados em si (geralmente `d`) e um para o índice do ponto dos dados no array. O segundo argumento para o índice é opcional. Este é o formato:
|
||||
|
||||
```js
|
||||
selection.attr("property", (d, i) => {
|
||||
@@ -22,65 +22,65 @@ selection.attr("property", (d, i) => {
|
||||
})
|
||||
```
|
||||
|
||||
It's important to note that you do NOT need to write a `for` loop or use `forEach()` to iterate over the items in the data set. Recall that the `data()` method parses the data set, and any method that's chained after `data()` is run once for each item in the data set.
|
||||
É importante notar que você NÃO precisa escrever um laço `for` ou usar `forEach()` para iterar pelos itens no conjunto de dados. Lembre-se de que o método `data()` analisa o conjunto de dados. Qualquer método que seja encadeado após `data()` é executado uma vez por cada item no conjunto de dados.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `x` attribute callback function so it returns the index times 30.
|
||||
Altere a função de callback `x` para que ela retorne o índice 30 vezes.
|
||||
|
||||
**Note:** Each bar has a width of 25, so increasing each `x` value by 30 adds some space between the bars. Any value greater than 25 would work in this example.
|
||||
**Observação:** cada barra tem uma largura de 25, então aumentar cada valor de `x` por 30 adiciona algum espaço entre as barras. Qualquer valor superior a 25 poderia servir neste exemplo.
|
||||
|
||||
# --hints--
|
||||
|
||||
The first `rect` should have an `x` value of `0`.
|
||||
O primeiro `rect` deve ter um valor de `x` igual a `0`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(0).attr('x') == '0');
|
||||
```
|
||||
|
||||
The second `rect` should have an `x` value of `30`.
|
||||
O segundo `rect` deve ter um valor de `x` igual a `30`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(1).attr('x') == '30');
|
||||
```
|
||||
|
||||
The third `rect` should have an `x` value of `60`.
|
||||
O terceiro `rect` deve ter um valor de `x` igual a `60`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(2).attr('x') == '60');
|
||||
```
|
||||
|
||||
The fourth `rect` should have an `x` value of `90`.
|
||||
O quarto `rect` deve ter um valor de `x` igual a `90`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(3).attr('x') == '90');
|
||||
```
|
||||
|
||||
The fifth `rect` should have an `x` value of `120`.
|
||||
O quinto `rect` deve ter um valor de `x` igual a `120`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(4).attr('x') == '120');
|
||||
```
|
||||
|
||||
The sixth `rect` should have an `x` value of `150`.
|
||||
O sexto `rect` deve ter um valor de `x` igual a `150`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(5).attr('x') == '150');
|
||||
```
|
||||
|
||||
The seventh `rect` should have an `x` value of `180`.
|
||||
O sétimo `rect` deve ter um valor de `x` igual a `180`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(6).attr('x') == '180');
|
||||
```
|
||||
|
||||
The eighth `rect` should have an `x` value of `210`.
|
||||
O oitavo `rect` deve ter um valor de `x` igual a `210`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(7).attr('x') == '210');
|
||||
```
|
||||
|
||||
The ninth `rect` should have an `x` value of `240`.
|
||||
O nono `rect` deve ter um valor de `x` igual a `240`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(8).attr('x') == '240');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa9367417b2b2512bd0
|
||||
title: Invert SVG Elements
|
||||
title: Inverter elementos do SVG
|
||||
challengeType: 6
|
||||
forumTopicId: 301488
|
||||
dashedName: invert-svg-elements
|
||||
@@ -8,73 +8,73 @@ dashedName: invert-svg-elements
|
||||
|
||||
# --description--
|
||||
|
||||
You may have noticed the bar chart looked like it's upside-down, or inverted. This is because of how SVG uses (x, y) coordinates.
|
||||
Você pode ter percebido que o gráfico de barras parecia estar de cabeça para baixo ou invertido. Isso ocorre porque o SVG usa coordenadas (x, y).
|
||||
|
||||
In SVG, the origin point for the coordinates is in the upper-left corner. An `x` coordinate of 0 places a shape on the left edge of the SVG area. A `y` coordinate of 0 places a shape on the top edge of the SVG area. Higher `x` values push the rectangle to the right. Higher `y` values push the rectangle down.
|
||||
No SVG, o ponto de origem para as coordenadas está no canto superior esquerdo. Uma coordenada `x` de 0 coloca uma forma na borda esquerda da área do SVG. Uma coordenada `y` de 0 coloca uma forma na borda superior da área do SVG. Valores mais altos de `x` empurram o retângulo para a direita. Valores mais altos de `y` empurram o retângulo para baixo.
|
||||
|
||||
To make the bars right-side-up, you need to change the way the `y` coordinate is calculated. It needs to account for both the height of the bar and the total height of the SVG area.
|
||||
Para fazer as barras ficarem na posição correta, você precisa alterar a maneira como a coordenada `y` é calculada. Isso precisa levar em conta tanto a altura da barra quanto a altura total da área do SVG.
|
||||
|
||||
The height of the SVG area is 100. If you have a data point of 0 in the set, you would want the bar to start at the bottom of the SVG area (not the top). To do this, the `y` coordinate needs a value of 100. If the data point value were 1, you would start with a `y` coordinate of 100 to set the bar at the bottom. Then you need to account for the height of the bar of 1, so the final `y` coordinate would be 99.
|
||||
A altura da área do SVG é 100. Se você tem um ponto de dados de 0 no conjunto, você deve esperar que a barra comece na parte inferior da área do SVG (não na parte superior). Para fazer isso, a coordenada `y` precisa de um valor de 100. Se o valor do ponto de dados for 1, você começaria com uma coordenada `y` de 100 para definir a barra na parte inferior. Em seguida, você precisa levar em conta a altura da barra de 1. Assim, a coordenada `y` final seria 99.
|
||||
|
||||
The `y` coordinate that is `y = heightOfSVG - heightOfBar` would place the bars right-side-up.
|
||||
A coordenada `y` que é `y = heightOfSVG - heightOfBar` colocaria as barras na posição correta.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the callback function for the `y` attribute to set the bars right-side-up. Remember that the `height` of the bar is 3 times the data value `d`.
|
||||
Altere a função de callback para o atributo `y` para definir a posição das barras no lugar certo. Lembre-se de que a `height` da barra é 3 vezes o valor do dado `d`.
|
||||
|
||||
**Note:** In general, the relationship is `y = h - m * d`, where `m` is the constant that scales the data points.
|
||||
**Observação:** em geral, a relação é `y = h - m * d`, onde `m` é a constante que dimensiona os pontos de dados.
|
||||
|
||||
# --hints--
|
||||
|
||||
The first `rect` should have a `y` value of `64`.
|
||||
O primeiro `rect` deve ter um valor de `y` igual a `64`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(0).attr('y') == h - dataset[0] * 3);
|
||||
```
|
||||
|
||||
The second `rect` should have a `y` value of `7`.
|
||||
O segundo `rect` deve ter um valor de `y` igual a `7`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(1).attr('y') == h - dataset[1] * 3);
|
||||
```
|
||||
|
||||
The third `rect` should have a `y` value of `34`.
|
||||
O terceiro `rect` deve ter um valor de `y` igual a `34`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(2).attr('y') == h - dataset[2] * 3);
|
||||
```
|
||||
|
||||
The fourth `rect` should have a `y` value of `49`.
|
||||
O quarto `rect` deve ter um valor de `y` igual a `49`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(3).attr('y') == h - dataset[3] * 3);
|
||||
```
|
||||
|
||||
The fifth `rect` should have a `y` value of `25`.
|
||||
O quinto `rect` deve ter um valor de `y` igual a `25`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(4).attr('y') == h - dataset[4] * 3);
|
||||
```
|
||||
|
||||
The sixth `rect` should have a `y` value of `46`.
|
||||
O sexto `rect` deve ter um valor de `y` igual a `46`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(5).attr('y') == h - dataset[5] * 3);
|
||||
```
|
||||
|
||||
The seventh `rect` should have a `y` value of `13`.
|
||||
O sétimo `rect` deve ter um valor de `y` igual a `13`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(6).attr('y') == h - dataset[6] * 3);
|
||||
```
|
||||
|
||||
The eighth `rect` should have a `y` value of `58`.
|
||||
O oitavo `rect` deve ter um valor de `y` igual a `58`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(7).attr('y') == h - dataset[7] * 3);
|
||||
```
|
||||
|
||||
The ninth `rect` should have a `y` value of `73`.
|
||||
O nono `rect` deve ter um valor de `y` igual a `73`.
|
||||
|
||||
```js
|
||||
assert($('rect').eq(8).attr('y') == h - dataset[8] * 3);
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa8367417b2b2512bcb
|
||||
title: Learn About SVG in D3
|
||||
title: Aprender sobre o SVG no D3
|
||||
challengeType: 6
|
||||
forumTopicId: 301489
|
||||
dashedName: learn-about-svg-in-d3
|
||||
@@ -8,35 +8,35 @@ dashedName: learn-about-svg-in-d3
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>SVG</dfn> stands for <dfn>Scalable Vector Graphics</dfn>.
|
||||
<dfn>SVG</dfn> é a abreviação de <dfn>Scalable Vector Graphics</dfn>.
|
||||
|
||||
Here "scalable" means that, if you zoom in or out on an object, it would not appear pixelated. It scales with the display system, whether it's on a small mobile screen or a large TV monitor.
|
||||
Aqui, "scalable" significa que, se você der zoom ou se afastar do objeto, ele não parecerá pixelado. Ele se redimensiona com o sistema de exibição, seja na tela pequena de um dispositivo móvel, seja em um monitor grande de TV.
|
||||
|
||||
SVG is used to make common geometric shapes. Since D3 maps data into a visual representation, it uses SVG to create the shapes for the visualization. SVG shapes for a web page must go within an HTML `svg` tag.
|
||||
O SVG é usado para fazer formas geométricas comuns. Como o D3 faz o mapeamento dos dados em uma representação visual, ele usa o SVG para criar as formas para a visualização. As formas do SVG para um página da web devem ir dentro de uma tag `svg`.
|
||||
|
||||
CSS can be scalable when styles use relative units (such as `vh`, `vw`, or percentages), but using SVG is more flexible to build data visualizations.
|
||||
O CSS pode ser dimensionável quando os estilos usam unidades relativas (como `vh`, `vw` ou porcentagens), mas usar o SVG é mais flexível para criar visualizações de dados.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add an `svg` node to the `body` using `append()`. Give it a `width` attribute set to the provided `w` constant and a `height` attribute set to the provided `h` constant using the `attr()` or `style()` methods for each. You'll see it in the output because there's a `background-color` of pink applied to it in the `style` tag.
|
||||
Adicione um nó do `svg` ao `body` usando `append()`. Dê um atributo `width` definido para a constante `w` fornecida e um atributo `height` definido para a constante `h` fornecida usando os métodos `attr()` ou `style()` para cada um. Você verá o nó no resultado porque há uma `background-color` rosa aplicada a ele na tag `style`.
|
||||
|
||||
**Note:** When using `attr()` width and height attributes do not have units. This is the building block of scaling - the element will always have a 5:1 width to height ratio, no matter what the zoom level is.
|
||||
**Observação:** ao usar `attr()`, os atributos width e height não têm unidades. Este é o bloco de construção do dimensionamento - o elemento terá sempre uma proporção de 5:1 da largura para a altura, não importando o nível de zoom.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your document should have 1 `svg` element.
|
||||
O documento deve ter 1 elemento `svg`.
|
||||
|
||||
```js
|
||||
assert($('svg').length == 1);
|
||||
```
|
||||
|
||||
The `svg` element should have a `width` attribute set to `500` or styled to have a width of `500px`.
|
||||
O elemento `svg` deve ter um atributo `width` definido como `500` ou estilizado para ter uma largura de `500px`.
|
||||
|
||||
```js
|
||||
assert($('svg').attr('width') == '500' || $('svg').css('width') == '500px');
|
||||
```
|
||||
|
||||
The `svg` element should have a `height` attribute set to `100` or styled to have a height of `100px`.
|
||||
O elemento `svg` deve ter um atributo `height` definido como `100` ou estilizado para ter uma largura de `100px`.
|
||||
|
||||
```js
|
||||
assert($('svg').attr('height') == '100' || $('svg').css('height') == '100px');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa6367417b2b2512bc3
|
||||
title: Select a Group of Elements with D3
|
||||
title: Selecionar um grupo de elementos com D3
|
||||
challengeType: 6
|
||||
forumTopicId: 301490
|
||||
dashedName: select-a-group-of-elements-with-d3
|
||||
@@ -8,21 +8,21 @@ dashedName: select-a-group-of-elements-with-d3
|
||||
|
||||
# --description--
|
||||
|
||||
D3 also has the `selectAll()` method to select a group of elements. It returns an array of HTML nodes for all the items in the document that match the input string. Here's an example to select all the anchor tags in a document:
|
||||
O D3 também tem o método `selectAll()` para selecionar um grupo de elementos. Ele retorna um array de nós de HTML para todos os itens no documento que correspondem à string de entrada. Aqui está um exemplo para selecionar todas as tags de âncora em um documento:
|
||||
|
||||
```js
|
||||
const anchors = d3.selectAll("a");
|
||||
```
|
||||
|
||||
Like the `select()` method, `selectAll()` supports method chaining, and you can use it with other methods.
|
||||
Assim como o método `select()`, o `selectAll()` suporta encadeamento de métodos e você pode usá-lo com outros métodos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Select all of the `li` tags in the document, and change their text to the string `list item` by chaining the `.text()` method.
|
||||
Selecione todas as tags `li` do documento e altere o texto delas para a string `list item`, encadeando o método `.text()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
There should be 3 `li` elements on the page, and the text in each one should say `list item`. Capitalization and spacing should match exactly.
|
||||
Deve haver 3 elementos `li` na página, e o texto em cada um deve dizer `list item`. A capitalização e o espaçamento devem coincidir com exatidão.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -32,13 +32,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should access the `d3` object.
|
||||
O código deve acessar o objeto `d3`.
|
||||
|
||||
```js
|
||||
assert(code.match(/d3/g));
|
||||
```
|
||||
|
||||
Your code should use the `selectAll` method.
|
||||
O código deve usar o método `selectAll`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.selectAll/g));
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fac367417b2b2512bdb
|
||||
title: Set a Domain and a Range on a Scale
|
||||
title: Definir um domínio e uma imagem em uma escala
|
||||
challengeType: 6
|
||||
forumTopicId: 301491
|
||||
dashedName: set-a-domain-and-a-range-on-a-scale
|
||||
@@ -8,13 +8,13 @@ dashedName: set-a-domain-and-a-range-on-a-scale
|
||||
|
||||
# --description--
|
||||
|
||||
By default, scales use the identity relationship. This means the input value maps to the output value. However, scales can be much more flexible and interesting.
|
||||
Por padrão, as escalas usam a relação de identidade. Isso significa que o valor de entrada mapeia para o valor de saída. Entretanto, as escalas podem ser muito mais flexíveis e interessantes.
|
||||
|
||||
Say a dataset has values ranging from 50 to 480. This is the input information for a scale, also known as the <dfn>domain</dfn>.
|
||||
Digamos que um conjunto de dados tenha valores em um intervalo de 50 a 480. Esta é a informação de entrada para uma escala, também conhecida como o <dfn>domínio</dfn>.
|
||||
|
||||
You want to map those points along the `x` axis on the SVG canvas, between 10 units and 500 units. This is the output information, also known as the <dfn>range</dfn>.
|
||||
Você deseja mapear esses pontos sobre o eixo `x` no canvas do SVG, entre 10 e 500 unidades. Esta é a informação de saída, também conhecida como o <dfn>imagem</dfn>.
|
||||
|
||||
The `domain()` and `range()` methods set these values for the scale. Both methods take an array of at least two elements as an argument. Here's an example:
|
||||
Os métodos `domain()` e `range()` definem esses valores para a escala. Os dois métodos recebem um array de pelo menos dois elementos como argumento. Exemplo:
|
||||
|
||||
```js
|
||||
scale.domain([50, 480]);
|
||||
@@ -26,43 +26,43 @@ scale(750)
|
||||
d3.scaleLinear()
|
||||
```
|
||||
|
||||
In order, the following values would be displayed in the console: `10`, `500`, `323.37`, and `807.67`.
|
||||
Em ordem, os valores a seguir serão exibidos no console: `10`, `500`, `323.37` e `807.67`.
|
||||
|
||||
Notice that the scale uses the linear relationship between the domain and range values to figure out what the output should be for a given number. The minimum value in the domain (50) maps to the minimum value (10) in the range.
|
||||
Observe que a escala usa a relação linear entre os valores do domínio e da imagem para descobrir qual deve ser a saída para um determinado número. O valor mínimo no domínio (50) é mapeado para o valor mínimo (10) na imagem.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a scale and set its domain to `[250, 500]` and range to `[10, 150]`.
|
||||
Crie uma escala e defina seu domínio como `[250, 500]` e sua imagem (range) como `[10, 150]`.
|
||||
|
||||
**Note:** You can chain the `domain()` and `range()` methods onto the `scale` variable.
|
||||
**Observação:** você pode encadear os métodos `domain()` e `range()` na variável `scale`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `domain()` method.
|
||||
O código deve usar o método `domain()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.domain/g));
|
||||
```
|
||||
|
||||
The `domain()` of the `scale` should be set to `[250, 500]`.
|
||||
O `domain()` de `scale` deve ser definido como `[250, 500]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(scale.domain()) == JSON.stringify([250, 500]));
|
||||
```
|
||||
|
||||
Your code should use the `range()` method.
|
||||
O código deve usar o método `range()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.range/g));
|
||||
```
|
||||
|
||||
The `range()` of the `scale` should be set to `[10, 150]`.
|
||||
O `range()` de `scale` deve ser definido como `[10, 150]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(scale.range()) == JSON.stringify([10, 150]));
|
||||
```
|
||||
|
||||
The text in the `h2` should be `-102`.
|
||||
O texto no `h2` deve ser `-102`.
|
||||
|
||||
```js
|
||||
assert($('h2').text() == '-102');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7faa367417b2b2512bd3
|
||||
title: Style D3 Labels
|
||||
title: Estilizar as etiquetas do D3
|
||||
challengeType: 6
|
||||
forumTopicId: 301492
|
||||
dashedName: style-d3-labels
|
||||
@@ -8,21 +8,21 @@ dashedName: style-d3-labels
|
||||
|
||||
# --description--
|
||||
|
||||
D3 methods can add styles to the bar labels. The `fill` attribute sets the color of the text for a `text` node. The `style()` method sets CSS rules for other styles, such as `font-family` or `font-size`.
|
||||
Os métodos do D3 podem adicionar estilos às etiquetas das barras. O atributo `fill` define a cor do texto para um nó `text`. O método `style()` define as regras do CSS para outros estilos, como `font-family` ou `font-size`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set the `font-size` of the `text` elements to `25px`, and the color of the text to red.
|
||||
Defina o `font-size` dos elementos `text` para `25px` e a cor do texto para "red" (vermelho).
|
||||
|
||||
# --hints--
|
||||
|
||||
The labels should all have a `fill` color of red.
|
||||
As etiquetas devem ter a propriedade `fill` com a cor "red".
|
||||
|
||||
```js
|
||||
assert($('text').css('fill') == 'rgb(255, 0, 0)');
|
||||
```
|
||||
|
||||
The labels should all have a `font-size` of `25` pixels.
|
||||
As etiquetas devem ter um `font-size` de `25` pixels.
|
||||
|
||||
```js
|
||||
assert($('text').css('font-size') == '25px');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa8367417b2b2512bc9
|
||||
title: Update the Height of an Element Dynamically
|
||||
title: Atualizar a altura de um elemento dinamicamente
|
||||
challengeType: 6
|
||||
forumTopicId: 301493
|
||||
dashedName: update-the-height-of-an-element-dynamically
|
||||
@@ -8,13 +8,13 @@ dashedName: update-the-height-of-an-element-dynamically
|
||||
|
||||
# --description--
|
||||
|
||||
The previous challenges covered how to display data from an array and how to add CSS classes. You can combine these lessons to create a simple bar chart. There are two steps to this:
|
||||
Os desafios anteriores tratavam da forma como exibir os dados de um array e como adicionar classes do CSS. Você pode combinar essas lições para criar um gráfico de barras simples. Há duas etapas para isso:
|
||||
|
||||
1) Create a `div` for each data point in the array
|
||||
1) Crie uma `div` para cada ponto de dados no array
|
||||
|
||||
2) Give each `div` a dynamic height, using a callback function in the `style()` method that sets height equal to the data value
|
||||
2) Dê a cada `div` uma altura dinâmica usando uma função de callback no método `style()`, que define a altura igual ao valor de dado
|
||||
|
||||
Recall the format to set a style using a callback function:
|
||||
Lembre-se do formato para definir um estilo usando uma função de callback:
|
||||
|
||||
```js
|
||||
selection.style("cssProperty", (d) => d)
|
||||
@@ -22,59 +22,59 @@ selection.style("cssProperty", (d) => d)
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the `style()` method to the code in the editor to set the `height` property for each element. Use a callback function to return the value of the data point with the string `px` added to it.
|
||||
Adicione o método `style()` ao código no editor para definir a propriedade `height` para cada elemento. Use uma função de callback para retornar o valor do ponto de dados com a string `px` adicionada a ele.
|
||||
|
||||
# --hints--
|
||||
|
||||
The first `div` should have a `height` of `12` pixels.
|
||||
A primeira `div` deve ter uma `height` de `12` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(0)[0].style.height === '12px');
|
||||
```
|
||||
|
||||
The second `div` should have a `height` of `31` pixels.
|
||||
A segunda `div` deve ter uma `height` de `31` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(1)[0].style.height === '31px');
|
||||
```
|
||||
|
||||
The third `div` should have a `height` of `22` pixels.
|
||||
A terceira `div` deve ter uma `height` de `22` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(2)[0].style.height === '22px');
|
||||
```
|
||||
|
||||
The fourth `div` should have a `height` of `17` pixels.
|
||||
A quarta `div` deve ter uma `height` de `17` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(3)[0].style.height === '17px');
|
||||
```
|
||||
|
||||
The fifth `div` should have a `height` of `25` pixels.
|
||||
A quinta `div` deve ter uma `height` de `25` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(4)[0].style.height === '25px');
|
||||
```
|
||||
|
||||
The sixth `div` should have a `height` of `18` pixels.
|
||||
A sexta `div` deve ter uma `height` de `18` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(5)[0].style.height === '18px');
|
||||
```
|
||||
|
||||
The seventh `div` should have a `height` of `29` pixels.
|
||||
A sétima `div` deve ter uma `height` de `29` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(6)[0].style.height === '29px');
|
||||
```
|
||||
|
||||
The eighth `div` should have a `height` of `14` pixels.
|
||||
A oitava `div` deve ter uma `height` de `14` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(7)[0].style.height === '14px');
|
||||
```
|
||||
|
||||
The ninth `div` should have a `height` of `9` pixels.
|
||||
A nona `div` deve ter uma `height` de `9` pixels.
|
||||
|
||||
```js
|
||||
assert($('div').eq(8)[0].style.height === '9px');
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fac367417b2b2512bde
|
||||
title: Use a Pre-Defined Scale to Place Elements
|
||||
title: Usar uma escala predefinida para definir o local dos elementos
|
||||
challengeType: 6
|
||||
forumTopicId: 301494
|
||||
dashedName: use-a-pre-defined-scale-to-place-elements
|
||||
@@ -8,32 +8,32 @@ dashedName: use-a-pre-defined-scale-to-place-elements
|
||||
|
||||
# --description--
|
||||
|
||||
With the scales set up, it's time to map the scatter plot again. The scales are like processing functions that turn the `x` and `y` raw data into values that fit and render correctly on the SVG canvas. They keep the data within the screen's plotting area.
|
||||
Com as escalas configuradas, é hora de mapear novamente o diagrama de dispersão. As escalas são como funções de processamento que transformam os valores `x` e `y` dos dados brutos em valores que se ajustem e que sejam renderizados corretamente no canvas do SVG. Eles mantêm os dados dentro da área de plotagem da tela.
|
||||
|
||||
You set the coordinate attribute values for an SVG shape with the scaling function. This includes `x` and `y` attributes for `rect` or `text` elements, or `cx` and `cy` for `circles`. Here's an example:
|
||||
Você define os valores dos atributos das coordenadas para uma forma do SVG com a função de dimensionamento. Isso inclui os atributos `x` e `y` para `rect`, elementos `text`, ou `cx` e `cy` para `circles`. Exemplo:
|
||||
|
||||
```js
|
||||
shape
|
||||
.attr("x", (d) => xScale(d[0]))
|
||||
```
|
||||
|
||||
Scales set shape coordinate attributes to place the data points onto the SVG canvas. You don't need to apply scales when you display the actual data value, for example, in the `text()` method for a tooltip or label.
|
||||
As escalas definem atributos de coordenadas de forma a colocar os pontos de dados no canvas do SVG. Você não precisa aplicar as escalas quando exibir o valor real dos dados, por exemplo, no método `text()` para uma dica ou etiqueta.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use `xScale` and `yScale` to position both the `circle` and `text` shapes onto the SVG canvas. For the `circles`, apply the scales to set the `cx` and `cy` attributes. Give them a radius of `5` units, too.
|
||||
Use `xScale` e `yScale` para posicionar ambas as formas, `circle` e `text`, no canvas do SVG. Para os `circles`, aplique as escalas para definir os atributos `cx` e `cy`. Dê a elas um raio de `5` unidades, também.
|
||||
|
||||
For the `text` elements, apply the scales to set the `x` and `y` attributes. The labels should be offset to the right of the dots. To do this, add `10` units to the `x` data value before passing it to the `xScale`.
|
||||
Para os elementos `text`, aplique as escalas para definir os atributos `x` e `y`. As etiquetas devem ser deslocadas para a direita dos pontos. Para fazer isso, adicione `10` unidades ao valor de `x` dos dados antes de passá-lo para `xScale`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should have 10 `circle` elements.
|
||||
O código deve ter 10 elementos `circle`.
|
||||
|
||||
```js
|
||||
assert($('circle').length == 10);
|
||||
```
|
||||
|
||||
The first `circle` element should have a `cx` value of approximately `91` and a `cy` value of approximately `368` after applying the scales. It should also have an `r` value of `5`.
|
||||
O primeiro elemento `circle` deve ter um valor de `cx` de aproximadamente `91` e um valor de `cy` de aproximadamente `368` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -43,7 +43,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The second `circle` element should have a `cx` value of approximately `159` and a `cy` value of approximately `181` after applying the scales. It should also have an `r` value of `5`.
|
||||
O segundo elemento `circle` deve ter um valor de `cx` de aproximadamente `159` e um valor de `cy` de aproximadamente `181` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -53,7 +53,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The third `circle` element should have a `cx` value of approximately `340` and a `cy` value of approximately `329` after applying the scales. It should also have an `r` value of `5`.
|
||||
O terceiro elemento `circle` deve ter um valor de `cx` de aproximadamente `340` e um valor de `cy` de aproximadamente `329` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -63,7 +63,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fourth `circle` element should have a `cx` value of approximately `131` and a `cy` value of approximately `60` after applying the scales. It should also have an `r` value of `5`.
|
||||
O quarto elemento `circle` deve ter um valor de `cx` de aproximadamente `131` e um valor de `cy` de aproximadamente `60` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -73,7 +73,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fifth `circle` element should have a `cx` value of approximately `440` and a `cy` value of approximately `237` after applying the scales. It should also have an `r` value of `5`.
|
||||
O quinto elemento `circle` deve ter um valor de `cx` de aproximadamente `440` e um valor de `cy` de aproximadamente `237` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -83,7 +83,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The sixth `circle` element should have a `cx` value of approximately `271` and a `cy` value of approximately `306` after applying the scales. It should also have an `r` value of `5`.
|
||||
O sexto elemento `circle` deve ter um valor de `cx` de aproximadamente `271` e um valor de `cy` de aproximadamente `306` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -93,7 +93,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The seventh `circle` element should have a `cx` value of approximately `361` and a `cy` value of approximately `351` after applying the scales. It should also have an `r` value of `5`.
|
||||
O sétimo elemento `circle` deve ter um valor de `cx` de aproximadamente `361` e um valor de `cy` de aproximadamente `351` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -103,7 +103,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The eighth `circle` element should have a `cx` value of approximately `261` and a `cy` value of approximately `132` after applying the scales. It should also have an `r` value of `5`.
|
||||
O oitavo elemento `circle` deve ter um valor de `cx` de aproximadamente `261` e um valor de `cy` de aproximadamente `132` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -113,7 +113,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The ninth `circle` element should have a `cx` value of approximately `131` and a `cy` value of approximately `144` after applying the scales. It should also have an `r` value of `5`.
|
||||
O nono elemento `circle` deve ter um valor de `cx` de aproximadamente `131` e um valor de `cy` de aproximadamente `144` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -123,7 +123,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The tenth `circle` element should have a `cx` value of approximately `79` and a `cy` value of approximately `326` after applying the scales. It should also have an `r` value of `5`.
|
||||
O décimo elemento `circle` deve ter um valor de `cx` de aproximadamente `79` e um valor de `cy` de aproximadamente `326` após a aplicação das escalas. Ele também deve ter um valor `r` de `5`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -133,13 +133,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should have 10 `text` elements.
|
||||
O código deve ter 10 elementos `text`.
|
||||
|
||||
```js
|
||||
assert($('text').length == 10);
|
||||
```
|
||||
|
||||
The first label should have an `x` value of approximately `100` and a `y` value of approximately `368` after applying the scales.
|
||||
A primeira etiqueta deve ter um valor de `x` de aproximadamente `100` e um valor de `y` de aproximadamente `368` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -148,7 +148,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The second label should have an `x` value of approximately `168` and a `y` value of approximately `181` after applying the scales.
|
||||
A segunda etiqueta deve ter um valor de `x` de aproximadamente `168` e um valor de `y` de aproximadamente `181` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -157,7 +157,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The third label should have an `x` value of approximately `350` and a `y` value of approximately `329` after applying the scales.
|
||||
A terceira etiqueta deve ter um valor de `x` de aproximadamente `350` e um valor de `y` de aproximadamente `329` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -166,7 +166,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fourth label should have an `x` value of approximately `141` and a `y` value of approximately `60` after applying the scales.
|
||||
A quarta etiqueta deve ter um valor de `x` de aproximadamente `141` e um valor de `y` de aproximadamente `60` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -175,7 +175,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The fifth label should have an `x` value of approximately `449` and a `y` value of approximately `237` after applying the scales.
|
||||
A quinta etiqueta deve ter um valor de `x` de aproximadamente `449` e um valor de `y` de aproximadamente `237` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -184,7 +184,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The sixth label should have an `x` value of approximately `280` and a `y` value of approximately `306` after applying the scales.
|
||||
A sexta etiqueta deve ter um valor de `x` de aproximadamente `280` e um valor de `y` de aproximadamente `306` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -193,7 +193,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The seventh label should have an `x` value of approximately `370` and a `y` value of approximately `351` after applying the scales.
|
||||
A sétima etiqueta deve ter um valor de `x` de aproximadamente `370` e um valor de `y` de aproximadamente `351` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -202,7 +202,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The eighth label should have an `x` value of approximately `270` and a `y` value of approximately `132` after applying the scales.
|
||||
A oitava etiqueta deve ter um valor de `x` de aproximadamente `270` e um valor de `y` de aproximadamente `132` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -211,7 +211,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The ninth label should have an `x` value of approximately `140` and a `y` value of approximately `144` after applying the scales.
|
||||
A nona etiqueta deve ter um valor de `x` de aproximadamente `140` e um valor de `y` de aproximadamente `144` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -220,7 +220,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The tenth label should have an `x` value of approximately `88` and a `y` value of approximately `326` after applying the scales.
|
||||
A décima etiqueta deve ter um valor de `x` de aproximadamente `88` e um valor de `y` de aproximadamente `326` após aplicar as escalas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fac367417b2b2512bdd
|
||||
title: Use Dynamic Scales
|
||||
title: Usar escalas dinâmicas
|
||||
challengeType: 6
|
||||
forumTopicId: 301495
|
||||
dashedName: use-dynamic-scales
|
||||
@@ -8,13 +8,13 @@ dashedName: use-dynamic-scales
|
||||
|
||||
# --description--
|
||||
|
||||
The D3 `min()` and `max()` methods are useful to help set the scale.
|
||||
Os métodos `min()` e `max()` do D3 são úteis para definir a escala.
|
||||
|
||||
Given a complex data set, one priority is to set the scale so the visualization fits the SVG container's width and height. You want all the data plotted inside the SVG canvas so it's visible on the web page.
|
||||
Dado um conjunto de dados complexos, uma prioridade é definir a escala para que a visualização se encaixe na largura e na altura do contêiner do SVG. Você quer todos os dados plotados dentro do canvas do SVG para que sejam visíveis na página da web.
|
||||
|
||||
The example below sets the x-axis scale for scatter plot data. The `domain()` method passes information to the scale about the raw data values for the plot. The `range()` method gives it information about the actual space on the web page for the visualization.
|
||||
O exemplo abaixo define a escala do eixo x para dados do diagrama de dispersão. O método `domain()` passa informações para a escala sobre os valores dos dados brutos para a plotagem. O método `range()` dá a ela informações sobre o espaço real na página da web para a visualização.
|
||||
|
||||
In the example, the domain goes from 0 to the maximum in the set. It uses the `max()` method with a callback function based on the x values in the arrays. The range uses the SVG canvas' width (`w`), but it includes some padding, too. This puts space between the scatter plot dots and the edge of the SVG canvas.
|
||||
No exemplo, o domínio vai de 0 ao valor máximo do conjunto. Ele usa o método `max()` com uma função de callback baseada nos valores de x nos arrays. A imagem (range) usa a largura do canvas do SVG (`w`), mas também inclui algum preenchimento. Isso coloca o espaço entre os pontos do diagrama de dispersão e a borda do canvas do SVG.
|
||||
|
||||
```js
|
||||
const dataset = [
|
||||
@@ -38,29 +38,29 @@ const xScale = d3.scaleLinear()
|
||||
.range([padding, w - padding]);
|
||||
```
|
||||
|
||||
The padding may be confusing at first. Picture the x-axis as a horizontal line from 0 to 500 (the width value for the SVG canvas). Including the padding in the `range()` method forces the plot to start at 30 along that line (instead of 0), and end at 470 (instead of 500).
|
||||
O preenchimento pode ser confuso no começo. Imagine o eixo x como uma linha horizontal de 0 a 500 (o valor de largura para o canvas do SVG). Incluir o preenchimento no método `range()` força o gráfico a começar de 30 ao longo dessa linha (em vez de 0) e terminar em 470 (em vez de 500).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `yScale` variable to create a linear y-axis scale. The domain should start at zero and go to the maximum `y` value in the set. The range should use the SVG height (`h`) and include padding.
|
||||
Use a variável `yScale` para criar uma escala linear no eixo y. O domínio deve começar em zero e ir até o valor de `y` máximo no conjunto. A imagem (range) deve usar a altura do SVG (`h`) e incluir o preenchimento.
|
||||
|
||||
**Note:** Remember to keep the plot right-side-up. When you set the range for the y coordinates, the higher value (height minus padding) is the first argument, and the lower value is the second argument.
|
||||
**Observação:** lembre-se de manter o gráfico na posição correta. Quando você define a imagem como as coordenadas y, o valor maior (altura menos o preenchimento) é o primeiro argumento, enquanto o valor menor é o segundo argumento.
|
||||
|
||||
# --hints--
|
||||
|
||||
The text in the `h2` should be `30`.
|
||||
O texto no `h2` deve ser `30`.
|
||||
|
||||
```js
|
||||
assert(output == 30 && $('h2').text() == '30');
|
||||
```
|
||||
|
||||
The `domain()` of yScale should be equivalent to `[0, 411]`.
|
||||
O `domain()` de yScale deve ser equivalente a `[0, 411]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(yScale.domain()) == JSON.stringify([0, 411]));
|
||||
```
|
||||
|
||||
The `range()` of yScale should be equivalent to `[470, 30]`.
|
||||
O `range()` de yScale deve ser equivalente a `[470, 30]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(yScale.range()) == JSON.stringify([470, 30]));
|
||||
|
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: 587d7fac367417b2b2512bdc
|
||||
title: >-
|
||||
Use the d3.max and d3.min Functions to Find Minimum and Maximum Values in a Dataset
|
||||
Usar as funções d3.max e d3.min para encontrar valores mínimos e máximos em um conjunto de dados
|
||||
challengeType: 6
|
||||
forumTopicId: 301496
|
||||
dashedName: >-
|
||||
@@ -10,11 +10,11 @@ dashedName: >-
|
||||
|
||||
# --description--
|
||||
|
||||
The D3 methods `domain()` and `range()` set that information for your scale based on the data. There are a couple methods to make that easier.
|
||||
Os métodos `domain()` e `range()` do D3 definem essas informações para sua escala com base nos dados. Existem alguns métodos que tornam isso mais fácil.
|
||||
|
||||
Often when you set the domain, you'll want to use the minimum and maximum values within the data set. Trying to find these values manually, especially in a large data set, may cause errors.
|
||||
Muitas vezes, quando você define o domínio, vai querer usar os valores mínimo e máximo dentro do conjunto de dados. Tentar encontrar esses valores manualmente, especialmente em um conjunto grande de dados, pode causar erros.
|
||||
|
||||
D3 has two methods - `min()` and `max()` to return this information. Here's an example:
|
||||
O D3 tem dois métodos - `min()` e `max()` - para retornar essa informação. Exemplo:
|
||||
|
||||
```js
|
||||
const exampleData = [34, 234, 73, 90, 6, 52];
|
||||
@@ -22,28 +22,28 @@ d3.min(exampleData)
|
||||
d3.max(exampleData)
|
||||
```
|
||||
|
||||
A dataset may have nested arrays, like the `[x, y]` coordinate pairs that were in the scatter plot example. In that case, you need to tell D3 how to calculate the maximum and minimum. Fortunately, both the `min()` and `max()` methods take a callback function. In this example, the callback function's argument `d` is for the current inner array. The callback needs to return the element from the inner array (the `x` or `y` value) over which you want to compute the maximum or minimum. Here's an example for how to find the min and max values with an array of arrays:
|
||||
Um conjunto de dados pode ter arrays aninhados, como os pares de coordenadas `[x, y]` que estavam no diagrama de dispersão do exemplo. Nesse caso, você precisa dizer ao D3 como calcular o máximo e o mínimo. Felizmente, ambos os métodos `min()` e `max()` têm uma função de callback. Neste exemplo, o argumento da função de callback `d` é para o array interno atual. A função de callback precisa retornar o elemento do array interno (o valor `x` ou `y`) sobre o qual você deseja calcular o máximo ou o mínimo. Aqui vemos um exemplo de como encontrar os valores mínimo e máximo em um array de arrays:
|
||||
|
||||
```js
|
||||
const locationData = [[1, 7],[6, 3],[8, 3]];
|
||||
const minX = d3.min(locationData, (d) => d[0]);
|
||||
```
|
||||
|
||||
`minX` would have the value `1`.
|
||||
`minX` teria o valor `1`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The `positionData` array holds sub arrays of x, y, and z coordinates. Use a D3 method to find the maximum value of the z coordinate (the third value) from the arrays and save it in the `output` variable.
|
||||
O array `positionData` contém subarrays das coordenadas x, y e z. Use um método do D3 para encontrar o valor máximo da coordenada z (o terceiro valor) entre os arrays e salvá-lo na variável `output`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The text in the `h2` should be `8`.
|
||||
O texto no `h2` deve ser `8`.
|
||||
|
||||
```js
|
||||
assert(output == 8 && $('h2').text() == '8');
|
||||
```
|
||||
|
||||
Your code should use the `max()` method.
|
||||
O código deve usar o método `max()`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa7367417b2b2512bc4
|
||||
title: Work with Data in D3
|
||||
title: Trabalhar com dados no D3
|
||||
challengeType: 6
|
||||
forumTopicId: 301497
|
||||
dashedName: work-with-data-in-d3
|
||||
@@ -8,15 +8,15 @@ dashedName: work-with-data-in-d3
|
||||
|
||||
# --description--
|
||||
|
||||
The D3 library focuses on a data-driven approach. When you have a set of data, you can apply D3 methods to display it on the page. Data comes in many formats, but this challenge uses a simple array of numbers.
|
||||
A biblioteca D3 concentra-se numa abordagem baseada em dados. Quando você tem um conjunto de dados, você pode aplicar os métodos do D3 para exibi-los na página. Os dados vêm em vários formatos, mas este desafio usa um arrays simples de números.
|
||||
|
||||
The first step is to make D3 aware of the data. The `data()` method is used on a selection of DOM elements to attach the data to those elements. The data set is passed as an argument to the method.
|
||||
O primeiro passo é sensibilizar o D3 para os dados. O método `data()` é usado em uma seleção de elementos do DOM para anexar os dados a esses elementos. O conjunto de dados é passado como um argumento ao método.
|
||||
|
||||
A common workflow pattern is to create a new element in the document for each piece of data in the set. D3 has the `enter()` method for this purpose.
|
||||
Um padrão comum de fluxo de trabalho é criar um novo elemento no documento para cada parte dos dados no conjunto. O D3 tem o método `enter()` para esse propósito.
|
||||
|
||||
When `enter()` is combined with the `data()` method, it looks at the selected elements from the page and compares them to the number of data items in the set. If there are fewer elements than data items, it creates the missing elements.
|
||||
Quando `enter()` é combinado com o método `data()`, ele olha para os elementos selecionados da página e os compara com o número de itens de dados no conjunto. Se houver menos elementos do que itens de dados, ele criará os elementos que faltam.
|
||||
|
||||
Here is an example that selects a `ul` element and creates a new list item based on the number of entries in the array:
|
||||
Aqui está um exemplo que seleciona um elemento `ul` e cria um novo item de lista baseado no número de entradas no array:
|
||||
|
||||
```html
|
||||
<body>
|
||||
@@ -32,21 +32,21 @@ Here is an example that selects a `ul` element and creates a new list item based
|
||||
</body>
|
||||
```
|
||||
|
||||
It may seem confusing to select elements that don't exist yet. This code is telling D3 to first select the `ul` on the page. Next, select all list items, which returns an empty selection. Then the `data()` method reviews the dataset and runs the following code three times, once for each item in the array. The `enter()` method sees there are no `li` elements on the page, but it needs 3 (one for each piece of data in `dataset`). New `li` elements are appended to the `ul` and have the text `New item`.
|
||||
Pode parecer confuso selecionar elementos que ainda não existem. Este código está dizendo para o D3 selecionar primeiro o `ul` na página. Em seguida, selecionar todos os itens da lista, o que retorna uma seleção vazia. Então, o método `data()` revisa o conjunto de dados e executa o código a seguir três vezes, uma vez para cada item do array. O método `enter()` vê que não há elementos `li` na página, mas precisa de 3 (um para cada dado no `dataset`). Novos elementos `li` são anexados ao `ul` e têm o texto `New item`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Select the `body` node, then select all `h2` elements. Have D3 create and append an `h2` tag for each item in the `dataset` array. The text in the `h2` should say `New Title`. Your code should use the `data()` and `enter()` methods.
|
||||
Selecione o nó de `body` e todos os elementos `h2`. Faça com que o D3 crie e anexe uma tag `h2` para cada item no array do `dataset`. O texto no `h2` deve dizer `New Title`. O código deve usar os métodos `data()` e `enter()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your document should have 9 `h2` elements.
|
||||
O documento deve ter 9 elementos `h2`.
|
||||
|
||||
```js
|
||||
assert($('h2').length == 9);
|
||||
```
|
||||
|
||||
The text in the `h2` elements should say `New Title`. The capitalization and spacing should match exactly.
|
||||
O texto no `h2` deve dizer `New Title`. A capitalização e o espaçamento devem coincidir com exatidão.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -56,13 +56,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should use the `data()` method.
|
||||
O código deve usar o método `data()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.data/g));
|
||||
```
|
||||
|
||||
Your code should use the `enter()` method.
|
||||
O código deve usar o método `enter()`.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.enter/g));
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7fa7367417b2b2512bc5
|
||||
title: Work with Dynamic Data in D3
|
||||
title: Trabalhar com dados dinâmicos no D3
|
||||
challengeType: 6
|
||||
forumTopicId: 301498
|
||||
dashedName: work-with-dynamic-data-in-d3
|
||||
@@ -8,75 +8,75 @@ dashedName: work-with-dynamic-data-in-d3
|
||||
|
||||
# --description--
|
||||
|
||||
The last two challenges cover the basics of displaying data dynamically with D3 using the `data()` and `enter()` methods. These methods take a data set and, together with the `append()` method, create a new DOM element for each entry in the data set.
|
||||
Os dois últimos desafios cobrem o básico da exibição de dados dinamicamente com o D3 usando os métodos `data()` e `enter()`. Esses métodos requerem um conjunto de dados e, junto com o método `append()`, criam um novo elemento do DOM para cada entrada no conjunto de dados.
|
||||
|
||||
In the previous challenge, you created a new `h2` element for each item in the `dataset` array, but they all contained the same text, `New Title`. This is because you have not made use of the data that is bound to each of the `h2` elements.
|
||||
No desafio anterior, você criou um novo elemento `h2` para cada item no array do `dataset`, mas todos continham o mesmo texto, `New Title`. Isso ocorreu porque você ainda não utilizou os dados que estão associados a cada um dos elementos `h2`.
|
||||
|
||||
The D3 `text()` method can take a string or a callback function as an argument:
|
||||
O método `text()` do D3 pode receber uma string ou uma função de callback como um argumento:
|
||||
|
||||
```js
|
||||
selection.text((d) => d)
|
||||
```
|
||||
|
||||
In the example above, the parameter `d` refers to a single entry in the dataset that a selection is bound to.
|
||||
No exemplo acima, o parâmetro `d` se refere a uma única entrada no conjunto de dados a qual uma seleção está vinculada.
|
||||
|
||||
Using the current example as context, the first `h2` element is bound to 12, the second `h2` element is bound to 31, the third `h2` element is bound to 22, and so on.
|
||||
Usando o exemplo atual como contexto, o primeiro elemento `h2` está ligado a 12, o segundo elemento `h2` está ligado a 31, o terceiro elemento `h2` está ligado a 22 e assim por diante.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `text()` method so that each `h2` element displays the corresponding value from the `dataset` array with a single space and the string `USD`. For example, the first heading should be `12 USD`.
|
||||
Altere o método `text()` para que cada elemento `h2` exiba o valor correspondente do array do `dataset` com um único espaço e a string `USD`. Por exemplo, o primeiro título deve ser `12 USD`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The first `h2` should have the text `12 USD`.
|
||||
O primeiro `h2` deve ter o texto `12 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(0).text() == '12 USD');
|
||||
```
|
||||
|
||||
The second `h2` should have the text `31 USD`.
|
||||
O segundo `h2` deve ter o texto `31 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(1).text() == '31 USD');
|
||||
```
|
||||
|
||||
The third `h2` should have the text `22 USD`.
|
||||
O terceiro `h2` deve ter o texto `22 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(2).text() == '22 USD');
|
||||
```
|
||||
|
||||
The fourth `h2` should have the text `17 USD`.
|
||||
O quarto `h2` deve ter o texto `17 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(3).text() == '17 USD');
|
||||
```
|
||||
|
||||
The fifth `h2` should have the text `25 USD`.
|
||||
O quinto `h2` deve ter o texto `25 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(4).text() == '25 USD');
|
||||
```
|
||||
|
||||
The sixth `h2` should have the text `18 USD`.
|
||||
O sexto `h2` deve ter o texto `18 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(5).text() == '18 USD');
|
||||
```
|
||||
|
||||
The seventh `h2` should have the text `29 USD`.
|
||||
O sétimo `h2` deve ter o texto `29 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(6).text() == '29 USD');
|
||||
```
|
||||
|
||||
The eighth `h2` should have the text `14 USD`.
|
||||
O oitavo `h2` deve ter o texto `14 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(7).text() == '14 USD');
|
||||
```
|
||||
|
||||
The ninth `h2` should have the text `9 USD`.
|
||||
O nono `h2` deve ter o texto `9 USD`.
|
||||
|
||||
```js
|
||||
assert($('h2').eq(8).text() == '9 USD');
|
||||
|
Reference in New Issue
Block a user