[python] ReportLab 차트 생성

ReportLab은 파이썬에서 PDF 및 사용자 정의 문서를 생성하기 위한 강력한 도구입니다. 이번 블로그 포스트에서는 ReportLab을 사용하여 차트를 생성하는 방법을 알아보겠습니다.

1. ReportLab 설치하기

ReportLab을 사용하려면 우선 패키지를 설치해야 합니다. 다음 명령을 사용하여 패키지를 설치합니다.

pip install reportlab

2. 차트 생성하기

ReportLab을 사용하여 차트를 생성하기 위해서는 다음의 단계를 따라야 합니다.

2.1. 필요한 모듈 가져오기

from reportlab.lib import colors
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import HorizontalBarChart
from reportlab.platypus import SimpleDocTemplate

2.2. 데이터 준비하기

data = [
    (10, 'Python'),
    (8, 'Java'),
    (6, 'C++'),
    (4, 'JavaScript'),
    (2, 'Ruby')
]

생성할 차트에 사용할 데이터를 준비합니다.

2.3. 차트 생성하기

drawing = Drawing(400, 200)

chart = HorizontalBarChart()
chart.x = 50
chart.y = 50
chart.width = 300
chart.height = 100

chart.data = [d[0] for d in data]
chart.categories = [d[1] for d in data]

chart.bars[0].fillColor = colors.blue
chart.bars[1].fillColor = colors.red
chart.bars[2].fillColor = colors.green
chart.bars[3].fillColor = colors.yellow
chart.bars[4].fillColor = colors.orange

drawing.add(chart)

차트 객체를 생성하고, 데이터와 스타일을 설정합니다.

2.4. PDF 문서 생성하기

doc = SimpleDocTemplate("chart.pdf")
doc.build([drawing])

PDF 문서를 생성하고, 차트를 문서에 추가합니다.

3. 실행하기

위의 코드를 실행하면 chart.pdf라는 이름의 PDF 파일이 생성됩니다. 파일을 열어서 생성된 차트를 확인할 수 있습니다.

결론

ReportLab을 사용하여 파이썬에서 차트를 생성하는 방법을 알아봤습니다. ReportLab은 강력한 기능을 제공하며, 다양한 유형의 차트를 생성할 수 있습니다. 차트를 생성하고 문서를 생성하는 과정을 숙지하면 보다 다양하고 실용적인 문서를 만들 수 있을 것입니다.

참고 자료