[D3.js version7 & React] 라인 차트 만들기 1

종인·2023년 8월 24일
0

목차

  1. 기본 세팅
  2. svg 그리기
  3. scale 설정하기
  4. axis 그리기
  5. line 그리기
  6. tooltip 기능 추가하기

1. 기본 세팅

데이터 소개

// data.csv

date,close
2007-04-23,93.24
2007-04-24,95.35
2007-04-25,98.84
...
2012-04-26,603
2012-04-29,583.98
2012-05-01,582.13

라인 차트를 그릴 때 사용할 데이터는 2007년도 부터 2012년도 까지 date(날짜)와 close(종가)로 이루어진 데이터이다.

시작 코드

// index

const LineChartUI = () => {
  const ref = useRef(null);
  
  const draw = async () => {
    // 데이터
    const dataset = await d3.csv("/data.csv");

	// x, y의 접근자
    const xAccessor = (d) => d.date;
    const yAccessor = (d) => d.close;

    // svg를 그릴 때 사용할 차원 정보
    let dimensions = {
      width: 1000,
      height: 500,
      margins: 50,
    };

	// 차트가 그려질 컨테이너의 차원 정보
    dimensions.ctrWidth = dimensions.width - dimensions.margins * 2;
    dimensions.ctrHeight = dimensions.height - dimensions.margins * 2;
  };

  useEffect(() => {
    select(ref.current)?.select("svg").remove();

    draw();
  }, []);

  return (
    <>
      <LineChart ref={ref}>
        <Tooltip id="tooltip">
          <Price className="price"></Price>
          <Date className="date"></Date>
        </Tooltip>
      </LineChart>
    </>
  );
};

export default LineChartUI;
// styles

import styled from "@emotion/styled";

export const Tooltip = styled.div`
  border: 1px solid #ccc;
  position: absolute;
  padding: 10px;
  background-color: #fff;
  display: none;
  pointer-events: none;
`;

export const Price = styled.div`
  font-weight: bold;
`;

export const Date = styled.div``;

export const LineChart = styled.div`
  margin: 25px auto;
  width: 1000px;
  position: relative;
  background-color: #f7f7f7;
`;

버전 정보

"d3": "^7.8.5",
"react": "17.0.2",
"react-dom": "17.0.2",
"@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0",

svg 그리기

profile
어쩌면 오늘 하루는

0개의 댓글