[Recharts] 리차트(recharts) 가로 막대그래프 구현

2022. 12. 19. 15:28
반응형

 

막대그래프를 가로로 보여줘야 하는 상황!

 

 <ResponsiveContainer width="100%" height="100%">
          <BarChart
            layout="vertical"
            data={subjects}
            margin={{
              top: 5,
              right: 30,
              left: 20,
              bottom: 5,
            }}
          >
            <XAxis type="number" />
            <YAxis dataKey="label" type="category" domain={[0, 50]} tick={{ fontSize: '0.8rem' }} />
            <Bar dataKey="me" label={renderLabel}>
              {subjects.map((entry, index) => (
                <Cell key={`cell-${entry.label}`} fill={firstColors[index]} name="나" />
              ))}
            </Bar>

            <Bar dataKey="gradeAvg" label={renderLabel}>
              {subjects.map((entry, index) => (
                <Cell
                  key={`cell-${entry.label}`}
                  name="전체평균"
                  fill={firstColors[index]}
                  opacity={0.3}
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>

 

1. Barchart 안에 layout="vertical" 넣어주기

2. YAxis 안에 type="category" 넣어주기(이거 안해주면 안나옴..! 여기서 헤맸음)

 

 

***

데이터가 늘어남에 따라 무지개색 (ex 정보-빨강, 한문-주황, 수학-노랑...) 으로 막대들을 렌더링해야 해서,

<Bar> 안에 <Cell>을 mapping 해주는 식으로 구현했다.

(colors는 노가다로 색상값 array를 따로 만들어줌...)

 

그럴 필요 없다면 Cell 컴포넌트 사용할 필요 없음!

 

 

***

만약 그래프가 왼쪽 여백 없이(ex 캡쳐에서 '정보', '한문'이라 나온 부분) 처음부터 나오길 원한다면,

<YAxis width={0}> 넣어주면 됨!

 

 

 

 

반응형

BELATED ARTICLES

more