2025-06-04

장상희·2025년 6월 4일
0

파이썬

목록 보기
29/31

Plotly 범례 지정하기 (Legend)

import plotly.express as px
#express 방식
#데이터 불러오기 
df = px.data.tips()

#데이터 확인
df.head()

#그래프 그리기
fig = px.scatter(df, x="total_bill", y="tip", color="sex")#x축은 total, y축은 tip, 찍히는건 성별로

fig.show()

#graph_object 방식은 직접 성별 데이터를 구분하고 따로따로 구분하고 그래프를 그려줘야합니다

Female = df.loc[df["sex"]=="Female", :]
Female.head()

Male = df.loc[df["sex"]=="Male", :]
Male.head()

#그래프 그리기
import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=Female.total_bill,#x값
    y=Female.tip,#y값
    mode='markers',#그래프 형식
    name="Female"#이름
	#fig.add_trace() 를 통해 Trace를 추가할때 해당 데이터를 범례로 표시할 문구를name=안에 넣어줍니다.
))

fig.add_trace(go.Scatter(
    x=Male.total_bill,
    y=Male.tip,
    mode='markers',
    name="Male"
))

범례 삭제하기

fig.update_layout(showlegend=False)#update해서 비활성화 한다, 다시 보일려면 false에서true로 바꿔준다

범례 위치 지정

fig.update_layout(
            legend__x = (0~1) 사이값
            legend__y = (0~1) 사이값
            legend_xanchor = (`auto","left","center","right")#좌표를 중심으로한 왼쪽 또는 가운데 오른쪽
            legend_yanchor = ("auto","top","middle","bottom")
            })

Plotly 수직선/수평선/사각영역 그리기

수직/수평선 그리기

# 수평선 그리기
fig.add_hline(y= 선의 y 위치,
            line_width= 선 두깨, 
            line_dash=선 스타일, 
            line_color=선 색,
            annotation_text= 주석 입력, 
            annotation_position= 주석 위치,
            annotation_font_size= 주석 폰트 사이즈,
            annotation_font_color=주석 폰트 색,
            annotation_font_family=주석 폰트 서체)

# 수직선 그리기
fig.add_vline(x= 선의 x 위치,
            line_width= 선 두깨, 
            line_dash=선 스타일, 
            line_color=선 색,
            annotation_text= 주석 입력, 
            annotation_position= 주석 위치,
            annotation_font_size= 주석 폰트 사이즈,
            annotation_font_color=주석 폰트 색,
            annotation_font_family=주석 폰트 서체)

둘다 그리기

#데이터 불러오기
df = px.data.iris()

#그래프 그리기
fig = px.scatter(df, x="petal_length", y="petal_width")

# 수평선 추가하기
fig.add_hline(y=0.9,line_width=3, line_dash="dash",
              line_color="green",
              annotation_text="수평선", 
              annotation_position="bottom right",
              annotation_font_size=20,
              annotation_font_color="green",
              annotation_font_family="Times New Roman")

# 수직선 추가하기
fig.add_vline(x=3,line_width=3, line_dash="dash",
              line_color="red",
              annotation_text="수직선", 
              annotation_position="top left",
              annotation_font_size=20,
              annotation_font_color="red",
              annotation_font_family="Times New Roman")

사각 영역 그리기

# 수평 사각영역 그리기
fig.add_vrect(x0= 영역시작 x좌표, x1=영역끝 x좌표, ,line_width= 테두리 선 두깨, line_dash=테두리 선 스타일, line_color=테두리 선 색, fillcolor=영역 색, opacity=영역 투명도)

# 수직영역 그리기
fig.add_hrect(x0= 영역시작 x좌표, x1=영역끝 x좌표, ,line_width= 테두리 선 두깨, line_dash=테두리 선 스타일, line_color=테두리 선 색, fillcolor=영역 색, opacity=영역 투명도)
import plotly.express as px

#데이터 불러오기
df = px.data.iris()

#그래프 그리기
fig = px.scatter(df, x="petal_length", y="petal_width")

# 수직 사각 영 추가하기
fig.add_vrect(x0=3, x1=5, line_width=0, fillcolor="green", opacity=0.2,
#opacity= 불투명도, line_width 테두리 두께
              annotation_text="수직 영역", 
              annotation_position="bottom right",
              annotation_font_size=20,
              annotation_font_color="green",
              annotation_font_family="Times New Roman")

# 수평 사각 영역 추가하기
fig.add_hrect(y0=0.9, y1=1.5, line_width=0, fillcolor="red", opacity=0.2,
              annotation_text="수 영역", 
              annotation_position="top left",
              annotation_font_size=20,
              annotation_font_color="red",
              annotation_font_family="Times New Roman")

fig.show()

Plotly 다양한 도형 그리기

fig.add_shape(type="rect",
            x0= 왼쪽 아래 x좌표, y0= 왼쪽 아랫 y좌표,
            x1= 오늘쪽 위 x좌표, y1= 오른쪽 위 y좌표,
            line_width= 테두리선 두깨, 
            line_dash= 테두리선 스타일, 
            line_color= 테두리선 색,
            fillcolor= 안에 채우는 색,
            opacity = 투명도)

사각형

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",
))

# 축 설정 변경
fig.update_xaxes(range=[0, 7], showgrid=False)
fig.update_yaxes(range=[0, 3.5])

# 사각형 그리기

fig.add_shape(type="rect",#사각형 타입
    x0=1, y0=1, x1=2, y1=3,
    line_color="RoyalBlue")

fig.add_shape(type="rect",
    x0=3, y0=1, x1=6, y1=2,
    line_color="RoyalBlue",
    line_width=2,#테두리 두계
    fillcolor="LightSkyBlue",
    opacity=0.5)

fig.show()

원 그리기

fig.add_shape(type="circle",
            x0= 원점 x좌표, y0= 원 y좌표,
            x1= 가로 반지름, y1= 세로 반지름,
            line_width= 테두리선 두깨, 
            line_dash= 테두리선 스타일, 
            line_color= 테두리선 색,
            fillcolor= 안에 채우는 색,
            opacity = 투명도)
import plotly.graph_objects as go

#그래프 생성
fig = go.Figure()

# 텍스트 추가
fig.add_trace(go.Scatter(
    x=[1.5, 3.5],
    y=[0.75, 2.5],
    text=["Unfilled Circle",
          "Filled Circle"],
    mode="text",
))

# 축 설정 변경
fig.update_xaxes(range=[0, 4.5], zeroline=False)
fig.update_yaxes(range=[0, 4.5])

# 원 그리기

fig.add_shape(type="circle",
    xref="x", yref="y",
    x0=1, y0=1, x1=3, y1=3,
    line_color="LightSeaGreen",)

fig.add_shape(type="circle",
    xref="x", yref="y",
    fillcolor="PaleTurquoise",
    x0=3, y0=3, x1=4, y1=4,
    line_color="LightSeaGreen",)

fig.show()

선 그리기

fig.add_shape(type="line",
            x0= 선 시작 x좌표, y0= 선 시작 y좌표,
            x1= 선 끝 x좌표, y1= 선 끝 y좌표,
            line_width= 선 두깨, 
            line_dash= 선 스타일, 
            line_color= 선 색,
            opacity = 투명도)
import plotly.graph_objects as go

#그래프 생성
fig = go.Figure()

# 텍스트 추가
fig.add_trace(go.Scatter(
    x=[2, 3.5, 6],
    y=[1, 1.5, 1],
    text=["Vertical Line",
          "Horizontal Dashed Line",
          "Diagonal dotted Line"],mode="text",))

# 축 설정 변경
fig.update_xaxes(range=[0, 7])
fig.update_yaxes(range=[0, 2.5])

# 선 그리기

fig.add_shape(type="line",
    x0=1, y0=0, x1=1, y1=2,
    line_color="RoyalBlue",
    line_width=3)

fig.add_shape(type="line",
    x0=2, y0=2, x1=5, y1=2,
    line_color="LightSeaGreen",
    line_width=4,
    line_dash="dashdot")

fig.add_shape(type="line",
    x0=4, y0=0, x1=6, y1=2,
    line_color="MediumPurple",
    line_width=4,
    line_dash="dot")

fig.show()

다각형 그리기

import plotly.graph_objects as go
# 그래프 생성
fig = go.Figure()

# 삼각형 그리기
fig.add_trace(go.Scatter(x=[5,6,7,5], y=[2,3,2,2], fill="toself"))#채울꺼면 toself 아니면 fill을 안넣음

fig.show()
import plotly.graph_objects as go

fig = go.Figure()

# 육각형
fig.add_trace(go.Scatter(x=[1,1,2,3,4,4,3,2,1], y=[1,2,3,3,2,1,0,0,1], fill="toself"))

# 사각형
fig.add_trace(go.Scatter(x=[5,5,7,7,5], y=[0.5,1.5,1.5,0.5,0.5], fill="toself"))

# 삼각형
fig.add_trace(go.Scatter(x=[5,6,7,5], y=[2,3,2,2], fill="toself"))

fig.show()

Plotly 텍스트/주석 넣기

Annotation 넣기

fig.add_annotation(
            x= x 좌표, y= y 좌표,
            text= 주석 텍스트,
            textangle= 텍스트 각도,
            font_color = 텍스트 색,
            font_family = 텍스트 서체,
            font_size = 텍스트 사이즈,
            arrowhead = 화살표 스타일,
            arrowcolor= 화살표 색,
            arrowside= 화살표 방향,
            arrowsize= 화살표 크기,
            arrowwidth = 화살표 두깨,
            bgcolor=텍스트 백그라운드색,
            bordercolor= 테두리 색,
            borderwidth = 테두리 두깨,
            opacity = 투명도,
            xshift = x축 방향 평행이동,
            yshift = y축 방향 평행이동)
import plotly.graph_objects as go

#그래프 생성
fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[0, 1, 3, 2, 4, 3, 4, 6, 5]
))

fig.add_trace(go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[0, 4, 5, 1, 2, 2, 3, 4, 2]
))

# annotation 추가
fig.add_annotation(x=2, y=5,
            text="Text annotation with arrow",
            showarrow=True,
            arrowhead=1)
fig.add_annotation(x=4, y=4,
            text="Text annotation without arrow",
            showarrow=False,
            yshift=10)

fig.show()

텍스트 넣기

go.Scatter(x=[X좌표 리스트], y=[Y좌표 리스트],text=[텍스트 리스트] mode="text", textposition= 텍스트 위치)
import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[0, 1, 2],
    y=[1, 1, 1],
    mode="text",
    name="아랫줄",
    text=["Text A", "Text B", "Text C"],
    textposition="top center"))

fig.add_trace(go.Scatter(
    x=[0, 1, 2],
    y=[2, 2, 2],
    mode="text",
    name="중간줄",
    text=["Text D", "Text E", "Text F"],
    textposition="bottom center"))

fig.add_trace(go.Scatter(
    x=[0, 1, 2],
    y=[3, 3, 3],
    mode="text",
    name="윗줄",
    text=["Text G", "Text H", "Text I"],
    textposition="bottom center"))

fig.show()
profile
프로그래머 꿈나무

0개의 댓글