'setting the global theme with offline = True'에 해당되는 글 1건

  1. 2019.02.02 [Python] Plotly 를 오프라인에서 Jupyter Notebook에서 사용하여 시각화하기 2

Plotly는 퀘벡 몬트리올에 본사가 있는 온라인 데이터 분석과 시각화 툴을 개발하는 테크 회사의 이름이기도 하구요, 분석/ 시각화 라이브러리의 이름이기도 합니다. Plotly 툴은 Python과 Django 프레임워크를 사용했고, 프런트엔드는 JavaScript, 시각화 라이브러리는 D3.js, HTML, CSS를 사용하여 만들어졌습니다. ((https://plot.ly/)


Plotly는 그래프가 (다른 시각화 라이브러리 대비) 아름답구요, 웹 상에 publish 하여 interactive visualization 용도로 사용하는데 매우 훌륭합니다. 


특히 Plotly Dash는 웹 기반 분석 애플리케이션 개발을 위한 오픈소스 파이썬 프레임워크인데요, JavaScript 를 안쓰고도 Python 코드 몇 백 줄로 Data Scientist가 디자이너 도움없이 매우 아름답고 완성도 높은 interactive analytics web application을 짧은 시간안에 만들 수 있어서 매우 매력적입니다. (for more information: https://dash.plot.ly/)


이번 포스팅에서는 웹에 publish 하는 것이 아니고, 로컬 컴퓨터에서 Jupyter Notebook에 offline으로 Plotly 라이브러리를 사용해서 시각화를 하는 방법을 소개하고자 합니다. 



  1. Plotly python package 설치(installation) 및 업그레이드(upgrade)


Plotly를 처음 사용하는 것이면 프롬프트 창에서 먼저 설치를 해야 합니다. 

 

$ pip install plotly




이미 Plotly를 설치해서 사용하고 있는 사용자라면, Plotly가 자주 버전 업그레이드를 하므로 아래처럼 Plotly를 업그레이트를 먼저 해주는 것을 추천합니다. 



$ pip install plotly --upgrade

 




  2. Plotly를 오프라인에서 사용하기 위한 라이브러리 import 및 환경 설정



# import plotly standard

import plotly.plotly as py

import plotly.graph_objs as go

import plotly.figure_factory as ff


# Cufflinks wrapper on plotly

import cufflinks as cf


# Display all cell outputs

from IPython.core.interactiveshell import InteractiveShell


# plotly + cufflinks in offline mode

from plotly.offline import iplot

cf.go_offline()


# set the global theme

cf.set_config_file(world_readable=True, theme='pearl', offline=True)

 




저의 로컴 컴퓨터에서 오프라인 Jupyter Notebook으로 Plotly의 interactive visualization 을 (1) 히스토그램(histogram), (2) 산점도행렬(scatterplot matrix) 의 두개 예를 들어보겠습니다. 


예제 데이터는 iris 데이터프레임입니다. seaborn 패키지에서 iris 데이터셋을 불러오겠습니다. 



import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

 



# data loading

iris = sns.load_dataset('iris')

iris.shape

(150, 5) 




iris.head()

sepal_lengthsepal_widthpetal_lengthpetal_widthspecies
05.13.51.40.2setosa
14.93.01.40.2setosa
24.73.21.30.2setosa
34.63.11.50.2setosa
45.03.61.40.2setosa




  (3) Plotly를 오프라인 Jupyter Notebook에서 사용한 히스토그램(histogram)


(3-1) 각 bin별 빈도(count, frequency)로 히스토그램 그리기


'petal_length' 변수에 대해서 iplot() 함수를 사용하여 20개의 bin으로 나누어서 빈도(count)를 기준으로 히스토그램을 그렸습니다.  아래는 화면 캡쳐한 이미지이다 보니 고정된 그래프인데요, Jupyter Notebook에서 마우스를 그래프 위에 가져다 대면 각 bin의 구간과 빈도가 화면에 interactive하게 나타납니다. 특정 구역을 마우스로 블럭을 설정하면 그 부분만 확대되어서 나타납니다(hover 기능). 



# Histogram with Frequency

iris['petal_length'].iplot(

    kind='hist', 

    bins=20, 

    xTitle='Petal Length(cm)', 

    linecolor='gray', 

    yTitle='Count', 

    title='Histogram of Petal Length')





(3-2) 각 bin별 구성비율로 히스토그램 그리기



# Histogram with Percentage

iris['petal_length'].iplot(

    kind='hist', 

    bins=20, 

    xTitle='Petal Length(cm)', 

    linecolor='gray', 

    histnorm='percent',

    yTitle='Percentage(%)', 

    title='Histogram of Petal Length in Percent')



 




  (4) Plotly를 오프라인 Jupyter Notebook에서 사용한 산점도 행렬(scatterplot matrix)


아래의 Plotly로 그린 산점도 행렬도 마우스를 가져다대면 interactive하게 해당 값이 화면에 나와서 바로 확인을 할 수 있습니다. 



fig = ff.create_scatterplotmatrix(

    iris[['petal_width', 'petal_length', 'sepal_width', 'sepal_length']],

    height=800,

    width=800, 

    diag='histogram') # scatter, histogram, box

iplot(fig)



 



Plotly로 그릴 수 있는 다양한 그래프 예제는 https://plot.ly/d3-js-for-python-and-pandas-charts/ 를 참고하시기 바랍니다. 


많은 도움이 되었기를 바랍니다. 


이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾹 눌러주세요.



728x90
반응형
Posted by Rfriend
,