Plotly line, shape 그리기

Plotly line, shape 그리기

Data Visualization
Plotly line, shape를 그리는 방법에 대해서 정리합니다.
Author

gabriel yang

Published

October 8, 2023

Plotly line, shape 그리기

Ploty로 line과 shape를 그리는 방법을 정리합니다.

Line 그리는 방법

add_shape함수로 line을 그리는 코드입니다.

import plotly.graph_objects as go

fig = go.Figure()

# Create scatter trace of text labels
fig.add_trace(go.Scatter(
    x=[6, 6, 6],
    y=[1, 3, 5],
    text=["Line",
          "Dashed Line",
          "Dotted Line"],
    mode="text",
))

# Add shapes
fig.add_shape(type="line",
    x0=1, y0=1, x1=5, y1=1,
    line=dict(color="RoyalBlue",width=3)
)

fig.add_shape(type="line",
    x0=1, y0=3, x1=5, y1=3,
    line=dict(
        color="LightSeaGreen",
        width=4,
        dash="dashdot",
    )
)

fig.add_shape(type="line",
    x0=1, y0=5, x1=5, y1=5,
    line=dict(
        color="MediumPurple",
        width=4,
        dash="dot",
    )
)

# Set axes ranges
fig.update_xaxes(range=[0, 8])
fig.update_yaxes(range=[0, 6])

fig.show()

line은 add_shape함수를 사용합니다. 라인의 스타일은 line변수에 딕셔너리 형식으로 정보를 전달합니다. 딕셔너리의 dash는 라인의 형태를 결정하고 dashdot, dot, line으로 설정할 수 있습니다.

직사각형을 그리는 방법

add_shape함수로 직사각형을 그리는 코드입니다.

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[1.5, 4.5],
    y=[0.75, 0.75],
    text=["Unfilled Rectangle", "Filled Rectangle"],
    mode="text",
))

# Set axes properties
fig.update_xaxes(range=[0, 7], showgrid=False)
fig.update_yaxes(range=[0, 3.5])

# Add shapes
fig.add_shape(type="rect",
    x0=1, y0=1, x1=2, y1=3,
    line=dict(color="RoyalBlue"),
)
fig.add_shape(type="rect",
    x0=3, y0=1, x1=6, y1=2,
    line=dict(
        color="RoyalBlue",
        width=2,
    ),
    fillcolor="LightSkyBlue",
)
fig.update_shapes(dict(xref='x', yref='y'))
fig.show()

이번엔 add_shape함수에 type으로 전달하는 정보를 rect로 전달해서 직사각형을 만들었습니다. 내부를 색으로 채울때는 fillcolor를 사용했습니다.

투명도 조절하기

차트에 라인을 이용하여 원하는 위치를 지정하는 경우 투명도를 조정해서 차트의 정보를 유지하면 라인을 그릴 수 있습니다.

import plotly.graph_objects as go

fig = go.Figure()

fig.add_shape(type="line",
    x0=1, y0=1, x1=5, y1=1,
    opacity=0.5,
    line=dict(
        color="MediumPurple",
        width=4,
        dash="dot",
    )
)

fig.add_shape(type="line",
    x0=1, y0=2, x1=5, y1=2,
    opacity=0.7,
    line=dict(
        color="MediumPurple",
        width=4,
        dash="dot",
    )
)

# Set axes ranges
fig.update_xaxes(range=[0, 6])
fig.update_yaxes(range=[0, 3])

fig.show()

add_shape함수에 opacity를 추가로 전달합니다. opacity가 1인 경우 투명도가 없이 표시되며 opacity가 0인 경우 완전히 투명합니다.