Plotly 마커 모양 변경하기

Plotly 마커 모양 변경하기

Data Visualization
Plotly 마커 모양을 변경하는 방법을 정리합니다.
Author

gabriel yang

Published

September 28, 2023

Plotly 마커 모양 변경하기

Plotly 차트의 마커 모양을 변경하면 집중이 필요한 데이터를 강조할 수 있습니다. 마커의 색과 모양을 변경하는 방법을 정리합니다.

import plotly.express as px

df = px.data.iris()
df.sample(3)
sepal_length sepal_width petal_length petal_width species species_id
77 6.7 3.0 5.0 1.7 versicolor 2
119 6.0 2.2 5.0 1.5 virginica 3
140 6.7 3.1 5.6 2.4 virginica 3

연습을 위해 사용할 데이터프레임을 알아봅니다. 붓꽃(Irises)의 종류를 구분하기 위해 사용되는 iris데이터입니다. 케글 데이터 셋에서 데이터셋의 자세한 내용을 확인할 수 있습니다.

df['species'].unique()
array(['setosa', 'versicolor', 'virginica'], dtype=object)

데이터셋의 3가지 붓꽃 종의 이름을 확인하기 위해서 species 컬럼의 중복을 제외한 unique한 데이터를 확인합니다. setosa, versicolor, virginica의 3개의 붓꽃 종이 있음을 알 수 있습니다.

Scatter Plot으로 그리기

scatter plot을 이용해서 데이터를 시각화합니다. x축과 y축에는 각각 sepal_widthsepal_length를 사용합니다.

fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")

fig.show()

colorspecies컬럼 정보를 전달해서 3개의 종의 데이터가 서로다른 색으로 시각화됐습니다.

마커 변경하기

update_tracesmarker에 마커 모양을 위한 딕셔너리 정보를 전달하여 마커의 모양을 변경합니다.

fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")

fig.update_traces(marker=dict(size=12,
                              line=dict(width=2,
                                        color='DarkSlateGrey')),
                  selector=dict(mode='markers'))
fig.show()

마커의 size는 12이고 마커의 외곽선은 width는 2, 색은 DarkSlateGrey로 수정했습니다. selector에는 modemarkers로 전달해서 style이 적용될 영역을 선택합니다.

여러개의 그래프에 마커변경하기

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(
  go.Scatter(
    mode = 'markers', # line, markers, text
    x = [1,2,3],
    y = [10,20,30],
    marker=dict(
        color='LightSkyBlue',
        size=20,
        line=dict(
            color='MediumPurple',
            width=2)
      ),
    name= 'Marker Style 1'
  )
)

fig.add_trace(
  go.Scatter(
    mode = 'lines',
    x = [1,2,3],
    y = [30,20,10],
    line=dict(
      color='Blue',
      width=5
    ),
    name= 'Marker Style 2'
  )
)

fig.add_trace(
  go.Scatter(
    mode = 'markers',
    x = [1,2,3],
    y = [50,50,50],
    marker=dict(
        color='Orange',
        size=20,
        line=dict(
            color='Blue',
            width=2)
      ),
    name= 'Marker Style 3'
  )
)



fig.show()

차트에 여러 개의 그래프를 추가하기 위해서 add_trace()를 사용했습니다. 각 그래프의 마커 스타일은 go.Scatter함수 mode에 전달한 정보에 따라 다릅니다.

markers모드인 경우 마커의 sytle을 marker로 전달한 정보로 변경합니다. line모드의 경우 line옵션에 style정보를 전달합니다.