Python plotly 사용법 - Plotly Express로 선, 막대, 산점도, 히스토그램 그리기

파이썬 plotly로 그래프를 그릴 때는 Plotly Express(import plotly.express as px)부터 쓰면 된다. 데이터프레임과 열 이름을 넘기면 px.line(), px.bar(), px.scatter(), px.histogram()이 한 줄로 확대, 이동, 마우스 오버가 되는 그래프를 만든다. 저장은 fig.write_html()로 HTML, fig.write_image()로 PNG를 만든다. 예전에 플로틀리 기본 사용법과 산점도 그리기를 다뤘는데, 이 글은 지금 버전 기준으로 자주 쓰는 것만 다시 정리한다.

이 글의 코드는 Python 3.12, plotly 7.2.0, kaleido 1.5.2, pandas 2.2에서 실행해 확인했고, 코드 아래의 결과는 실제 출력이다. 그림은 각 코드의 write_image()로 저장한 파일이다.

한눈에 보기

그래프 함수 핵심 인자
선 px.line(df, x, y, color) markers=True
막대 px.bar(df, x, y, color) barmode="group", text_auto=True
산점도 px.scatter(df, x, y, color, size) log_x=True, hover_name
히스토그램 px.histogram(df, x, color) nbins, barmode="overlay"
제목, 축 이름 title=, labels={"열": "표시 이름"}  
HTML 저장 fig.write_html("a.html") include_plotlyjs="cdn"
PNG 저장 fig.write_image("a.png") kaleido + 크롬 필요

설치

pip install plotly pandas
pip install kaleido   # PNG, PDF로 저장할 때만

예제 데이터

plotly에 들어 있는 px.data.gapminder()를 쓴다. 나라별, 5년 간격의 기대수명, 인구, 1인당 GDP 자료다.

import plotly
import plotly.express as px

print(plotly.__version__)

df = px.data.gapminder()
print(df.shape)
print(df.head(3).to_string())
7.2.0
(1704, 8)
       country continent  year  lifeExp       pop   gdpPercap iso_alpha  iso_num
0  Afghanistan      Asia  1952   28.801   8425333  779.445314       AFG        4
1  Afghanistan      Asia  1957   30.332   9240934  820.853030       AFG        4
2  Afghanistan      Asia  1962   31.997  10267083  853.100710       AFG        4

선 그래프 그리기 (px.line)

한국, 일본, 중국의 기대수명 변화를 그린다. color에 나라 열을 주면 나라마다 선 색이 달라지고 범례가 생긴다.

asia3 = df[df["country"].isin(["Korea, Rep.", "Japan", "China"])]

fig = px.line(
    asia3, x="year", y="lifeExp", color="country", markers=True,
    title="한국, 일본, 중국의 기대수명",
    labels={"year": "연도", "lifeExp": "기대수명(세)", "country": "나라"},
)
fig.update_layout(font_family="NanumGothic", width=900, height=450)
fig.write_image("line.png")

plotly express 선 그래프

labels는 열 이름을 축 제목과 범례 제목에 어떻게 보일지 정한다. 데이터프레임의 열 이름을 바꾸지 않아도 된다. 주피터에서는 fig.show()나 셀 마지막 줄의 fig로 바로 볼 수 있다.

막대 그래프 그리기 (px.bar)

2007년 아시아에서 1인당 GDP가 높은 10개 나라를 그린다. text_auto는 막대 위에 값을 적는다.

top10 = (df[(df["year"] == 2007) & (df["continent"] == "Asia")]
         .nlargest(10, "gdpPercap"))

fig = px.bar(
    top10, x="country", y="gdpPercap", text_auto=",.0f",
    title="2007년 아시아 1인당 GDP 상위 10개국",
    labels={"country": "", "gdpPercap": "1인당 GDP(달러)"},
)
fig.update_layout(font_family="NanumGothic", width=900, height=450)
fig.write_image("bar.png")
print(top10[["country", "gdpPercap"]].round(0).to_string(index=False))
         country  gdpPercap
          Kuwait    47307.0
       Singapore    47143.0
Hong Kong, China    39725.0
           Japan    31656.0
         Bahrain    29796.0
          Taiwan    28718.0
          Israel    25523.0
     Korea, Rep.    23348.0
            Oman    22316.0
    Saudi Arabia    21655.0

plotly express 막대 그래프

그룹 막대와 누적 막대

color를 주면 기본은 누적 막대(barmode="relative")다. 나란히 놓으려면 barmode="group"을 준다.

years = df[df["country"].isin(["Korea, Rep.", "Japan", "China"]) & df["year"].isin([1967, 1987, 2007])]

fig = px.bar(
    years, x="country", y="lifeExp", color=years["year"].astype(str), barmode="group",
    labels={"country": "", "lifeExp": "기대수명(세)", "color": "연도"},
)
fig.update_layout(font_family="NanumGothic", width=900, height=420)
fig.write_image("bar_group.png")

plotly express 그룹 막대 그래프

color에 숫자 열(year)을 그대로 넣으면 연속 색상 막대가 되어 그룹으로 나뉘지 않는다. 그래서 astype(str)로 문자열로 바꿔 넣었다.

산점도 그리기 (px.scatter)

2007년 나라별 1인당 GDP와 기대수명의 관계다. 대륙별로 색을 나누고, 점 크기는 인구로 한다. GDP는 나라 간 차이가 커서 log_x=True로 로그 축을 쓴다.

d2007 = df[df["year"] == 2007]

fig = px.scatter(
    d2007, x="gdpPercap", y="lifeExp", color="continent", size="pop",
    hover_name="country", log_x=True, size_max=45,
    title="2007년 1인당 GDP와 기대수명",
    labels={"gdpPercap": "1인당 GDP(달러, 로그 축)", "lifeExp": "기대수명(세)", "continent": "대륙"},
)
fig.update_layout(font_family="NanumGothic", width=900, height=500)
fig.write_image("scatter.png")

plotly express 산점도

hover_name은 마우스를 올렸을 때 맨 위에 굵게 나올 값이다. HTML로 저장해서 보면 점마다 나라 이름이 뜬다. 산점도를 더 자세히 꾸미는 방법은 Plotly 산점도 그리기 02에 있다.

히스토그램 그리기 (px.histogram)

값의 분포를 볼 때 쓴다. px.data.tips()(식당 계산서 자료)의 금액 분포를 점심과 저녁으로 나눠 겹쳐 본다.

tips = px.data.tips()

fig = px.histogram(
    tips, x="total_bill", color="time", nbins=30, barmode="overlay", opacity=0.6,
    title="계산 금액 분포",
    labels={"total_bill": "계산 금액(달러)", "time": "시간대"},
)
fig.update_layout(font_family="NanumGothic", width=900, height=420, yaxis_title="건수")
fig.write_image("hist.png")
print(tips.groupby("time", observed=True)["total_bill"].describe().round(1).to_string())
        count  mean  std  min   25%   50%   75%   max
time
Dinner  176.0  20.8  9.1  3.1  14.4  18.4  25.3  50.8
Lunch    68.0  17.2  7.7  7.5  12.2  16.0  19.5  43.1

plotly express 히스토그램

nbins는 막대 개수다. histnorm="percent"를 주면 건수 대신 비율로 그린다.

색 직접 정하기

color_discrete_sequence는 색 순서를, color_discrete_map은 값마다 색을 정한다.

fig = px.line(
    asia3, x="year", y="lifeExp", color="country",
    color_discrete_map={"Korea, Rep.": "#1f4e79", "Japan": "#c00000", "China": "#999999"},
)
print([(t.name, t.line.color) for t in fig.data])
[('China', '#999999'), ('Japan', '#c00000'), ('Korea, Rep.', '#1f4e79')]

한글 글꼴 지정하기

브라우저에서 보는 그래프는 브라우저가 가진 글꼴로 한글을 그리므로 대개 문제가 없다. write_image()로 저장할 때는 저장하는 컴퓨터의 글꼴을 쓴다. 그래서 글꼴을 지정해 두는 편이 안전하다.

fig.update_layout(font_family="NanumGothic")        # 나눔고딕 (리눅스)
fig.update_layout(font_family="Malgun Gothic")      # 맑은 고딕 (윈도우)
fig.update_layout(font_family="AppleGothic")        # 맥

이 글의 그림은 나눔 글꼴이 설치된 리눅스에서 font_family="NanumGothic"으로 저장했고, 위 그림처럼 한글 제목과 축 이름이 제대로 나왔다. 한글 글꼴이 전혀 없는 서버라면 지정과 관계없이 네모로 나오므로 글꼴부터 설치한다(우분투는 sudo apt install fonts-nanum).

HTML로 저장하기 (write_html)

HTML로 저장하면 받는 사람이 파이썬 없이 브라우저에서 확대, 이동, 마우스 오버를 그대로 쓸 수 있다.

import os

fig = px.scatter(d2007, x="gdpPercap", y="lifeExp", color="continent", hover_name="country", log_x=True)

fig.write_html("scatter_full.html")
fig.write_html("scatter_cdn.html", include_plotlyjs="cdn")

for f in ["scatter_full.html", "scatter_cdn.html"]:
    print(f, f"{os.path.getsize(f) / 1024:,.0f} KB")
scatter_full.html 4,717 KB
scatter_cdn.html 14 KB

기본값은 plotly.js 라이브러리 전체를 파일에 넣어서 수 MB가 된다. 대신 인터넷이 없어도 열린다. include_plotlyjs="cdn"은 라이브러리를 인터넷에서 받아 오게 해서 파일이 작다. 사내망처럼 인터넷이 막힌 곳에 보낼 파일은 기본값으로 저장한다.

이미지로 저장하기 (write_image, kaleido)

write_image()는 kaleido 패키지가 크롬을 화면 없이(헤드리스) 띄워 그래프를 그린 뒤 이미지로 찍는 방식이다. kaleido 1.0부터는 크롬이 패키지에 들어 있지 않아서, 컴퓨터에 설치된 크롬이나 크로미움을 찾아 쓴다. 이 글은 크로미움이 설치된 리눅스에서 실행했고 별도 설정 없이 저장됐다.

import time
import kaleido

t0 = time.perf_counter()
fig.write_image("scatter.webp", width=900, height=500)
fig.write_image("scatter_2x.png", width=900, height=500, scale=2)
fig.write_image("scatter.svg")
fig.write_image("scatter.pdf")
print(f"{time.perf_counter() - t0:.1f}초")

for f in ["scatter.webp", "scatter_2x.png", "scatter.svg", "scatter.pdf"]:
    print(f, f"{os.path.getsize(f) / 1024:,.0f} KB")
10.8초
scatter.webp 15 KB
scatter_2x.png 129 KB
scatter.svg 39 KB
scatter.pdf 15 KB

네 파일을 저장하는 데 10초 남짓 걸렸다. 크롬을 띄워 그리는 방식이라 HTML 저장보다 훨씬 느리다. 그림 수십 장을 만들 때는 이 시간을 감안한다.

  • 파일 확장자로 형식이 정해진다. PNG, JPEG, WebP, SVG, PDF를 쓸 수 있다.
  • width, height는 픽셀 크기, scale=2는 같은 배치로 해상도만 두 배로 만든다.
  • 보고서나 PPT에 넣을 그림은 PNG(scale=2), 문서 인쇄용은 SVG나 PDF가 깔끔하다.

크롬이 없는 컴퓨터에서는 다음 중 하나로 받는다.

plotly_get_chrome
import plotly.io as pio
pio.get_chrome()

잘 안 될 때

write_image에서 크롬을 못 찾는다는 오류

kaleido 1.0 이상은 크롬이 필요하다. 위의 plotly_get_chrome으로 받거나 크롬을 설치한다. 예전 글에 나오는 kaleido==0.2.1 고정이나 orca 설정은 지금 plotly에서는 쓰지 않는다.

fig.show()를 했는데 아무것도 안 나온다

주피터가 아닌 일반 스크립트에서는 fig.show()가 기본 브라우저를 연다. 서버처럼 브라우저가 없는 곳이면 write_html()로 저장해서 내려받아 연다. VS Code 노트북에서 빈 칸이 나오면 import plotly.io as pio; pio.renderers.default = "notebook"을 시도한다.

숫자 열인데 색이 그룹으로 안 나뉜다

color에 숫자 열을 주면 연속 색상(그라데이션)이 된다. 그룹으로 나누려면 astype(str)로 문자열로 바꾼다.

선이 지그재그로 엉킨다

px.line()은 데이터 순서대로 점을 잇는다. x 열 기준으로 df.sort_values("year")처럼 먼저 정렬한다.

Plotly Express와 Graph Objects

  Plotly Express (px) Graph Objects (go)
코드 양 한 줄 길다
입력 데이터프레임 + 열 이름 리스트, 배열을 직접
용도 대부분의 탐색, 보고서 특수한 그래프, 세세한 조정

px로 만든 fig도 go.Figure라서 fig.add_trace(go.Scatter(...))처럼 섞어 쓸 수 있다. Graph Objects로 선 그래프를 그리는 예는 Plotly 선 그래프 그리기에, 처음 plotly를 다룬 글은 플로틀리 기본 사용법에 있다.

자주 묻는 질문

Plotly Express는 plotly와 무엇이 다른가?

Plotly Express(plotly.express, 보통 px)는 plotly에 들어 있는 간편 함수 모음이다. 데이터프레임과 열 이름만 넘기면 px.line(df, x="year", y="value")처럼 한 줄로 그래프가 나온다. 세밀한 조정은 결과로 받은 fig에 update_layout() 등으로 한다.

plotly 그래프를 이미지(PNG)로 저장하려면?

pip install kaleido 후 fig.write_image("chart.png")를 쓴다. kaleido 1.0부터는 크롬이 들어 있지 않아서 컴퓨터에 크롬이나 크로미움이 있어야 하고, 없으면 plotly_get_chrome 명령으로 받는다.

plotly 그래프를 HTML 파일로 저장하려면?

fig.write_html("chart.html")을 쓴다. 기본은 plotly.js 전체가 파일에 들어가 수 MB가 되고, include_plotlyjs="cdn"을 주면 수 KB로 줄어드는 대신 열 때 인터넷이 필요하다.

plotly에서 한글이 깨지면 어떻게 하나?

브라우저에서 보는 그래프는 보통 깨지지 않는다. write_image로 저장할 때 깨지면 그 컴퓨터에 한글 글꼴이 없는 것이니 나눔고딕 등을 설치하고 fig.update_layout(font_family="NanumGothic")으로 지정한다.

plotly 그래프 색을 그룹별로 나누려면?

color="열 이름"을 주면 그 열의 값마다 색이 달라지고 범례가 생긴다. 색 순서는 color_discrete_sequence, 값별 색은 color_discrete_map으로 정한다.

참고한 문서

태그:

카테고리:

업데이트:

댓글남기기