DEV Community

Pedro Filho
Pedro Filho

Posted on • Updated on

Data Visualization with D3, React, visx and Typescript: 2 - Data Basics

It's not every day that you have a perfect dataset to work with, most of the time you'll need to apply transformations to properties to get it right for your visualization. This is pretty simple, and usually it's the first thing you do when you think about a chart.

Let's say that you have something like this to build a single line chart

[
    {
        name: "Bitcoin",
        price: 10,
        base: "USD",
        date: '1560507303',
        creator: "Satoshi Nakamoto",
    },
    {
        name: "Bitcoin",
        price: 12,
        base: "USD",
        date: '1592129703',
        creator: "Satoshi Nakamoto",
    }
]
Enter fullscreen mode Exit fullscreen mode

I need an X and an Y, and I already have it, right? But you need the date to be something more human-friendly, and the price, you want it to be in cents, not dollars. How would you do it?

const format = d3.time.format('%B %d, %Y')

const data = rawData.map(oldData => ({
    price: oldData.price * 100,
    date: format.parse(oldData.date)
}))
Enter fullscreen mode Exit fullscreen mode

But this isn't very functional, right? We should do something better for it! What if we create a function to transform A to B? Something like this

const format = d3.time.format('%B %d, %Y')

const getPrice = price => price * 100
const getDate = date => format.parse(oldData.date)
Enter fullscreen mode Exit fullscreen mode

Then you can use it like this:

const data = rawData.map(oldData => ({
    price: getPrice(oldData.price),
    date: getDate(oldData.date)
}))
Enter fullscreen mode Exit fullscreen mode

Then, you would have something like this in the end

[
    {
        price: 1000,
        date: 'June 14, 2019'
    },
    {

        price: 1200,
        date: 'June 14, 2020'   
    }
]
Enter fullscreen mode Exit fullscreen mode

Nice, right?

This is what we call accessors, and they are really helpful to get and transform data inside your dataset.

I hope you liked it! For the next chapter, I'll talk about D3, so stay tuned!

Top comments (0)