Recharts

hatban·2023년 5월 28일
0

Recharts는 데이터를 차트로 시각화 할 수 있는 라이브러리다

설치

$ npm install recharts

공통적으로 자주 쓰이는 기능들

XAxis

  • X축의 값
  • datakey : 특정 data의 값으로 X축 보여줄 때 사용
  • interval : tick의 값을 얼마정도로 지정할 것인지, 0으로 지정하면 모든 tick들을 보여준다
  • 이외에 tickSize, style요소 등등 여러가지를 커스터마이즈 가능

YAxis

  • Y축의 값
  • datakey : 특정 data의 값으로 Y축 보여줄 때 사용
  • tickCount : 세로축의 tick 개수(default = 5)
  • tickFormatter : 직접 tick을 커스터 마이즈하는 함수넣기

Legend

  • 범례를 표시
  • iconType : 'line' | 'plainline' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye’
  • align, verticalAlign : 수평, 수직 나열 속성정의
  • payload : 값을 배열로 전달하면 각 배열의 속성을 기준으로 생성
payload={[
          { value: "A", type: "square", color: genieColor },
          { value: "B", type: "square", color: subColor1 },
          { value: "C", type: "square", color: subColor2 },
        ]}

Tooltip

  • 마우스를 가져다대면 해당 지점의 값을 보여준다
  • formatter : tooltip의 값과 속성을 지정
- 마우스를 가져다대면 해당 지점의 값을 보여준다
- formatter : tooltip의 값과 속성을 지정

ResponsiveContainer

  • parent container의 사이즈에 따라서 차트를 반응형으로 만들 수 있다
  • 사용하는 차트를 ResponsiveContainer 태그로 감싸면된다

CartesianGrid

  • 표의 배경에 깔리는 그리드
  • strokeDasharray : dash의 패턴과 사이 간격 설정


몇가지 차트 예시

AreaChart

<AreaChart width={width} height={height} data={data} margin={margin}>
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis
        dataKey="date"
        interval={0}
        tickMargin={10}
        style={{ fontSize: "13px" }}
        height={40}
      />
      <YAxis tickCount={10} style={{ fontSize: "13px" }} />
      <Area
	      fillOpacity="1" 
        type="monotone"
        dataKey="streaming"
        stroke={color1}
        fill={color1}
      />
      <Legend
        verticalAlign="bottom"
        height={1}
        margin={{ top: 50, right: 0, left: 0, bottom: 0 }}
        iconType="square"
        iconSize={12}
      />
      <Tooltip />
    </AreaChart>
  • AreaChart로 Area와 이 외의 필요한 요소들을 감싼다
  • fillOpacity : 불투명도 지정, 1로하면 완전 불투명
  • type : 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | Function
  • dataKey : 보여줄 값 지정

StackedBarChart

<BarChart data={data} width={width} height={height} margin={margin}>
      <CartesianGrid strokeDasharray="3 3" /
      <XAxis
        interval={0}
        tickMargin={10}
        style={{ fontSize: "13px" }}
        dataKey={getXAxisData}
      />
      <YAxis
        style={{ fontSize: "13px" }}
      />
      <Tooltip />
<Bar stackId="numbers" dataKey="num1" fill="#3597FF" maxBarSize={30}>
          <LabelList
            position="inside"
            dataKey="num1"
            style={{ fontSize: "13px" }}
            stroke="#3d3d3d"
          />
      </Bar>
      <Bar stackId="numbers" dataKey="num2" fill="#c2e5ef" maxBarSize={30}>
          <LabelList
            position="inside"
            dataKey="num2"
            style={{ fontSize: "13px" }}
            stroke="#3d3d3d"
          />
      </Bar>
      <Bar stackId="numbers" dataKey="num3" fill="#a4de6c" maxBarSize={30}>
          <LabelList
            position="top"
            dataKey="num3"
            style={{ fontSize: "13px" }}
            stroke="#3d3d3d"
          />
      </Bar>
    </BarChart>
  • BarChart안에 Bar요소를 넣고 각각의 Bar에 stackId를 지정하면 stacked로 만들 수 있다
  • LabelList : 표 위에 어떤값인지 고정적으로 보여주기 위한 속성,
    • position, dataKey, style 등등 커스터마이징 가능

DonutChart

<PieChart width={width} height={height} margin={margin}>
      <Legend
        iconType="square"
        iconSize={12}
        layout="vertical"
        verticalAlign="middle"
        wrapperStyle={{ marginLeft: "15px" }}
      />
      <Pie
        data={data}
        dataKey="num1"
        nameKey="numbers"
        cx="50%"
        cy="50%"
        innerRadius={60}
        outerRadius={80}
      >
        {data &&
          Object.values(data).map((d, idx) => (
            <Cell key={`cell-${idx}`} fill={colors[idx]} />
          ))}
        <LabelList
          position="inside"
          dataKey={getNumbers}
          stroke="#3d3d3d"
        />
      </Pie>
      <Tooltip />
    </PieChart>
  • PieChart를 이용해 DonutChart를 만들 수 있다
  • Pie 컴포넌트의 outerRadius - innerRadius 만큼이 도넛의 두께다
  • cx, cy : x좌표, y좌표 , default가 50%
  • nameKey : 각 섹터의 이름
  • Cell
{data &&
          Object.values(data).map((d, idx) => (
            <Cell key={`cell-${idx}`} fill={colors[idx]} />
          ))}
  • colors배열을 미리 만들어둔다음, data를 순회하면서 각각의 cell 마다 다른 색을 지정할 수 있다

LineChart

<LineChart margin={margin} width={width} height={height} data={data}>
      <XAxis dataKey="date" style={{ fontSize: "13px" }} />
      <YAxis dataKey="number" style={{ fontSize: "13px" }} />
      <Tooltip formatter={(value, name, props) => [value, "number"]} />
      <Legend
        verticalAlign="bottom"
        height={1}
        margin={{ top: 50, right: 0, left: 0, bottom: 0 }}
        iconType="square"
        iconSize={12}
      />
      <Line type="linear" dataKey="num1" stroke={color1} dot={false} />
        <Line
          type="linear"
          dataKey="num2"
          stroke={color2}
          dot={false}
        />
        <Line
          type="linear"
          dataKey="num3"
          stroke={color3}
          dot={false}
        />
      )}
    </LineChart>


후기

Recharts 라이브러리를 사용하니 굉장히 편하게 차트를 구현할 수 있었다. 특히 ResponsiveContainer를 통해 반응형으로도 쉽게 구현할 수 있고 Tooltip이나 Legend도 여러 차트에서 동일한 방법으로 쓰이기 때문에 한 번 익혀두면 편해서 차트가 필요할 때 자주 이용할 것 같다

0개의 댓글