(Más fácil) Visualización interactiva de datos en React

Rate this content
Bookmark

Si estás construyendo un tablero de control, una plataforma de análisis o cualquier aplicación web donde necesites dar a tus usuarios una visión de sus datos, necesitas hermosas, personalizadas, visualizaciones de datos interactivas en tu aplicación React. Pero construir visualizaciones a mano con una biblioteca de bajo nivel como D3 puede ser un gran dolor de cabeza, que implica reinventar la rueda. En esta charla, veremos cómo el desarrollo de visualización de datos puede ser mucho más fácil gracias a herramientas como Plot, una biblioteca de dataviz de alto nivel para una rápida y fácil creación de gráficos, y Observable, un entorno de prototipado de dataviz reactivo, ambos del creador de D3. A través de ejemplos de codificación en vivo, exploraremos cómo los refs de React nos permiten delegar la manipulación del DOM para nuestras visualizaciones de datos, y cómo la funcionalidad de incrustación de Observable nos permite reutilizar fácilmente las visualizaciones construidas por la comunidad para nuestros propios datos y casos de uso. Al final de esta charla, sabremos cómo obtener una hermosa, personalizada, visualización de datos interactiva en nuestras aplicaciones con una fracción del tiempo y esfuerzo!

Anjana Vakil
Anjana Vakil
27 min
22 Oct, 2021

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Esta charla trata sobre la visualización interactiva de datos en React utilizando la biblioteca Plot. Plot es una biblioteca de alto nivel que simplifica el proceso de visualización de datos al proporcionar conceptos clave y valores predeterminados para las decisiones de diseño. Se puede integrar con React utilizando hooks como useRef y useEffect. Plot permite la personalización y admite características como la clasificación y la adición de marcas adicionales. La charla también discute las preocupaciones de accesibilidad, el soporte SSR y compara Plot con otras bibliotecas como D3 y Vega-Lite.

Available in English

1. Introducción a la visualización de datos interactiva en React

Short description:

Hola, amigos. ¿Cómo les va? Soy Anjana Vakil, una defensora de los desarrolladores en Observable. Hoy, hablaré sobre la visualización de datos interactiva en React. Visualizar datos puede ayudar a descubrir significado, patrones e insights. La visualización de datos es valiosa para las aplicaciones web, los paneles de control y los insights del usuario. Es un campo amplio, pero podemos construir visualizaciones efectivas sin aprender todo. Exploraremos cómo hacer una aplicación de visualización de datos reactiva en React usando la trama Observable.

Hola, amigos. ¿Cómo les va? Es muy bueno ver sus caras. Es muy bueno verlos a todos aquí. Dios mío. Hola. Soy Anjana Vakil, una defensora de los desarrolladores en Observable y estoy muy feliz de estar aquí con todos ustedes, ya sea en persona o en la transmisión en vivo.

¿Qué tal, todos? Estoy realmente emocionada de hablar con todos hoy sobre la visualización interactiva de data en React. Las diapositivas de esta presentación y todos los enlaces y todo están en esa URL en observableHQ.com y trataré de tuitear eso después de la charla también.

Así que soy relativamente nueva en el mundo de la visualización de data como desarrolladora de software, desarrolladora de JavaScript pero aquí hay algunas cosas que he estado aprendiendo sobre la visualization de data. Una cosa es que cuando tienes un montón de data, visualizarla, ponerla frente a los ojos de las personas de una manera efectiva puede ser la forma más impresionante de descubrir rápidamente el significado real de esa data, ver patterns en ella, obtener insights reales, poder tomar decisiones basadas en ella. Eso significa que la visualización de data es un componente extremadamente útil en muchos tipos diferentes de aplicaciones web.

Entonces, por supuesto, cualquier tipo de panel de control que puedas estar construyendo probablemente va a tener una visualización de data involucrada. Cualquier momento en que estés tratando de dar a tus usuarios insights sobre su propia data en tus plataformas. Levanta la mano si tuviste que construir algún tipo de visualización de data en alguna de tus aplicaciones. Muchas manos. Y estoy segura de que también hay muchas manos en el ciberespacio. Así que esto significa que también es una habilidad muy valiosa para tener en tu currículum o como parte de tu portafolio de desarrollador. Así que algo que vale la pena aprender un poco. Sin embargo, la visualización de data es un campo muy, muy amplio. Es algo en lo que podrías pasar toda tu vida y career profundizando y obteniendo una disertación, escribiendo una disertación y convirtiéndote en un experto y nunca llegar al fondo de. ¿Eso significa que para construir visualizaciones efectivas en mis aplicaciones, tengo que, además de todas las cosas regulares de la web y React y JavaScript que necesito saber, también tengo que aprender sobre análisis estadístico y teoría del color y percepción visual humana y todas estas cosas diferentes. Eso suena realmente abrumador y difícil. ¿Cómo puedo construir una buena visualization sin tener que rededicar mi vida a aprender todo lo que hay que saber sobre la visualización de data.

Así que puede parecer realmente desalentador, puede parecer realmente difícil. Lo que esperamos explorar hoy en el corto tiempo que tenemos juntos es cómo podemos hacer una aplicación de visualización de data interactiva reactiva en React sin tener que aprender todo lo que hay que saber sobre la visualización de data. ¿Cómo puedo apoyarme en los hombros de gigantes y poner en marcha esta visualización de data lo más rápido posible. Lo que tenemos aquí y esto es lo que vamos a construir hoy si los dioses de la demostración están con nosotros es una simple visualization de la frecuencia de diferentes letras en el idioma inglés y es algo que yo como usuario puedo ordenar de la manera que quiera verlo. Así que puedo ordenarlos por la frecuencia descendente y ver que está un poco cubierto aquí pero la E es la letra más frecuente. Así que esto es lo que vamos a intentar construir y esperamos ver cómo no necesitamos reinventar la rueda para hacerlo. La herramienta que vamos a usar para este trabajo es una nueva biblioteca de DataVis de código abierto relativamente nueva llamada Observable plot.

2. Introducción a la biblioteca Plot

Short description:

Plot es una biblioteca de alto nivel creada por la misma persona que creó D3. Te permite crear visualizaciones significativas y personalizables rápidamente. Plot emplea una gramática de gráficos, una forma de describir y sistematizar la creación de gráficos. Proporciona conceptos clave como marcas, escalas, transformaciones y facetas para crear gráficos poderosos y complejos. Los valores predeterminados de la biblioteca toman decisiones de diseño por ti, simplificando el proceso de visualización de datos.

Entonces, Plot, al igual que Observable, fue creado por la misma persona que creó la biblioteca D3 si la gente ha oído hablar de eso o se ha encontrado con eso, viendo algunos asentimientos. Entonces, Mike Bostock, quien también es CTO en Observable y algunos de nuestros otros compañeros de equipo en Observable crearon esta increíble biblioteca de DataVis que se lanzó de código abierto a principios de este año.

Y Plot es una biblioteca de muy alto nivel. Por lo tanto, te permite obtener rápidamente un gráfico significativo en funcionamiento al mismo tiempo que te da la flexibilidad para poder personalizar y construir exactamente el tipo de visualization que necesitas para tus propósitos en lugar de elegir uno de un conjunto limitado de opciones listas para usar.

Entonces, cómo hace esto es gracias a una API muy simple y muy poderosa que se basa en la noción de algo llamado una gramática de gráficos. Entonces, esta es una forma de pensar en describir y sistematizar cómo podemos armar un gráfico, prácticamente cualquier tipo de gráfico que podamos imaginar, a partir de unos pocos conceptos básicos.

Y esto es algo que ha estado en el mundo de la data vis durante mucho tiempo, por lo que tenemos expertos y toneladas de décadas de investigación en data vis incorporadas en esta gramática de gráficos. Y luego, PLOT emplea esta gramática de gráficos, pero la implementa sobre D3. Entonces, también tenemos a Mike y al resto del equipo de D3, una década de experiencia construyendo visualizaciones basadas en SVG para la web, todo incorporado en esta biblioteca.

Entonces, es esencialmente como tener un pequeño amigo experto en data vis en tu bolsillo que puede ayudarte a descubrir el mejor gráfico para construir. Y cómo hace eso es por medio de algunos conceptos clave. No vamos a entrar en detalle en todos ellos. Podrías leer todo sobre ello. Pero hay cosas como marcas, que son los elementos visuales que vemos en la página. Esto podría ser una barra. Podría ser una línea. Podría ser puntos en un gráfico de dispersión. Hay escalas, que son esencialmente funciones que transforman los valores que tengo en mi conjunto de data, por lo que en mi espacio de data, en valores en la representación visual real.

Entonces, esto podría ser tomar esos números de frecuencia y convertirlos en píxeles de cuán alta será la barra en la pantalla. Un par de características de las que no vamos a hablar mucho, pero son súper útiles para crear visualizaciones más personalizadas, cosas como transformaciones, por lo que podemos hacer agregaciones, como suma, media, ese tipo de cosas, y facetas, que te permiten tomar una data vis y dividirla en subvisualizaciones más pequeñas que se centran en un subconjunto de la data.

Entonces, con estos pocos conceptos, que no tardan mucho en entender, puedes crear gráficos realmente poderosos y realmente complejos que se ajusten completamente a lo que sea que necesites. Pero al mismo tiempo, puedes permitir que los valores predeterminados incorporados en Plot tomen muchas de las decisiones por ti, para que no necesites aprender todo lo que hay que saber sobre cómo organizar perfectamente las cosas en la pantalla.

Entonces, echemos un vistazo a cómo se siente realmente escribir algo de Plot. Espero que la gente pueda leer esto bien en la parte de atrás. Voy a tomar eso como un sí. Vale. Entonces, lo que tengo aquí es algo de data sobre estas letras y su frecuencia relativa. Entonces, tengo una matriz de pequeños objetos de data, datos, que tienen una propiedad de letra y frecuencia. Para crear un Plot, es una simple llamada al método Plot en este objeto Plot con P mayúscula que va a crear un SVG. Y este SVG es súper aburrido.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
Building Better Websites with Remix
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a new web framework from the creators of React Router that helps you build better, faster websites through a solid understanding of web fundamentals. Remix takes care of the heavy lifting like server rendering, code splitting, prefetching, and navigation and leaves you with the fun part: building something awesome!
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced Conference 2023React Advanced Conference 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
React provides a contract to developers- uphold certain rules, and React can efficiently and correctly update the UI. In this talk we'll explore these rules in depth, understanding the reasoning behind them and how they unlock new directions such as automatic memoization. 
Using useEffect Effectively
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Concurrent Rendering Adventures in React 18
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Top Content
Featured WorkshopFree
Maurice de Beijer
Maurice de Beijer
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
React Hooks Tips Only the Pros Know
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Web3 Workshop - Building Your First Dapp
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured WorkshopFree
Nader Dabit
Nader Dabit
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
Designing Effective Tests With React Testing Library
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
Josh Justice
Josh Justice
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn