[React] Nivo Chart 사용기

반응형

1. Nivo를 선택한 이유

평소에 React나 프론트 개발을 할 일이 많이 없지만, 가끔 모델의 결과를 직관적으로 표출하기 위해 차트를 사용한다. 원래는 Chartjs 를 사용했지만, 본격적으로 팀이 React로 개발하는 일이 많아지면서 좀 더 리액트스럽다고 하는 Nivo Chart를 사용해 보았다.

 

Chartjs는 워낙 유명하기 때문에 Examples도 많고, 블로그 글도 많았다. 나는 기본 차트가 아닌 커스텀 차트를 많이 개발했어야 했기 때문에, 유튜브 튜토리얼도 많이 참고했다. 차차 Chartjs 커스텀 차트는 소개하도록 하겠다. 

 

Nivo는 유튜브 튜토리얼은 따로 없었지만, 공식 홈페이지에 사용법이 자세하게 적혀 있어서 바로 사용하기 편리했다. 무엇보다 편리했던 점은 하나하나 코드를 적을 필요 없이 차트를 선택하고, 원하는 차트 설정을 선택해주기만 하면 바로 코드를 복사할 수 있었다. 

 

원하는 차트의 옵션을 마우스로 선택하면 차트의 모양이 바뀐다!

2. Nivo Bar Chart 그리기

나는 Nivo 라이브러리를 사용하여 Horizontal Bar graph를 그려보고자 한다. 먼저 Nivo를 설치한다. Nivo를 설치하려면 다음과 같이 설치한다. @nivo/bar을 통해 Bar graph를 그릴 수 있게 되며, 원하는 차트를 그리기 위해서는 @nivo/[원하는 차트] 이렇게 설치를 해주어야 한다. 

yarn add @nivo/core @nivo/bar

 

Nivo를 설치하고 나면 다음과 같이 Nivo 라이브러리에서 Responsive bar를 불러올 수 있게 된다.

import { ResponsiveBar } from "@nivo/bar";

 

Nivo 홈페이지에서 Bar graph를 선택한 후, 원하는 옵션값을 선택한다. 제일 처음 홈페이지에 들어가 </> code를 누르면 다음과 같이 기본 Bar graph 코드가 나온다. 

// install (please make sure versions match peerDependencies)
// yarn add @nivo/core @nivo/bar
import { ResponsiveBar } from '@nivo/bar'

// make sure parent container have a defined height when using
// responsive component, otherwise height will be 0 and
// no chart will be rendered.
// website examples showcase many properties,
// you'll often use just a few of them.
const MyResponsiveBar = ({ data /* see data tab */ }) => (
    <ResponsiveBar
        data={data}
        keys={[
            'hot dog',
            'burger',
            'sandwich',
            'kebab',
            'fries',
            'donut'
        ]}
        indexBy="country"
        margin={{ top: 50, right: 130, bottom: 50, left: 60 }}
        padding={0.3}
        layout="horizontal"
        valueScale={{ type: 'linear' }}
        indexScale={{ type: 'band', round: true }}
        colors={{ scheme: 'nivo' }}
        defs={[
            {
                id: 'dots',
                type: 'patternDots',
                background: 'inherit',
                color: '#38bcb2',
                size: 4,
                padding: 1,
                stagger: true
            },
            {
                id: 'lines',
                type: 'patternLines',
                background: 'inherit',
                color: '#eed312',
                rotation: -45,
                lineWidth: 6,
                spacing: 10
            }
        ]}
        fill={[
            {
                match: {
                    id: 'fries'
                },
                id: 'dots'
            },
            {
                match: {
                    id: 'sandwich'
                },
                id: 'lines'
            }
        ]}
        borderColor={{
            from: 'color',
            modifiers: [
                [
                    'darker',
                    1.6
                ]
            ]
        }}
        axisTop={null}
        axisRight={null}
        axisBottom={{
            tickSize: 5,
            tickPadding: 5,
            tickRotation: 0,
            legend: 'country',
            legendPosition: 'middle',
            legendOffset: 32
        }}
        axisLeft={{
            tickSize: 5,
            tickPadding: 5,
            tickRotation: 0,
            legend: 'food',
            legendPosition: 'middle',
            legendOffset: -40
        }}
        labelSkipWidth={12}
        labelSkipHeight={12}
        labelTextColor={{
            from: 'color',
            modifiers: [
                [
                    'darker',
                    1.6
                ]
            ]
        }}
        legends={[
            {
                dataFrom: 'keys',
                anchor: 'bottom-right',
                direction: 'column',
                justify: false,
                translateX: 120,
                translateY: 0,
                itemsSpacing: 2,
                itemWidth: 100,
                itemHeight: 20,
                itemDirection: 'left-to-right',
                itemOpacity: 0.85,
                symbolSize: 20,
                effects: [
                    {
                        on: 'hover',
                        style: {
                            itemOpacity: 1
                        }
                    }
                ]
            }
        ]}
        role="application"
        ariaLabel="Nivo bar chart demo"
        barAriaLabel={e=>e.id+": "+e.formattedValue+" in country: "+e.indexValue}
    />
)

 

위 그래프를 직접 수정해도 되고, 원하는 옵션을 마우스로 클릭하여 수정해서 코드를 다시 복사할 수 있다. 만약 Bar 그래프가 원하는 모양이 아니거나 Custom을 하고 싶다면 링크를 참조해 수정할 수 있다.

 

기본적인 데이터의 포맷은 리스트 안의 dictionary로 위의 그래프를 그리기 위한 데이터는 다음과 같다. 

[
  {
    "country": "AD",
    "hot dog": 0,
    "hot dogColor": "hsl(188, 70%, 50%)",
    "burger": 17,
    "burgerColor": "hsl(24, 70%, 50%)",
    "sandwich": 72,
    "sandwichColor": "hsl(150, 70%, 50%)",
    "kebab": 73,
    "kebabColor": "hsl(40, 70%, 50%)",
    "fries": 112,
    "friesColor": "hsl(12, 70%, 50%)",
    "donut": 154,
    "donutColor": "hsl(148, 70%, 50%)"
  },
  {
    "country": "AE",
    "hot dog": 79,
    "hot dogColor": "hsl(124, 70%, 50%)",
    "burger": 148,
    "burgerColor": "hsl(229, 70%, 50%)",
    "sandwich": 84,
    "sandwichColor": "hsl(56, 70%, 50%)",
    "kebab": 175,
    "kebabColor": "hsl(238, 70%, 50%)",
    "fries": 45,
    "friesColor": "hsl(203, 70%, 50%)",
    "donut": 69,
    "donutColor": "hsl(274, 70%, 50%)"
  },
  {
    "country": "AF",
    "hot dog": 19,
    "hot dogColor": "hsl(293, 70%, 50%)",
    "burger": 33,
    "burgerColor": "hsl(215, 70%, 50%)",
    "sandwich": 155,
    "sandwichColor": "hsl(75, 70%, 50%)",
    "kebab": 111,
    "kebabColor": "hsl(221, 70%, 50%)",
    "fries": 97,
    "friesColor": "hsl(275, 70%, 50%)",
    "donut": 51,
    "donutColor": "hsl(181, 70%, 50%)"
  },
  {
    "country": "AG",
    "hot dog": 174,
    "hot dogColor": "hsl(283, 70%, 50%)",
    "burger": 57,
    "burgerColor": "hsl(347, 70%, 50%)",
    "sandwich": 1,
    "sandwichColor": "hsl(330, 70%, 50%)",
    "kebab": 28,
    "kebabColor": "hsl(208, 70%, 50%)",
    "fries": 32,
    "friesColor": "hsl(201, 70%, 50%)",
    "donut": 25,
    "donutColor": "hsl(93, 70%, 50%)"
  },
  {
    "country": "AI",
    "hot dog": 101,
    "hot dogColor": "hsl(104, 70%, 50%)",
    "burger": 179,
    "burgerColor": "hsl(187, 70%, 50%)",
    "sandwich": 159,
    "sandwichColor": "hsl(258, 70%, 50%)",
    "kebab": 175,
    "kebabColor": "hsl(15, 70%, 50%)",
    "fries": 127,
    "friesColor": "hsl(145, 70%, 50%)",
    "donut": 155,
    "donutColor": "hsl(166, 70%, 50%)"
  },
  {
    "country": "AL",
    "hot dog": 191,
    "hot dogColor": "hsl(162, 70%, 50%)",
    "burger": 156,
    "burgerColor": "hsl(127, 70%, 50%)",
    "sandwich": 107,
    "sandwichColor": "hsl(291, 70%, 50%)",
    "kebab": 80,
    "kebabColor": "hsl(223, 70%, 50%)",
    "fries": 174,
    "friesColor": "hsl(53, 70%, 50%)",
    "donut": 60,
    "donutColor": "hsl(220, 70%, 50%)"
  },
  {
    "country": "AM",
    "hot dog": 24,
    "hot dogColor": "hsl(193, 70%, 50%)",
    "burger": 69,
    "burgerColor": "hsl(354, 70%, 50%)",
    "sandwich": 92,
    "sandwichColor": "hsl(312, 70%, 50%)",
    "kebab": 129,
    "kebabColor": "hsl(56, 70%, 50%)",
    "fries": 55,
    "friesColor": "hsl(354, 70%, 50%)",
    "donut": 159,
    "donutColor": "hsl(0, 70%, 50%)"
  }
]

위 코드를 사용해 그래프를 그리면 다음과 같이 나오게 된다.

Nivo Bar Chart 예시

원하는 데이터를 가지고 data 변수에 넣어주면 원하는 막대그래프를 그릴 수 있다. 

 

참고 : 

https://nivo.rocks/ 

반응형