Plotly

Google Colab Plotly Graph 안 보일 때

현상

  • plotly 라이브러리를 활용하여 Google Colab에서 시각화를 할 때 그래프가 보이지 않는 현상이 존재함
  • 여러 방법론이 등장하지만, 공식문서에 따라서 어떻게 활용하는지 확인하도록 함

Google Colab

  • 먼저 구글 코랩에서 간단한 시각화 코드를 작성하고 코드를 실행한다.
import plotly 
plotly.__version__
# 5.13.1
  • 샘플 코드는 아래와 같음
import plotly.graph_objects as go
import pandas as pd 

temp = pd.DataFrame({
  "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
  "Contestant": ["Alex", "Alex", "Alex", "Jordan", "Jordan", "Jordan"],
  "Number Eaten": [2, 1, 3, 1, 3, 2],
})

fig = go.Figure()
fig.add_trace(go.Bar(name = "Alex", x = temp['Fruit'], y = temp[temp['Contestant'] == 'Alex']['Number Eaten'].values))
fig.add_trace(go.Bar(name = "Jordan", x = temp['Fruit'], y = temp[temp['Contestant'] == 'Jordan']['Number Eaten'].values))
fig.update_layout(barmode='group')
print(type(fig))
fig.show()

시각화가 나타나지 않을 경우

  • 만약 시각화가 나타나지 않는다면 설정이 제대로 되어 있지 않았을 가능성이 있다.
  • 공식문서를 참조하면 다음과 같다.
  • 공식 문서에서의 설명을 보면 다음과 같다.

Untitled

Plotly 그래프 - 막대 그래프 색상 변경

개요

  • 특정 컬럼의 색상을 변경하는 코드를 작성한다.

기본 그래프 작성

  • 우선 아래와 같은 기본 그래프를 작성한다.
import plotly.express as px 

tips = px.data.tips()
tips_mean_day = tips.groupby("day").mean().reset_index()
tips_mean_day.head()

Untitled

fig = px.bar(tips_mean_day, x = 'day', y = 'tip')
fig.show()

newplot_01.png

Sun 색상 변경

  • Sun 값의 막대 그래프의 색상을 변경하도록 한다.
  • 먼저 marker.color를 활용하여 색상을 먼저 지정한 뒤, X축 라벨의 순서를 후에 재정렬한 것이다.
fig.data[0].marker.color = ['#ff0000', '#ff0000', 'black', '#ff0000']
fig.layout.xaxis.categoryarray = ["Thur", "Fri", "Sat", "Sun"]
fig.show()

newplot_01.png

투명도 설정

fig.data[0].marker.color = ['#ff0000', '#ff0000', 'black', '#ff0000']
fig.data[0].marker.opacity = [0.3, 0.3, 1, 0.3]
fig.layout.xaxis.categoryarray = ["Thur", "Fri", "Sat", "Sun"]
fig.show()

newplot_02.png

Plotly 그래프 - 막대 그래프 X축 라벨 변경하기

개요

  • 기존에 작성한 그래프를 목적에 맞게 수정 및 변경할 수 있다.
  • Figure Object를 활용한다.

데이터 불러오기 및 가공

  • tips 데이터를 불러온 뒤, 데이터를 가공하여 평균 값을 구한다.
import plotly.express as px 

tips = px.data.tips()
tips_mean_day = tips.groupby("day").mean().reset_index()
tips_mean_day.head()

Untitled

막대 그래프 작성하기

  • 기본 막대그래프를 작성한다.
  • 그런데, X축의 값을 보면 요일별로 정리가 안된 것을 확인할 수 있다. 이 부분을 수정하도록 한다.
fig = px.bar(tips_mean_day, x = 'day', y = 'tip')
fig.show()

newplot_01.png

막대 그래프의 X 라벨 변경하기

  • 우선 막대그래프의 순서를 변경하도록 한다. 세가지 방법이 있다. 첫번째는 최초 그래프를 생성할 때, category_orders 에 그래프의 순서를 지정하는 방법이 있다.
fig = px.bar(tips_mean_day, x = 'day', y = 'tip', category_orders={"day": ["Thur", "Fri", "Sat", "Sun"]})
fig.show()

newplot_02.png

Plotly 그래프 - Plotly Express

개요

  • High-Level API 형태인 Plotly Express에 대해 학습하도록 한다.
  • Plotly Express는 간단하게 말하면 Pandas Dataframe과 직접적으로 연동이 가능하다.
  • 보다 직관적으로 그래프를 시각화할 수 있기 때문에 초기 밑그림을 그릴 때는 Plotly Express로 작성하는 것이 좋다.
  • 전체 설명 참고자료 : Plotly Express in Python

Plotly Express 요약

Plotly Express 그래프 종류

Plotly Express currently includes the following functions:

Plotly 그래프 - 테마 변경하기

개요

  • plotly 그래프의 테마를 변경하는 방법에 대해 알아본다.

그래프 테마의 종류 확인하기

  • 우선 기본 그래프를 확인한다.
import plotly.graph_objects as go
weekly_sales = dict({
    "data": [{
        "type": "bar", 
        "x": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], 
        "y": [28, 27, 25, 31, 32, 35, 36]
    }], 
    "layout" : {"title": {"text": "Sales of the week", 
                          "x": 0.5, "font": {"color": "red", "size": 15}}}
})

fig = go.Figure(weekly_sales)
fig.show()

newplot.png

  • 그래프 테마를 변경하기 위해 우선 종류를 확인해야 한다.
plotly.io.templates
Templates configuration
-----------------------
    Default template: 'plotly'
    Available templates:
        ['ggplot2', 'seaborn', 'simple_white', 'plotly',
         'plotly_white', 'plotly_dark', 'presentation', 'xgridoff',
         'ygridoff', 'gridon', 'none']

그래프 테마 변경하기

  • 그래프 테마를 변경하도록 하기 위해서는 간단하게 아래와 같이 적용하면 된다.
fig.layout.template = 'ggplot2'
fig.show()

newplot_02.png

Plotly 그래프 - 이미지 내보내기

개요

  • Plotly 그래프를 다양한 방법으로 내보내는 코드를 작성해본다.
  • 본 블로그에서는 HTML, PNG 두가지 형태로 내보내는 방법을 숙지한다.

HTML로 내보내기

  • plotly figures는 HTML 및 자바스크립트로 구성되어 있다.
  • 소스코드는 아래와 같다.
fig.write_html('html_plot.html', config={'toImageButtonOptions':{'format': 'svg'}})

Screen Shot 2022-09-11 at 4.00.12 PM.png

image로 내보내기

  • 이미지로 내보내기 위해서는 아래와 같이 소스코드를 작성한다.
fig.write_image('path/to/image_file.svg',height=600, width=850)
  • 그런데, 실행 시, 다음과 에러가 나올 경우 아래와 같이 라이브러리를 설치한다.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-691564193a43> in <module>
----> 1 fig.write_image('img/tutorial.png', height = 600, width = 850)

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/plotly/basedatatypes.py in write_image(self, *args, **kwargs)
   3819         import plotly.io as pio
   3820 
-> 3821         return pio.write_image(self, *args, **kwargs)
   3822 
   3823     # Static helpers

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/plotly/io/_kaleido.py in write_image(fig, file, format, scale, width, height, validate, engine)
    266     # -------------
    267     # Do this first so we don't create a file if image conversion fails
--> 268     img_data = to_image(
    269         fig,
    270         format=format,

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/plotly/io/_kaleido.py in to_image(fig, format, width, height, scale, validate, engine)
    132     # Raise informative error message if Kaleido is not installed
    133     if scope is None:
--> 134         raise ValueError(
    135             """
    136 Image export using the "kaleido" engine requires the kaleido package,

ValueError: 
Image export using the "kaleido" engine requires the kaleido package,
which can be installed using pip:
    $ pip install -U kaleido
pip install -U kaleido
  • 다음 코드를 재 실행한다.
fig.write_image('img/tutorial.png', height = 600, width = 850)
  • 해당되는 경로에서 실제 이미지가 내보내기가 되었는지 확인한다.

Screen Shot 2022-09-11 at 4.18.57 PM.png

Plotly 그래프 - Figure Object 이해하기

Figure Object

  • Figure Object는 크게 두가지로 구성(Attribute)이 되어 있다.
    • data : 여기에서는 그래프와 관련된 각종 정보가 담긴 데이터를 의미한다. 예를 들면, 산점도를 그린다면, X와 Y값의 정보를 확인할 수 있다. 그래프의 색상도 정의할 수 있다.
    • layout : data외의 모든 것은 layout에 속한다. 기본적으로 layout은 그래프의 Styling 요소들이 들어 있다. 예를 들면, X축, Y축의 제목, 색상 등을 변경하고자 할 때는 layout에 접근해야 한다.
  • 간단하게 Figure Object를 정의해본다.
import plotly.graph_objects as go

fig = go.Figure()
fig.show()

tutorial_02.png

Plotly 그래프 시작하기 - 필수 사전 준비

개요

  • Plotly 그래프의 기본 생태계를 익히도록 한다.
  • Plotly 그래프를 작성하도록 한다.

라이브러리 불러오기

  • 본 코드는 모두 Local 가상환경을 설치한 후, Jupyter Lab에서 작성했다.
  • 현재 plotly 버전은 다음과 같다.
import plotly
print(plotly.__version__)
5.1.0
  • 로컬 환경에서 Jupyter notebook에서 plotly 그래프가 간혹 나타나지 않는 경우가 있다. 그런 경우, 아래와 같이 추가로 설치를 진행한다.
jupyter labextension install jupyterlab-plotly
  • 설치가 완료되었다면, 아래와 같은 코드를 추가로 실행한다.
import plotly
plotly.offline.init_notebook_mode(connected=True)

그래프 테스트

  • 먼저, 아래와 같은 샘플 코드를 실행했을 때, Jupyter Lab 상에 그래프 창이 나오면 정상이다.
import plotly.graph_objects as go
weekly_sales = dict({
    "data": [{
        "type": "bar", 
        "x": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], 
        "y": [28, 27, 25, 31, 32, 35, 36]
    }], 
    "layout" : {"title": {"text": "Sales of the week", 
                          "x": 0.5, "font": {"color": "red", "size": 15}}}
})

fig = go.Figure(weekly_sales)
fig.show()

Screen Shot 2022-09-08 at 5.28.19 PM.png

Convert Plotly Jupyterlab to HTML

개요

  • jupyter notebook에서 plotly 기반의 시각화를 작성한다.
  • jupyter notebook에서 html로 변환 시, plotly로 작성된 코드는 나타나지 않았다.
  • 이 때 필수적으로 입력해야 할 코드를 작성한다.

필수 코드 적용 전 변환 시

  • 간단한 시각화 코드를 작성 후, html로 변환한다.
import plotly.express as px

fig = px.line(x=["a","b","c"], y=[1,3,2], title="sample figure")
fig.show()
  • 아래 그림은 일반적으로 JupyterLab 에디터에서 HTML로 변환하는 과정이다.
    • File - Save and Export Notebook As… - HTML 순차적으로 클릭한다.

Screen Shot 2022-04-11 at 10.56.22 PM.png

(Python-Plotly) Plotly 그래프 깃헙 블로그에 올리기

강의 홍보

개요

  • 깃헙 브로그에 동적 시각화를 올리는 방법에 대해 기술한다.
  • 현재까지 찾아낸 것은 이게 최선입니다! 더 나은 것이 있다면 공유 부탁드립니다. (꾸벅)

필수 라이브러리 설치

$ pip install plotly
$ pip install chart_studio
  • plotly의 역할 그래프를 작성하는 기본 도구이며, chart_studio의 역할은 그래프를 plotly 홈페이지 업로드 할 수 있도록 도와주고, 또한 iframe output으로 변환하는 데 도움을 주는 코드이다.

step 01. 그래프 작성

  • 그래프를 작성합니다.
import plotly.express as px
import chart_studio

gapminder = px.data.gapminder()
fig = px.scatter(gapminder.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent",
           hover_name="country", log_x=True, size_max=60)
fig.show()
  • 위 출력물은 실제로는 동적 시각화로 구현이 됩니다만, 캡쳐하여 올려 놓습니다.