python-pptx로 파워포인트에 차트 넣기 - 막대, 꺾은선, 원 그래프
python-pptx 파이썬으로 파워포인트 이용하기에서는 슬라이드를 만들고 글, 그림, 도형, 표를 넣는 방법을 다뤘다. 이번에는 보고서에서 빠지지 않는 차트를 넣어 본다. python-pptx로 넣은 차트는 그림이 아니라 파워포인트에서 숫자와 색을 고칠 수 있는 진짜 차트다.
이 글의 코드는 python-pptx 1.0.2에서 실행해 확인했고, 코드 아래의 결과는 실제 출력이다. 슬라이드 그림은 만들어진 파일을 LibreOffice로 열어 저장한 것이라 파워포인트에서 볼 때와 글꼴이 조금 다를 수 있다.
설치
pip install python-pptx
세로 막대 차트 넣기
차트를 넣는 순서는 세 단계다.
CategoryChartData에 범주(가로축 이름)와 계열(숫자 묶음)을 담는다.slide.shapes.add_chart()에 차트 종류, 위치, 크기, 데이터를 준다.- 돌려받은 객체의
.chart로 범례나 색을 다듬는다.
from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches, Pt
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5]) # 제목만 있는 슬라이드
slide.shapes.title.text = "분기별 매출"
chart_data = CategoryChartData()
chart_data.categories = ["1분기", "2분기", "3분기", "4분기"]
chart_data.add_series("2025년", (120, 135, 128, 150))
chart_data.add_series("2026년", (132, 141, 156, 171))
x, y, width, height = Inches(0.5), Inches(1.5), Inches(9), Inches(5.5)
frame = slide.shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, width, height, chart_data)
chart = frame.chart
print(chart.chart_type)
print([series.name for series in chart.plots[0].series])
COLUMN_CLUSTERED (51)
['2025년', '2026년']
add_chart()가 돌려주는 것은 차트를 담은 틀이고, 실제 차트는 그 안의 .chart에 있다. 기본 슬라이드는 가로 10인치, 세로 7.5인치이므로 위치와 크기는 그 안에서 잡는다.
범례, 데이터 레이블, 색 다듬기
아무것도 손대지 않은 차트는 범례도 숫자도 없다. 보고서에 쓸 만하게 다듬어 보자.
from pptx.dml.color import RGBColor
from pptx.enum.chart import XL_LEGEND_POSITION, XL_LABEL_POSITION
# 차트 전체 글꼴
chart.font.size = Pt(14)
chart.font.name = "맑은 고딕"
# 범례를 아래쪽에
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.BOTTOM
chart.legend.include_in_layout = False
# 막대 위에 숫자 표시
plot = chart.plots[0]
plot.has_data_labels = True
labels = plot.data_labels
labels.number_format = "#,##0"
labels.number_format_is_linked = False
labels.position = XL_LABEL_POSITION.OUTSIDE_END
labels.font.size = Pt(12)
# 계열 색과 막대 간격
for series, color in zip(plot.series, ("9DB7D5", "1F4E78")):
series.format.fill.solid()
series.format.fill.fore_color.rgb = RGBColor.from_string(color)
plot.gap_width = 80
# 세로축 최댓값과 차트 제목
chart.value_axis.maximum_scale = 200
chart.has_title = True
chart.chart_title.text_frame.text = "단위: 억 원"

자주 헷갈리는 부분만 짚어 둔다.
number_format을 바꿀 때는number_format_is_linked = False를 함께 줘야 적용된다.include_in_layout = False는 범례가 그래프 영역을 밀어내지 않고 바깥에 자리 잡게 한다.gap_width는 막대 묶음 사이의 간격이다. 숫자가 작을수록 막대가 굵어진다.
꺾은선 차트
차트 종류만 LINE_MARKERS로 바꾸면 된다. 선 색과 굵기는 계열의 format.line에서 정한다.
slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = "월별 방문자"
chart_data = CategoryChartData()
chart_data.categories = [f"{month}월" for month in range(1, 13)]
chart_data.add_series("방문자", (2100, 2300, 2250, 2600, 2900, 3100, 3050, 3300, 3600, 3550, 3900, 4200))
chart = slide.shapes.add_chart(XL_CHART_TYPE.LINE_MARKERS, x, y, width, height, chart_data).chart
chart.has_legend = False
chart.has_title = False # 계열이 하나면 계열 이름이 제목으로 자동으로 붙는다
chart.font.size = Pt(12)
line = chart.plots[0].series[0]
line.smooth = False
line.format.line.color.rgb = RGBColor(0x0B, 0x64, 0x77)
line.format.line.width = Pt(3)

원 차트
원 차트는 계열을 하나만 넣는다. 값을 0.62처럼 비율로 넣고 레이블 형식을 0%로 주면 퍼센트로 표시된다.
slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = "유입 경로"
chart_data = CategoryChartData()
chart_data.categories = ["검색", "직접 방문", "소셜", "기타"]
chart_data.add_series("비율", (0.62, 0.21, 0.11, 0.06))
chart = slide.shapes.add_chart(XL_CHART_TYPE.PIE, Inches(1.5), y, Inches(7), height, chart_data).chart
chart.has_title = False
chart.font.size = Pt(14)
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.RIGHT
chart.legend.include_in_layout = False
plot = chart.plots[0]
plot.has_data_labels = True
plot.data_labels.number_format = "0%"
plot.data_labels.number_format_is_linked = False
plot.data_labels.position = XL_LABEL_POSITION.BEST_FIT

판다스 데이터프레임으로 차트 만들기
실제 업무에서는 숫자가 데이터프레임에 들어 있는 경우가 많다. 범주로 쓸 열과 숫자 열을 꺼내 그대로 넣으면 된다. 이번에는 가로 막대(BAR_CLUSTERED)로 그린다. 가로 막대 차트는 엑셀과 마찬가지로 첫 번째 범주를 맨 아래에 그리므로, 데이터프레임 순서대로 위에서부터 보이게 하려면 reverse_order로 축을 뒤집는다. 축을 뒤집으면 숫자 눈금은 차트 위쪽으로 옮겨 간다.
import pandas as pd
df = pd.DataFrame({
"제품": ["A", "B", "C"],
"상반기": [320, 210, 150],
"하반기": [410, 190, 230],
})
chart_data = CategoryChartData()
chart_data.categories = df["제품"].tolist()
for column in ("상반기", "하반기"):
chart_data.add_series(column, df[column].tolist())
slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = "제품별 판매량"
chart = slide.shapes.add_chart(XL_CHART_TYPE.BAR_CLUSTERED, x, y, width, height, chart_data).chart
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.BOTTOM
chart.legend.include_in_layout = False
# 가로 막대는 첫 범주가 맨 아래에 그려진다. 표와 같은 순서로 위에서부터 보이게 뒤집는다.
chart.category_axis.reverse_order = True
prs.save("chart.pptx")

파일 안의 차트 찾아 읽기
저장한 파일을 다시 열어 어떤 차트가 들어 있는지 확인해 보자. 도형 가운데 has_chart가 참인 것이 차트다.
prs = Presentation("chart.pptx")
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_chart:
chart = shape.chart
print(slide.shapes.title.text, chart.chart_type)
for series in chart.plots[0].series:
print(" ", series.name, list(series.values))
분기별 매출 COLUMN_CLUSTERED (51)
2025년 [120.0, 135.0, 128.0, 150.0]
2026년 [132.0, 141.0, 156.0, 171.0]
월별 방문자 LINE_MARKERS (65)
방문자 [2100.0, 2300.0, 2250.0, 2600.0, 2900.0, 3100.0, 3050.0, 3300.0, 3600.0, 3550.0, 3900.0, 4200.0]
유입 경로 PIE (5)
비율 [0.62, 0.21, 0.11, 0.06]
제품별 판매량 BAR_CLUSTERED (57)
상반기 [320.0, 210.0, 150.0]
하반기 [410.0, 190.0, 230.0]
이미 있는 차트의 숫자만 바꾸기
매달 같은 양식의 보고서를 만든다면 이 기능이 가장 쓸모 있다. 꾸며 둔 양식 파일을 열어 replace_data()로 숫자만 갈아 끼우면, 색과 글꼴 같은 꾸밈은 그대로 남는다.
first_slide = prs.slides[0]
chart = next(shape.chart for shape in first_slide.shapes if shape.has_chart)
new_data = CategoryChartData()
new_data.categories = ["1분기", "2분기", "3분기", "4분기"]
new_data.add_series("2026년", (132, 141, 156, 171))
new_data.add_series("2027년", (150, 163, 170, 188))
chart.replace_data(new_data)
prs.save("chart_updated.pptx")
for series in chart.plots[0].series:
print(series.name, list(series.values))
2026년 [132.0, 141.0, 156.0, 171.0]
2027년 [150.0, 163.0, 170.0, 188.0]
자주 쓰는 차트 종류
| 차트 | XL_CHART_TYPE 값 |
|---|---|
| 묶은 세로 막대 | COLUMN_CLUSTERED |
| 누적 세로 막대 | COLUMN_STACKED |
| 묶은 가로 막대 | BAR_CLUSTERED |
| 꺾은선 | LINE, LINE_MARKERS |
| 원, 도넛 | PIE, DOUGHNUT |
| 영역 | AREA |
| 분산형 | XY_SCATTER (데이터는 XyChartData로 만든다) |
16:9 슬라이드에서 쓸 때
prs.slide_width = Inches(13.333)으로 슬라이드를 16:9로 넓힐 수 있다. 다만 기본 양식의 제목 틀은 4:3일 때의 위치와 크기를 그대로 가지고 있어서 제목이 왼쪽으로 치우쳐 보인다. 16:9로 만들 때는 파워포인트에서 16:9로 저장해 둔 양식 파일을 Presentation("양식.pptx")로 열어 쓰는 편이 깔끔하다.
자주 묻는 질문
python-pptx로 넣은 차트는 그림인가, 파워포인트에서 고칠 수 있는 차트인가?
파워포인트에서 고칠 수 있는 진짜 차트다. 데이터가 파일 안에 엑셀 시트로 함께 들어가므로 파워포인트에서 ‘데이터 편집’으로 숫자를 바꿀 수 있다.
차트 종류는 어떻게 고르나?
add_chart()의 첫 인자로 XL_CHART_TYPE.COLUMN_CLUSTERED(세로 막대), BAR_CLUSTERED(가로 막대), LINE_MARKERS(꺾은선), PIE(원) 같은 값을 준다.
판다스 데이터프레임으로 차트를 만들 수 있나?
된다. 범주로 쓸 열을 chart_data.categories에, 숫자 열을 chart_data.add_series(이름, 값목록)에 넣으면 된다. 값은 tolist()로 파이썬 리스트로 바꿔 넣는다.
매달 같은 양식의 보고서에서 숫자만 바꾸려면?
양식 파일을 열어 차트를 찾은 뒤 chart.replace_data(새_데이터)를 부른다. 색이나 글꼴 같은 꾸밈은 그대로 두고 숫자만 바뀐다.
matplotlib 그래프를 넣는 것과 무엇이 다른가?
matplotlib 그래프는 그림 파일로 저장해 add_picture()로 넣는 것이라 파워포인트에서 고칠 수 없다. 받는 사람이 색이나 숫자를 손봐야 한다면 차트로 넣는 편이 낫다.
참고한 문서
- https://python-pptx.readthedocs.io/en/latest/user/charts.html
- https://python-pptx.readthedocs.io/en/latest/api/chart.html
댓글남기기