chore(i18n,curriculum): processed translations (#43713)

This commit is contained in:
camperbot
2021-10-04 07:27:38 -07:00
committed by GitHub
parent 838d352979
commit aae7b7bca0
27 changed files with 145 additions and 113 deletions

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c164
title: 解析 HTML 和保存數據 title: 解析 HTML 和保存數據
challengeType: 11 challengeType: 11
videoId: bJaqnTWQmb0 videoId: bJaqnTWQmb0
bilibiliIds:
aid: 335522976
bvid: BV1RA411F7vi
cid: 409023170
dashedName: parsing-html-and-saving-data dashedName: parsing-html-and-saving-data
--- ---
@ -12,7 +16,7 @@ dashedName: parsing-html-and-saving-data
更多資源: 更多資源:
- [在 GitHub 平臺的 Notebooks](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-17-reading-html-tables/files) - [在 GitHub 平臺的 Notebooks](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [如何使用 Google Colab 來打開 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) - [如何使用 Google Colab 來打開 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question-- # --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c162
title: 從 CSV 和 TXT 中讀取數據 title: 從 CSV 和 TXT 中讀取數據
challengeType: 11 challengeType: 11
videoId: ViGEv0zOzUk videoId: ViGEv0zOzUk
bilibiliIds:
aid: 505575354
bvid: BV1tg411c7GH
cid: 409020451
dashedName: reading-data-csv-and-txt dashedName: reading-data-csv-and-txt
--- ---
@ -12,7 +16,7 @@ dashedName: reading-data-csv-and-txt
以下有更多的資料: 以下有更多的資料:
- [在 GitHub 平臺的 Notebooks](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-1-reading-csv-and-txt-files/files) - [在 GitHub 平臺的 Notebooks](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [如何使用 Google Colab 來打開 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) - [如何使用 Google Colab 來打開 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question-- # --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c163
title: 從數據庫中讀取數據 title: 從數據庫中讀取數據
challengeType: 11 challengeType: 11
videoId: MtgXS1MofRw videoId: MtgXS1MofRw
bilibiliIds:
aid: 890546354
bvid: BV1JP4y1h7gk
cid: 409020851
dashedName: reading-data-from-databases dashedName: reading-data-from-databases
--- ---
@ -12,7 +16,7 @@ dashedName: reading-data-from-databases
以下有更多的資料 以下有更多的資料
- [在 GitHub 平臺的 Notebooks](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-11-reading-data-from-relational-databases/files) - [在 GitHub 平臺的 Notebooks](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [如何使用 Google Colab 來打開 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) - [如何使用 Google Colab 來打開 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question-- # --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c161
title: 讀取數據簡介 title: 讀取數據簡介
challengeType: 11 challengeType: 11
videoId: cDnt02BcHng videoId: cDnt02BcHng
bilibiliIds:
aid: 548023524
bvid: BV1Nq4y1K7iV
cid: 409020187
dashedName: reading-data-introduction dashedName: reading-data-introduction
--- ---
@ -12,7 +16,7 @@ dashedName: reading-data-introduction
以下有更多的資料: 以下有更多的資料:
- [在 GitHub 平臺的 Notebooks](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-1-reading-csv-and-txt-files/files) - [在 GitHub 平臺的 Notebooks](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [如何使用 Google Colab 來打開 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) - [如何使用 Google Colab 來打開 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question-- # --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c164
title: 解析 HTML 和保存数据 title: 解析 HTML 和保存数据
challengeType: 11 challengeType: 11
videoId: bJaqnTWQmb0 videoId: bJaqnTWQmb0
bilibiliIds:
aid: 335522976
bvid: BV1RA411F7vi
cid: 409023170
dashedName: parsing-html-and-saving-data dashedName: parsing-html-and-saving-data
--- ---
@ -12,7 +16,7 @@ dashedName: parsing-html-and-saving-data
更多资源: 更多资源:
- [在 GitHub 平台的 Notebooks](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-17-reading-html-tables/files) - [在 GitHub 平台的 Notebooks](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [如何使用 Google Colab 来打开 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) - [如何使用 Google Colab 来打开 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question-- # --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c162
title: 从 CSV 和 TXT 中读取数据 title: 从 CSV 和 TXT 中读取数据
challengeType: 11 challengeType: 11
videoId: ViGEv0zOzUk videoId: ViGEv0zOzUk
bilibiliIds:
aid: 505575354
bvid: BV1tg411c7GH
cid: 409020451
dashedName: reading-data-csv-and-txt dashedName: reading-data-csv-and-txt
--- ---
@ -12,7 +16,7 @@ dashedName: reading-data-csv-and-txt
以下有更多的资料: 以下有更多的资料:
- [在 GitHub 平台的 Notebooks](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-1-reading-csv-and-txt-files/files) - [在 GitHub 平台的 Notebooks](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [如何使用 Google Colab 来打开 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) - [如何使用 Google Colab 来打开 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question-- # --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c163
title: 从数据库中读取数据 title: 从数据库中读取数据
challengeType: 11 challengeType: 11
videoId: MtgXS1MofRw videoId: MtgXS1MofRw
bilibiliIds:
aid: 890546354
bvid: BV1JP4y1h7gk
cid: 409020851
dashedName: reading-data-from-databases dashedName: reading-data-from-databases
--- ---
@ -12,7 +16,7 @@ dashedName: reading-data-from-databases
以下有更多的资料 以下有更多的资料
- [在 GitHub 平台的 Notebooks](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-11-reading-data-from-relational-databases/files) - [在 GitHub 平台的 Notebooks](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [如何使用 Google Colab 来打开 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) - [如何使用 Google Colab 来打开 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question-- # --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c161
title: 读取数据简介 title: 读取数据简介
challengeType: 11 challengeType: 11
videoId: cDnt02BcHng videoId: cDnt02BcHng
bilibiliIds:
aid: 548023524
bvid: BV1Nq4y1K7iV
cid: 409020187
dashedName: reading-data-introduction dashedName: reading-data-introduction
--- ---
@ -12,7 +16,7 @@ dashedName: reading-data-introduction
以下有更多的资料: 以下有更多的资料:
- [在 GitHub 平台的 Notebooks](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-1-reading-csv-and-txt-files/files) - [在 GitHub 平台的 Notebooks](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [如何使用 Google Colab 来打开 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb) - [如何使用 Google Colab 来打开 GitHub 上的 Notebooks](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question-- # --question--

View File

@ -8,7 +8,7 @@ dashedName: sort-an-array-alphabetically-using-the-sort-method
# --description-- # --description--
El método `sort` ordena los elementos de un arreglo de acuerdo a la función "callback". El método `sort` ordena los elementos de un arreglo de acuerdo a la función callback.
Por ejemplo: Por ejemplo:
@ -34,7 +34,7 @@ reverseAlpha(['l', 'h', 'z', 'b', 's']);
Esto devolvería el valor de `['z', 's', 'l', 'h', 'b']`. Esto devolvería el valor de `['z', 's', 'l', 'h', 'b']`.
Por defecto, JavaScript ordena basándose en el valor "Unicode" de la cadena de caracteres, lo cual puede dar resultados inesperados. Por lo tanto, se recomienda proporcionar una función "callback" para especificar cómo se deben ordenar los elementos del arreglo. Cuando se proporciona dicha función "callback", normalmente llamada `compareFunction`, los elementos del arreglo se ordenan de acuerdo al valor que devuelve la función `compareFunction`: Si `compareFunction(a,b)` devuelve un valor menor a 0 para dos elementos `a` y `b`, entonces `a` irá antes que `b`. Si `compareFunction(a,b)` devuelve un valor mayor a 0 para dos elementos `a` y `b`, entonces `b` irá antes que `a`. Si `compareFunction(a,b)` devuelve un valor igual a 0 para dos elementos `a` y `b`, entonces `a` y `b` se dejarán sin cambios. Por defecto, JavaScript ordena basándose en el valor "Unicode" de la cadena de caracteres, lo cual puede dar resultados inesperados. Por lo tanto, se recomienda proporcionar una función callback para especificar como se deben ordenar los elementos del arreglo. Cuando se proporciona dicha función callback, normalmente llamada `compareFunction`, los elementos del arreglo se ordenan de acuerdo al valor que devuelve la función `compareFunction`: Si `compareFunction(a,b)` devuelve un valor menor que 0 para dos elementos `a` y `b`, entonces `a` irá antes que `b`. Si `compareFunction(a,b)` devuelve un valor mayor a 0 para dos elementos `a` y `b`, entonces `b` irá antes que `a`. Si `compareFunction(a,b)` devuelve un valor igual a 0 para dos elementos `a` y `b`, entonces `a` y `b` se dejarán sin cambios.
# --instructions-- # --instructions--

View File

@ -14,7 +14,7 @@ Otra función útil de los arreglos es `Array.prototype.filter()` o simplemente
La función callback acepta tres argumentos. El primer argumento es el elemento actual que se está procesando. El segundo es el índice de ese elemento y el tercero es el arreglo sobre el que se llamó al método `filter`. La función callback acepta tres argumentos. El primer argumento es el elemento actual que se está procesando. El segundo es el índice de ese elemento y el tercero es el arreglo sobre el que se llamó al método `filter`.
A continuación se muestra un ejemplo en el que se utiliza el método `filter` en el arreglo `users` para devolver un nuevo arreglo que contiene sólo a los usuarios menores de 30 años. Para que sea más fácil, el ejemplo sólo utiliza el primer argumento del callback. A continuación se muestra un ejemplo en el que se utiliza el método `filter` en el arreglo `users` para devolver un nuevo arreglo que contiene sólo a los usuarios menores de 30 años. Para que sea más fácil, el ejemplo solo utiliza el primer argumento de la función callback.
```js ```js
const users = [ const users = [

View File

@ -18,7 +18,7 @@ Empecemos con algunas funciones de arreglos simples, que son métodos en el prot
El método `map` iterará sobre cada elemento de un arreglo y devuelve un nuevo arreglo que contiene los resultados de llamar a la función callback en cada elemento. Esto lo hace sin mutar el arreglo original. El método `map` iterará sobre cada elemento de un arreglo y devuelve un nuevo arreglo que contiene los resultados de llamar a la función callback en cada elemento. Esto lo hace sin mutar el arreglo original.
Cuando se utiliza el callback, se pasan tres argumentos. El primer argumento es el elemento actual que se está procesando. El segundo es el índice de ese elemento y el tercero es el arreglo al que se llamó el método `map`. Cuando se utiliza la función callback, se pasan tres argumentos. El primer argumento es el elemento actual que se está procesando. El segundo es el índice de ese elemento y el tercero es el arreglo al que se llamó el método `map`.
A continuación se muestra un ejemplo con el método `map` en el arreglo `users` para devolver un nuevo arreglo que contiene solo los nombres de los usuarios como elementos. Para que sea más fácil, el ejemplo solo utiliza el primer argumento del callback. A continuación se muestra un ejemplo con el método `map` en el arreglo `users` para devolver un nuevo arreglo que contiene solo los nombres de los usuarios como elementos. Para que sea más fácil, el ejemplo solo utiliza el primer argumento del callback.

View File

@ -10,7 +10,7 @@ dashedName: use-the-reduce-method-to-analyze-data
`Array.prototype.reduce()` o simplemente `reduce()` es la operación más común de todas para arreglos en JavaScript. Se puede resolver casi cualquier problema de procesamiento de arreglos utilizando el método `reduce`. `Array.prototype.reduce()` o simplemente `reduce()` es la operación más común de todas para arreglos en JavaScript. Se puede resolver casi cualquier problema de procesamiento de arreglos utilizando el método `reduce`.
El método `reduce` permite formas más generales de procesamiento de arreglos y es posible mostrar que tanto `filter` como `map` pueden derivarse como aplicaciones especiales de `reduce`. El método `reduce` itera sobre cada elemento del arreglo y devuelve un solo valor (por ejemplo una cadena, número, objeto, arreglo). Esto se consigue mediante una función de callback que se llama en cada iteración. El método `reduce` permite formas más generales de procesamiento de arreglos y es posible mostrar que tanto `filter` como `map` pueden derivarse como aplicaciones especiales de `reduce`. El método `reduce` itera sobre cada elemento del arreglo y devuelve un solo valor (por ejemplo una cadena, número, objeto, arreglo). Esto se consigue mediante una función callback que se llama en cada iteración.
La función callback acepta cuatro argumentos. El primer argumento se conoce como acumulador, que recibe el valor retornado de la función callback de la iteración anterior, el segundo es el elemento actual que se está procesando, el tercero es el índice de ese elemento y el cuarto es el arreglo sobre el que se llama a la función `reduce`. La función callback acepta cuatro argumentos. El primer argumento se conoce como acumulador, que recibe el valor retornado de la función callback de la iteración anterior, el segundo es el elemento actual que se está procesando, el tercero es el índice de ese elemento y el cuarto es el arreglo sobre el que se llama a la función `reduce`.

View File

@ -14,7 +14,7 @@ Ya has estado usando algunos de estos controladores de eventos sintéticos como
# --instructions-- # --instructions--
Agrega un detector de eventos en el método `componentDidMount()` para los eventos `keydown` y haz que estos eventos ejecuten el callback `handleKeyPress()`. Puedes usar `document.addEventListener()` el cual toma el evento (en comillas) como primer argumento y el callback como segundo argumento. Agrega un detector de eventos en el método `componentDidMount()` para los eventos `keydown` y haz que estos eventos ejecuten la función callback `handleKeyPress()`. Puedes usar `document.addEventListener()` el cual toma el evento (en comillas) como primer argumento y la función callback como segundo argumento.
Posteriormente, en `componentWillUnmount()`, remueve este mismo detector de eventos. Puedes pasar los mismos argumentos al `document.removeEventListener()`. Es buena práctica usar este método del ciclo de vida para hacer cualquier limpieza en un componente de React antes de que estos sean desmontados y destruidos. Removiendo los detectores de eventos es un ejemplo de una limpieza de este tipo. Posteriormente, en `componentWillUnmount()`, remueve este mismo detector de eventos. Puedes pasar los mismos argumentos al `document.removeEventListener()`. Es buena práctica usar este método del ciclo de vida para hacer cualquier limpieza en un componente de React antes de que estos sean desmontados y destruidos. Removiendo los detectores de eventos es un ejemplo de una limpieza de este tipo.

View File

@ -14,7 +14,7 @@ El último desafío mostró cómo el método `map` es usado para representar din
# --instructions-- # --instructions--
El editor de código tiene un arreglo con algunos frameworks frontend y un componente funcional sin estado llamado `Frameworks()`. `Frameworks()` necesita mapear (asignar) el arreglo a una lista desordenada, como en el último desafío. Finaliza la escritura del callback `map` para devolver un elemento `li` por cada framework en el arreglo `frontEndFrameworks`. Esta vez, debes asegurarte de dar a cada elemento `li` un atributo `key`, establecido a un valor único. Los elementos `li` también deben contener texto de `frontEndFrameworks`. El editor de código tiene un arreglo con algunos frameworks frontend y un componente funcional sin estado llamado `Frameworks()`. `Frameworks()` necesita mapear (asignar) el arreglo a una lista desordenada, como en el último desafío. Finaliza la escritura de la función callback `map` para devolver un elemento `li` por cada framework en el arreglo `frontEndFrameworks`. Esta vez, debes asegurarte de dar a cada elemento `li` un atributo `key`, establecido a un valor único. Los elementos `li` también deben contener texto de `frontEndFrameworks`.
Normalmente, deseas hacer que la clave sea algo que identifique de manera única el elemento que se está procesando. Como último recurso se puede utilizar el índice del arreglo, pero normalmente se debe intentar usar una identificación única. Normalmente, deseas hacer que la clave sea algo que identifique de manera única el elemento que se está procesando. Como último recurso se puede utilizar el índice del arreglo, pero normalmente se debe intentar usar una identificación única.

View File

@ -1,6 +1,6 @@
--- ---
id: 5a24c314108439a4d403617b id: 5a24c314108439a4d403617b
title: Pasa un callback como "props" title: Pasa una función callback como "props"
challengeType: 6 challengeType: 6
forumTopicId: 301400 forumTopicId: 301400
dashedName: pass-a-callback-as-props dashedName: pass-a-callback-as-props
@ -14,7 +14,7 @@ Puedes pasar `state` como "props" a los componentes hijos, pero no estás limita
Hay tres componentes descritos en el editor de código. El componente `MyApp` es el padre que renderizará los componentes hijos `GetInput` y `RenderInput`. Añade el componente `GetInput` al método de renderizar en `MyApp`, luego pásale un "prop" llamado `input` asignado a `inputValue` desde el estado `state` de `MyApp`. También crea un "prop" llamado `handleChange` y pasa el controlador de entrada `handleChange` a este. Hay tres componentes descritos en el editor de código. El componente `MyApp` es el padre que renderizará los componentes hijos `GetInput` y `RenderInput`. Añade el componente `GetInput` al método de renderizar en `MyApp`, luego pásale un "prop" llamado `input` asignado a `inputValue` desde el estado `state` de `MyApp`. También crea un "prop" llamado `handleChange` y pasa el controlador de entrada `handleChange` a este.
A continuación, añade `RenderInput` al método de renderizar en `MyApp`, luego crea un "prop" llamado `input` y pasa el `inputValue` desde el estado `state` a este. Una vez que hayas terminado podrás escribir en el campo `input` en el componente `GetInput`, que luego llama al método manejador en su padre a través de "props". Esto actualiza la entrada en el `state` del padre, que se pasa como "props" a ambos hijos. Observa cómo fluyen los datos entre los componentes y cómo la única fuente de verdad sigue siendo el `state` del componente padre. Es cierto que este ejemplo es un poco inventado, pero debe servir para ilustrar cómo los datos y los callbacks pueden ser pasados entre componentes React. A continuación, añade `RenderInput` al método de renderizar en `MyApp`, luego crea un "prop" llamado `input` y pasa el `inputValue` desde el estado `state` a este. Una vez que hayas terminado podrás escribir en el campo `input` en el componente `GetInput`, que luego llama al método manejador en su padre a través de "props". Esto actualiza la entrada en el `state` del padre, que se pasa como "props" a ambos hijos. Observa cómo fluyen los datos entre los componentes y cómo la única fuente de verdad sigue siendo el `state` del componente padre. Es cierto que este ejemplo es un poco inventado, pero debe servir para ilustrar cómo los datos y las funciones callback pueden ser pasados entre componentes React.
# --hints-- # --hints--

View File

@ -41,7 +41,7 @@ El `store.subscribe` debe recibir una función.
(getUserInput) => assert(getUserInput('index').match(/(\s*function\s*)|(\s*\(\s*\)\s*=>)/gm)) (getUserInput) => assert(getUserInput('index').match(/(\s*function\s*)|(\s*\(\s*\)\s*=>)/gm))
``` ```
El callback a `store.subscribe` también debe incrementar la variable global `count` a medida que se actualiza el almacén. La función callback a `store.subscribe` también debe incrementar la variable global `count` a medida que se actualiza el almacén.
```js ```js
assert(store.getState() === count); assert(store.getState() === count);

View File

@ -14,7 +14,7 @@ Un cuadro emergente muestra más información acerca de un elemento en la págin
# --instructions-- # --instructions--
Añade un elemento `title` debajo de cada nodo `rect`. Luego llama al método `text()` con una función de devolución de llamada para que el texto muestre el valor de los datos. Añade un elemento `title` debajo de cada nodo `rect`. Luego llama al método `text()` con una función callback para que el texto muestre el valor de los datos.
# --hints-- # --hints--

View File

@ -14,7 +14,7 @@ Un `circle` en SVG tiene tres atributos principales. Los atributos `cx` y `cy` s
Al igual que la coordenada `rect` `y`, el atributo `cy` para un `circle` se mide desde la parte superior del lienzo SVG, no desde abajo. Al igual que la coordenada `rect` `y`, el atributo `cy` para un `circle` se mide desde la parte superior del lienzo SVG, no desde abajo.
Los tres atributos pueden usar una función de devolución de llamada para establecer sus valores de forma dinámica. Recuerda que todos los métodos encadenados después de `data(dataset)` se ejecutan una vez por elemento en `dataset`. El parámetro `d` en la función de devolución de llamada se refiere al elemento actual en `dataset`, que es un arreglo para cada punto. Utiliza la notación de corchetes, como `d[0]`, para acceder a los valores de ese arreglo. Los tres atributos pueden usar una función callback para establecer sus valores de forma dinámica. Recuerda que todos los métodos encadenados después de `data(dataset)` se ejecutan una vez por elemento en `dataset`. El parámetro `d` en la función callback se refiere al elemento actual en `dataset`, que es un arreglo para cada punto. Utiliza la notación de corchetes, como `d[0]`, para acceder a los valores de ese arreglo.
# --instructions-- # --instructions--

View File

@ -10,7 +10,7 @@ dashedName: add-classes-with-d3
Usar muchos estilos en línea en elementos HTML se vuelve difícil de administrar, incluso para aplicaciones más pequeñas. Es más fácil agregar una clase a los elementos y darle estilo a esa clase una vez usando las reglas CSS. D3 tiene el método `attr()` para agregar cualquier atributo HTML a un elemento, incluido un nombre de clase. Usar muchos estilos en línea en elementos HTML se vuelve difícil de administrar, incluso para aplicaciones más pequeñas. Es más fácil agregar una clase a los elementos y darle estilo a esa clase una vez usando las reglas CSS. D3 tiene el método `attr()` para agregar cualquier atributo HTML a un elemento, incluido un nombre de clase.
El método `attr()` funciona de la misma manera que `style()`. Toma valores separados por comas y puede usar una función de devolución de llamada. A continuación, se muestra un ejemplo para agregar una clase de `container` a una selección: El método `attr()` funciona de la misma manera que `style()`. Toma valores separados por comas y puede usar una función callback. A continuación, se muestra un ejemplo para agregar una clase de `container` a una selección:
```js ```js
selection.attr("class", "container"); selection.attr("class", "container");

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7faa367417b2b2512bd2 id: 587d7faa367417b2b2512bd2
title: Add Labels to D3 Elements title: Agrega etiquetas a elementos D3
challengeType: 6 challengeType: 6
forumTopicId: 301476 forumTopicId: 301476
dashedName: add-labels-to-d3-elements dashedName: add-labels-to-d3-elements
@ -8,69 +8,69 @@ dashedName: add-labels-to-d3-elements
# --description-- # --description--
D3 lets you label a graph element, such as a bar, using the SVG `text` element. D3 te permite etiquetar un elemento gráfico, como una barra, usando el elemento SVG `text`.
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. Como el elemento `rect`, un elemento `text` necesita tener atributos `x` e `y`, para colocarlo en el lienzo SVG. También necesita acceso a los datos para mostrar los valores.
D3 gives you a high level of control over how you label your bars. D3 te da un nivel de control alto sobre cómo etiquetas tus barras.
# --instructions-- # --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. El código en el editor ya vincula los datos a cada nuevo elemento `text`. Primero, añade nodos `text` a el `svg`. Luego, agrega atributos para las coordenadas `x` e `y`. Deben ser calculadas de la misma forma que las de `rect`, excepto el valor `y` para el `text`. Este debe hacer que la etiqueta se ubique 3 unidades más alto que la barra. Finalmente, usa el método de D3 `text()` para establecer la etiqueta igual al valor del punto de datos.
**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. **Nota:** Para que la etiqueta se ubique arriba de la barra, decide si el valor `y` para el `text` debe ser 3 más o 3 menos que el valor `y` de la barra.
# --hints-- # --hints--
The first `text` element should have a label of `12` and a `y` value of `61`. El primer elemento `text` debe tener una etiqueta de `12` y un valor `y` de `61`.
```js ```js
assert($('text').eq(0).text() == '12' && $('text').eq(0).attr('y') == '61'); 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`. El segundo elemento `text` debe tener una etiqueta de `31` y un valor `y` de `4`.
```js ```js
assert($('text').eq(1).text() == '31' && $('text').eq(1).attr('y') == '4'); 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`. El tercer elemento `text` debe tener una etiqueta de `22` y un valor `y` de `31`.
```js ```js
assert($('text').eq(2).text() == '22' && $('text').eq(2).attr('y') == '31'); 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`. El cuarto elemento `text` debe tener una etiqueta de `17` y un valor `y` de `46`.
```js ```js
assert($('text').eq(3).text() == '17' && $('text').eq(3).attr('y') == '46'); 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`. El quinto elemento `text` debe tener una etiqueta de `25` y un valor `y` de `22`.
```js ```js
assert($('text').eq(4).text() == '25' && $('text').eq(4).attr('y') == '22'); 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`. El sexto elemento `text` debe tener una etiqueta de `18` y un valor `y` de `43`.
```js ```js
assert($('text').eq(5).text() == '18' && $('text').eq(5).attr('y') == '43'); 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`. El séptimo elemento `text` debe tener una etiqueta de `29` y un valor `y` de `10`.
```js ```js
assert($('text').eq(6).text() == '29' && $('text').eq(6).attr('y') == '10'); 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`. El octavo elemento `text` debe tener una etiqueta de `14` y un valor `y` de `55`.
```js ```js
assert($('text').eq(7).text() == '14' && $('text').eq(7).attr('y') == '55'); 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`. El noveno elemento `text` debe tener una etiqueta de `9` y un valor `y` de `70`.
```js ```js
assert($('text').eq(8).text() == '9' && $('text').eq(8).attr('y') == '70'); assert($('text').eq(8).text() == '9' && $('text').eq(8).attr('y') == '70');

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7fab367417b2b2512bd9 id: 587d7fab367417b2b2512bd9
title: Add Labels to Scatter Plot Circles title: Añade etiquetas a un diagrama de dispersión
challengeType: 6 challengeType: 6
forumTopicId: 301477 forumTopicId: 301477
dashedName: add-labels-to-scatter-plot-circles dashedName: add-labels-to-scatter-plot-circles
@ -8,25 +8,25 @@ dashedName: add-labels-to-scatter-plot-circles
# --description-- # --description--
You can add text to create labels for the points in a scatter plot. Puedes agregar texto para crear etiquetas para los puntos en un diagrama de dispersión.
The goal is to display the comma-separated values for the first (`x`) and second (`y`) fields of each item in `dataset`. El objetivo es mostrar los valores separados por coma del primer (`x`) y segundo (`y`) campo de cada elemento en `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. Los nodos `text` necesitan atributos `x` e `y` para posicionarlo en el lienzo SVG. En este desafío, el valor `y` (que determina la altura) puede usar el mismo valor que el `circle` usa para su atributo `cy`. El valor `x` puede ser ligeramente mayor que el valor `cx` del `circle` para que la etiqueta sea visible. Esto empujará la etiqueta a la derecha del punto trazado.
# --instructions-- # --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`. Etiqueta cada punto en el diagrama de dispersión usando los elementos `text`. El texto de la etiqueta debe ser los valores separados por una coma y un espacio. Por ejemplo, la etiqueta para el primer punto es `34, 78`. Establece el atributo `x` para que sea `5` unidades mayor que el valor que utilizaste para el atributo `cx` en el `circle`. Establece el atributo `y` de la misma manera que se usa para el valor `cy` en el `circle`.
# --hints-- # --hints--
Your code should have 10 `text` elements. Tu código debe tener 10 elementos `text`.
```js ```js
assert($('text').length == 10); assert($('text').length == 10);
``` ```
The first label should have text of `34, 78`, an `x` value of `39`, and a `y` value of `422`. La primera etiqueta debe tener como texto `34, 78`, un valor de `x` de `39`, y un valor de `y` de `422`.
```js ```js
assert( 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`. La segunda etiqueta debe tener como texto `109, 280`, un valor de `x` de `114`, y un valor de `y` de `220`.
```js ```js
assert( 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`. La tercera etiqueta debe tener como texto `310, 120`, un valor de `x` de `315`, y un valor de `y` de `380`.
```js ```js
assert( 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`. La cuarta etiqueta debe tener como texto `79, 411`, un valor de `x` de `84`, y un valor de `y` de `89`.
```js ```js
assert( 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`. La quinta etiqueta debe tener como texto `420, 220`, un valor de `x` de `425`, y un valor de `y` de `280`.
```js ```js
assert( 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`. La sexta etiqueta debe tener como texto `233, 145`, un valor de `x` de `238`, y un valor de `y` de `355`.
```js ```js
assert( 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`. La séptima etiqueta debe tener como texto `333, 96`, un valor de `x` de `338`, y un valor de `y` de `404`.
```js ```js
assert( 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`. La octava etiqueta debe tener como texto `222, 333`, un valor de `x` de `227`, y un valor de `y` de `167`.
```js ```js
assert( 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`. La novena etiqueta debe tener como texto `78, 320`, un valor de `x` de `83`, y un valor de `y` de `180`.
```js ```js
assert( 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`. La décima etiqueta debe tener como texto `21, 123`, un valor de `x` de `26`, y un valor de `y` de `377`.
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7fa7367417b2b2512bc7 id: 587d7fa7367417b2b2512bc7
title: Change Styles Based on Data title: Cambia estilos con base en los datos
challengeType: 6 challengeType: 6
forumTopicId: 301479 forumTopicId: 301479
dashedName: change-styles-based-on-data dashedName: change-styles-based-on-data
@ -8,9 +8,9 @@ dashedName: change-styles-based-on-data
# --description-- # --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. D3 se trata de la visualización y presentación de datos. Probablemente vayas a querer estilizar los elementos con base en los datos. Puedes usar una función callback en el método `style()` para cambiar el estilo a diferentes elementos.
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 ejemplo, podrías querer colorear un punto de dato a azul si tiene un valor menor a 20, y a rojo en caso contrario. Puedes usar una función callback en el método `style()` e incluir la lógica condicional. La función callback usa el parámetro `d` para representar el punto de dato:
```js ```js
selection.style("color", (d) => { 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. El método `style()` no está limitado a configurar el `color` puede ser usado también con otras propiedades CSS.
# --instructions-- # --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. Agrega el método `style()` al código en el editor para establecer el `color` de los elementos `h2` de manera condicional. Escribe la función callback para que si el valor del dato es menor a 20, retorne rojo, de lo contrario, retorna verde.
**Note:** You can use if-else logic, or the ternary operator. **Nota:** Puedes usar lógica if-else, o el operador ternario.
# --hints-- # --hints--
The first `h2` should have a `color` of red. El primer `h2` debe tener un `color` rojo.
```js ```js
assert($('h2').eq(0).css('color') == 'rgb(255, 0, 0)'); assert($('h2').eq(0).css('color') == 'rgb(255, 0, 0)');
``` ```
The second `h2` should have a `color` of green. El segundo `h2` debe tener un `color` verde.
```js ```js
assert($('h2').eq(1).css('color') == 'rgb(0, 128, 0)'); assert($('h2').eq(1).css('color') == 'rgb(0, 128, 0)');
``` ```
The third `h2` should have a `color` of green. El tercer `h2` debe tener un `color` verde.
```js ```js
assert($('h2').eq(2).css('color') == 'rgb(0, 128, 0)'); assert($('h2').eq(2).css('color') == 'rgb(0, 128, 0)');
``` ```
The fourth `h2` should have a `color` of red. El cuarto `h2` debe tener un `color` rojo.
```js ```js
assert($('h2').eq(3).css('color') == 'rgb(255, 0, 0)'); assert($('h2').eq(3).css('color') == 'rgb(255, 0, 0)');
``` ```
The fifth `h2` should have a `color` of green. El quinto `h2` debe tener un `color` verde.
```js ```js
assert($('h2').eq(4).css('color') == 'rgb(0, 128, 0)'); assert($('h2').eq(4).css('color') == 'rgb(0, 128, 0)');
``` ```
The sixth `h2` should have a `color` of red. El sexto `h2` debe tener un `color` rojo.
```js ```js
assert($('h2').eq(5).css('color') == 'rgb(255, 0, 0)'); assert($('h2').eq(5).css('color') == 'rgb(255, 0, 0)');
``` ```
The seventh `h2` should have a `color` of green. El séptimo `h2` debe tener un `color` verde.
```js ```js
assert($('h2').eq(6).css('color') == 'rgb(0, 128, 0)'); assert($('h2').eq(6).css('color') == 'rgb(0, 128, 0)');
``` ```
The eighth `h2` should have a `color` of red. El octavo `h2` debe tener un `color` rojo.
```js ```js
assert($('h2').eq(7).css('color') == 'rgb(255, 0, 0)'); assert($('h2').eq(7).css('color') == 'rgb(255, 0, 0)');
``` ```
The ninth `h2` should have a `color` of red. El noveno `h2` debe tener un `color` rojo.
```js ```js
assert($('h2').eq(8).css('color') == 'rgb(255, 0, 0)'); assert($('h2').eq(8).css('color') == 'rgb(255, 0, 0)');

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7fa9367417b2b2512bd1 id: 587d7fa9367417b2b2512bd1
title: Change the Color of an SVG Element title: Cambia el color de un elemento SVG
challengeType: 6 challengeType: 6
forumTopicId: 301480 forumTopicId: 301480
dashedName: change-the-color-of-an-svg-element dashedName: change-the-color-of-an-svg-element
@ -8,17 +8,17 @@ dashedName: change-the-color-of-an-svg-element
# --description-- # --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. Las barras están en la posición correcta, pero todas son del mismo color negro. SVG tiene una manera de cambiar el color de las 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. En SVG una figura `rect` es coloreada con el atributo `fill`. Admite códigos hexadecimales, nombres de colores y valores rgb, así como opciones más complejas como degradados y transparencias.
# --instructions-- # --instructions--
Add an `attr()` method to set the `fill` of all the bars to the color navy. Agrega un método `attr()` para establecer el `fill` (relleno) de todas las barras a un color azul marino.
# --hints-- # --hints--
The bars should all have a `fill` color of navy. Todas las barras deberían tener un color de `fill` azul marino.
```js ```js
assert($('rect').css('fill') == 'rgb(0, 0, 128)'); assert($('rect').css('fill') == 'rgb(0, 0, 128)');

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7fa8367417b2b2512bca id: 587d7fa8367417b2b2512bca
title: Change the Presentation of a Bar Chart title: Cambia la presentación de un gráfico de barras
challengeType: 6 challengeType: 6
forumTopicId: 301481 forumTopicId: 301481
dashedName: change-the-presentation-of-a-bar-chart dashedName: change-the-presentation-of-a-bar-chart
@ -8,21 +8,21 @@ dashedName: change-the-presentation-of-a-bar-chart
# --description-- # --description--
The last challenge created a bar chart, but there are a couple of formatting changes that could improve it: El último desafío creó un gráfico de barras, pero hay algunos cambios en el formateo que podrían mejorarlo:
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) Agrega espacio entre cada barra para separarlas visualmente, lo cual se hace agregando un margen al CSS de la clase `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) Aumenta la altura de las barras para visualizar mejor la diferencia de valores, lo cual se realiza multiplicando cada valor por un número para escalar la altura
# --instructions-- # --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`). Primero, agrega un `margin` de `2px` a la clase `bar` en la etiqueta `style`. A continuación, cambia la función callback en el método `style()` para que retorne un valor `10` veces más grande que el valor del dato original (mas el `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. **Nota:** Multiplicar cada punto de dato por la *misma* constante solo altera la escala. Es como acercarnos, y no cambia el significado de los datos subyacentes.
# --hints-- # --hints--
The first `div` should have a `height` of `120` pixels and a `margin` of `2` pixels. El primer `div` debe tener un `height` de `120` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(
@ -31,7 +31,7 @@ assert(
); );
``` ```
The second `div` should have a `height` of `310` pixels and a `margin` of `2` pixels. El segundo `div` debe tener un `height` de `310` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(
@ -40,7 +40,7 @@ assert(
); );
``` ```
The third `div` should have a `height` of `220` pixels and a `margin` of `2` pixels. El tercer `div` debe tener un `height` de `220` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(
@ -49,7 +49,7 @@ assert(
); );
``` ```
The fourth `div` should have a `height` of `170` pixels and a `margin` of `2` pixels. El cuarto `div` debe tener un `height` de `170` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(
@ -58,7 +58,7 @@ assert(
); );
``` ```
The fifth `div` should have a `height` of `250` pixels and a `margin` of `2` pixels. El quinto `div` debe tener un `height` de `250` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(
@ -67,7 +67,7 @@ assert(
); );
``` ```
The sixth `div` should have a `height` of `180` pixels and a `margin` of `2` pixels. El sexto `div` debe tener un `height` de `180` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(
@ -76,7 +76,7 @@ assert(
); );
``` ```
The seventh `div` should have a `height` of `290` pixels and a `margin` of `2` pixels. El séptimo `div` debe tener un `height` de `290` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(
@ -85,7 +85,7 @@ assert(
); );
``` ```
The eighth `div` should have a `height` of `140` pixels and a `margin` of `2` pixels. El octavo `div` debe tener un `height` de `140` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(
@ -94,7 +94,7 @@ assert(
); );
``` ```
The ninth `div` should have a `height` of `90` pixels and a `margin` of `2` pixels. El noveno `div` debe tener un `height` de `90` pixeles y un `margin` de `2` pixeles.
```js ```js
assert( assert(

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7fa8367417b2b2512bcd id: 587d7fa8367417b2b2512bcd
title: Create a Bar for Each Data Point in the Set title: Crea una barra para cada punto de dato en el set
challengeType: 6 challengeType: 6
forumTopicId: 301482 forumTopicId: 301482
dashedName: create-a-bar-for-each-data-point-in-the-set 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-- # --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`. El anterior desafío agrega solo un rectángulo al elemento `svg` para representar una barra. Ahora, combinarás lo que has aprendido hasta ahora sobre `data()`, `enter()`, y formas SVG para crear y añadir un rectángulo para cada punto de dato en `dataset`.
A previous challenge showed the format for how to create and append a `div` for each item in `dataset`: Uno de los desafíos anteriores mostró el formato para cómo crear y añadir un `div` para cada elemento en `dataset`:
```js ```js
d3.select("body").selectAll("div") d3.select("body").selectAll("div")
@ -19,33 +19,33 @@ d3.select("body").selectAll("div")
.append("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. Hay algunas diferencias cuando trabajamos con elementos `rect` en lugar de elementos `div`. Los elementos `rect` deben ser añadidos a un elemento `svg`, no directamente al `body`. Además, necesitas decirle a D3 donde colocar cada `rect` dentro del área `svg`. El posicionamiento de la barra lo veremos en el siguiente desafío.
# --instructions-- # --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. Usa los métodos `data()`, `enter()`, y `append()` para crear y agregar un `rect` por cada elemento en `dataset`. Las barras deben mostrarse una arriba de la otra, esto será arreglado en el siguiente desafío.
# --hints-- # --hints--
Your document should have 9 `rect` elements. Tu documento debe tener 9 elementos `rect`.
```js ```js
assert($('rect').length == 9); assert($('rect').length == 9);
``` ```
Your code should use the `data()` method. Tu código debe usar el método `data()`.
```js ```js
assert(code.match(/\.data/g)); assert(code.match(/\.data/g));
``` ```
Your code should use the `enter()` method. Tu código debe usar el método `enter()`.
```js ```js
assert(code.match(/\.enter/g)); assert(code.match(/\.enter/g));
``` ```
Your code should use the `append()` method. Tu código debe usar el método `append()`.
```js ```js
assert(code.match(/\.append/g)); assert(code.match(/\.append/g));

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7fab367417b2b2512bda id: 587d7fab367417b2b2512bda
title: Create a Linear Scale with D3 title: Crea una escala lineal con D3
challengeType: 6 challengeType: 6
forumTopicId: 301483 forumTopicId: 301483
dashedName: create-a-linear-scale-with-d3 dashedName: create-a-linear-scale-with-d3
@ -8,41 +8,41 @@ dashedName: create-a-linear-scale-with-d3
# --description-- # --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. La barra y los diagramas de dispersión dibujan los datos directamente en el lienzo SVG. Sin embargo, si la altura de una barra o uno de los puntos de dato fuesen mayores que los valores de ancho (width) o largo (height) del SVG, se irían fuera del área del 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. En D3, hay escalas para ayudar a trazar datos. `scales` son funciones que le dicen al programa cómo asignar un conjunto de puntos de datos en bruto, a los píxeles del lienzo 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 ejemplo, digamos que tienes un lienzo SVG de 100x500 y quieres trazar el Producto Bruto Interno(PBI) para una cantidad de países. El conjunto de números estaría en el rango de miles de millones o billones de dólares. Tú le provees a D3 un tipo de escala para decirle como colocar los grandes valores de PBI en esa área de tamaño 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. Es muy poco probable que traces los datos en bruto tal como son. Antes de trazarlo, estableces la escala para todo tu conjunto de datos(data set), para que los valores de `x` e `y` vayan dentro del alto y ancho de tu lienzo.
D3 has several scale types. For a linear scale (usually used with quantitative data), there is the D3 method `scaleLinear()`: D3 tiene varios tipos de escalas. Para una escala lineal (usualmente usada con datos cuantitativos), existe el método de D3 `scaleLinear()`:
```js ```js
const scale = d3.scaleLinear() 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 defecto, una escala usa la relación de identidad. El valor de la entrada es el mismo que el valor de la salida. Un desafío aparte cubre como cambiar esto.
# --instructions-- # --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`. Cambia la variable `scale` para crear una escala lineal. Luego, establece la variable `output` a la escala llamada, con un argumento de entrada (input) de `50`.
# --hints-- # --hints--
The text in the `h2` should be `50`. El texto en el `h2` debe ser `50`.
```js ```js
assert($('h2').text() == '50'); assert($('h2').text() == '50');
``` ```
Your code should use the `scaleLinear()` method. Tu código debe utilizar el método `scaleLinear()`.
```js ```js
assert(code.match(/\.scaleLinear/g)); assert(code.match(/\.scaleLinear/g));
``` ```
The `output` variable should call `scale` with an argument of `50`. La variable `output` debe llamar a `scale` con un argumento de `50`.
```js ```js
assert(output == 50 && code.match(/scale\(\s*?50\s*?\)/g)); assert(output == 50 && code.match(/scale\(\s*?50\s*?\)/g));

View File

@ -1,6 +1,6 @@
--- ---
id: 587d7fab367417b2b2512bd7 id: 587d7fab367417b2b2512bd7
title: Create a Scatterplot with SVG Circles title: Crea un diagrama de dispersión con círculos SVG
challengeType: 6 challengeType: 6
forumTopicId: 301484 forumTopicId: 301484
dashedName: create-a-scatterplot-with-svg-circles dashedName: create-a-scatterplot-with-svg-circles
@ -8,19 +8,19 @@ dashedName: create-a-scatterplot-with-svg-circles
# --description-- # --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. Un diagrama de dispersión es otro tipo de gráfico. Usualmente utiliza círculos para trazar los datos, los cuales tienen dos valores cada uno. Estos valores están vinculados a los ejes `x` asimismo `y`, son usados para posicionar el circulo en el gráfico.
SVG has a `circle` tag to create the circle shape. It works a lot like the `rect` elements you used for the bar chart. SVG tiene una etiqueta `circle` para crear la forma de un circulo. Se parece mucho en funcionamiento al elemento `rect` que has utilizado para el gráfico de barras.
# --instructions-- # --instructions--
Use the `data()`, `enter()`, and `append()` methods to bind `dataset` to new `circle` elements that are appended to the SVG canvas. Usa los métodos `data()`, `enter()` y `append()` para enlazar `dataset` con nuevos elementos `circle` que serán añadidos al lienzo SVG.
**Note:** The circles won't be visible because we haven't set their attributes yet. We'll do that in the next challenge. **Nota:** Los círculos no serán visibles porque aún no establecimos sus atributos. Haremos esto en el siguiente desafío.
# --hints-- # --hints--
Your code should have 10 `circle` elements. Tu código debe tener 10 elementos `circle`.
```js ```js
assert($('circle').length == 10); assert($('circle').length == 10);