In [1]:
from IPython.core.display import display, HTML
display(HTML("<style> .container{width:90% !important;}</style>"))
In [2]:
# !pip install plotly
import plotly.graph_objects as go
import plotly.offline as pyo # jupyter notebook에서 보여지도록 설정하는 부분
pyo.init_notebook_mode()
plotly.graph_objects 로 시각화 하는 패턴¶
- fig = go.Figure()로 기본 객체 만들기
- fig.add_trace()에 그래프 객체go.Scatter()를 추가 # go.Scatter는 선그래프
- fig.update_layout()으로 layout 업데이트 필요시 업데이트
- fig.update_annotation()으로 annotation 필요시 업데이트
- 데이터는 사전 형태로 넣는것이 가장 쉬움 참조 : https://plotly.com/python/reference
- fig.show()로 객체에 만들어둔 그래프 보여주기
plotly.grahp_ojbect로 line 그래프 그리기¶
In [3]:
import pandas as pd
import numpy as np
import plotly.graph_objects as go
# DataFrame 생성
df = pd.DataFrame(np.random.rand(10,2), columns = ['A', 'B'])
df.head()
# fig 객체 생성
fig = go.Figure()
fig.add_trace(
go.Scatter(
x = df.index, y = df['A'], name = 'A'
)
)
# 한 fig 객체에 두개의 그래프를 넣고 싶으면, fig.add_trace()에 go.scatter를 두번 추가
fig.add_trace(
go.Scatter(
x = df.index, y = df['B'], name = 'B', mode = 'lines + markers',
text = df.index, textposition = 'top center'
)
)
fig.update_layout(
{
"title" : { # graph의 Title
"text" : "Graph with go.Scatter",
"font" : {
"size" : 15
}
},
"showlegend" : True, # 범례 유무
"xaxis" :{ # x 축 Title
"title" : "random number"
},
"yaxis": { # y 축 Title
"title" : "A"
}
}
)
plotly.grahp_ojbect로 bar + scatter 혼합 그래프 그리기¶
In [4]:
import pandas as pd
import numpy as np
import plotly.graph_objects as go
# DataFrame 생성
df = pd.DataFrame(np.random.rand(10,2), columns = ['A', 'B'])
df.head()
# fig 객체 생성
fig = go.Figure()
fig.add_trace(
go.Bar(
x = df.index, y = df['A'], name = 'A', text = df['A'], textposition = 'auto',
texttemplate = '%{y:.2f}'
# text position = 그래프 내에서 text 어디에 쓸건지?
# text = df['B'] 로 설정하면, B column의 value를 사용
# texttemplate = '%{y:.2f}' 실수형 소수점 둘째자리까지
)
)
# Line 그래프 추가
fig.add_trace(
go.Scatter(
x = df.index, y = df['B'], name = 'B', mode = 'lines + markers',
text = df.index, textposition = 'top center'
)
)
fig.update_layout(
{
"title" : {
"text" : "Graph with <b>go.Bar</b>", # text 시작과 끝에 <b> 넣어서, Boldic 선언가능
"x" : 0.5,
"y" : 0.9,
"font" : {
"size" : 20
}
},
"showlegend" : True,
"xaxis" : {
"title" : "random number",
"showticklabels":True,
"dtick" : 1
},
"yaxis" : {
"title" : "A"
},
"autosize" : False,
"width" : 600,
"height" : 300
}
)
In [ ]:
'데이터분석 > Pandas' 카테고리의 다른 글
[Pandas] 데이터 Feature 파악 기본 (그래프) (0) | 2021.07.23 |
---|---|
[Pandas] plotly 사용해서 시각화 해보기 1 (0) | 2021.07.18 |
[Pandas] 데이터 처리 연습2 결과물 시각화 (0) | 2021.07.17 |
[Pandas] 데이터 처리 연습 2 (0) | 2021.07.17 |
[Pandas] 데이터 처리 연습 (0) | 2021.07.15 |