Data Visualisation

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

Plot Tree 색상 변경

개요

  • skleran.tree.plot_tree의 색상을 바꿔보도록 한다.
  • matplotlib 객체지향의 구조를 알면 어렵지(?) 않게 바꿀 수 있다.
  • 간단하게 plot_tree 시각화를 구현해본다.
    • 언제나 예제로 희생당하는 iris 데이터에게 애도를 표한다.
  • 구글코랩에서 실행 시, 다음 코드를 실행하여 최신 라이브러리로 업그레이드 한다.
!pip install -U matplotlib
Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (3.2.2)
Collecting matplotlib
  Downloading matplotlib-3.5.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl (11.2 MB)
     |████████████████████████████████| 11.2 MB 27.0 MB/s 
[?25hRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (1.4.0)
Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (2.8.2)
Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (1.21.5)
Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (7.1.2)
Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (3.0.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (0.11.0)
Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (21.3)
Collecting fonttools>=4.22.0
  Downloading fonttools-4.31.2-py3-none-any.whl (899 kB)
     |████████████████████████████████| 899 kB 50.5 MB/s 
[?25hRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib) (3.10.0.2)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7->matplotlib) (1.15.0)
Installing collected packages: fonttools, matplotlib
  Attempting uninstall: matplotlib
    Found existing installation: matplotlib 3.2.2
    Uninstalling matplotlib-3.2.2:
      Successfully uninstalled matplotlib-3.2.2
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.
Successfully installed fonttools-4.31.2 matplotlib-3.5.1
%matplotlib inline 

import sklearn
print(sklearn.__version__)
import matplotlib
print(matplotlib.__version__)

# 필수 라이브러리 불러오기
from sklearn.datasets import load_iris
from sklearn import tree 
import matplotlib.pyplot as plt

# 데이터 불러오기
iris = load_iris()
print(iris.data.shape, iris.target.shape)
print("feature names", iris.feature_names)
print("class names", iris.target_names)

# 모형 학습 및 plot_tree 그래프 구현
dt = tree.DecisionTreeClassifier(random_state=0)
dt.fit(iris.data, iris.target)

fig, ax = plt.subplots(figsize=(10, 6))
ax = tree.plot_tree(dt, max_depth = 2, filled=True, feature_names = iris.feature_names, class_names = iris.target_names)
plt.show()
1.0.2
3.5.1
(150, 4) (150,)
feature names ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
class names ['setosa' 'versicolor' 'virginica']

png

Matplotlib 한글 폰트 추가 (Mac)

개요

  • Mac 유저를 위해 한글 폰트 추가하는 방법을 설명한다.
  • 기본 코드는 Windows에서도 동작한다.
  • 폰트 추가 방법은 생략한다.

한글 폰트 깨진 시각화

  • 간단하게 깨진 한글이 들어간 시각화를 구현한다.
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import matplotlib as mpl
 
plt.plot([1, 2, 3, 4, 5])
plt.title("테스트")
plt.show()
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 53580 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 49828 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 53944 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 53580 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 49828 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 53944 missing from current font.
  font.set_text(s, 0, flags=flags)

png

Home Credit Default - Data Visualization

공지

  • 본 포스트는 재직자 교육을 위해 만든 강의안의 일부입니다.

Introduction

대회 개요

Many people struggle to get loans due to insufficient or non-existent credit histories. And, unfortunately, this population is often taken advantage of by untrustworthy lenders. Home Credit strives to broaden financial inclusion for the unbanked population by providing a positive and safe borrowing experience. In order to make sure this underserved population has a positive loan experience, Home Credit makes use of a variety of alternative data–including telco and transactional information–to predict their clients’ repayment abilities. While Home Credit is currently using various statistical and machine learning methods to make these predictions, they’re challenging Kagglers to help them unlock the full potential of their data. Doing so will ensure that clients capable of repayment are not rejected and that loans are given with a principal, maturity, and repayment calendar that will empower their clients to be successful.

Kaggle Countplot with Text using Seaborn

강의 홍보

개요

캐글 데이터 연동

  • 캐글 데이터를 구글 드라이브에 업로드 한 뒤 구글 코랩과 연동한다.
  • Kaggle API를 통해 데이터를 불러올 수도 있지만, 수동으로 다운로드 받은 뒤 드라이브에 업로드 하였다.
# Mount Google Drive
from google.colab import drive # import drive from google colab

ROOT = "/content/drive"     # default location for the drive
print(ROOT)                 # print content of ROOT (Optional)
drive.mount(ROOT)           # we mount the google drive at /content/drive
/content/drive
Mounted at /content/drive
# import join used to join ROOT path and MY_GOOGLE_DRIVE_PATH
from os.path import join  

# path to your project on Google Drive
MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/competition/kaggle/2020 Kaggle Machine Learning'

PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH)
print(PROJECT_PATH)
/content/drive/My Drive/Colab Notebooks/competition/kaggle/2020 Kaggle Machine Learning
%cd "{PROJECT_PATH}"
/content/drive/My Drive/Colab Notebooks/competition/kaggle/2020 Kaggle Machine Learning

라이브러리 & 데이터 불러오기

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

pd.set_option('mode.chained_assignment', None)
survey = pd.read_csv('./data/kaggle_survey_2020_responses.csv')
question = survey.iloc[0,:].T
full_df = survey.iloc[1:,:]
full_df.shape
/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:2718: DtypeWarning: Columns (0) have mixed types.Specify dtype option on import or set low_memory=False.
  interactivity=interactivity, compiler=compiler, result=result)





(20036, 355)

데이터 전처리

  • 우선 IndiaUSA를 제외한 나라는 삭제하도록 한다.
  • 출력된 결과를 확인해보면 알겠지만, 행이 대폭 감소한 것을 확인할 수 있다.
full_df['Q3'].replace({'United States of America':'USA'}, inplace=True)
df1 = full_df[(full_df['Q3']=='India')|(full_df['Q3']=='USA')]
df1.reset_index(drop=True, inplace=True)
print(df1['Q3'].unique())
df1.shape
['USA' 'India']





(8088, 355)

1차 데이터 시각화

  • 이제 countplot()을 활용하여 시각화를 진행한다.
sns.countplot(x = 'Q4', hue = 'Q3', data = df1)
<matplotlib.axes._subplots.AxesSubplot at 0x7f3bbad50ac8>

png

matplotlib 03_2 Scatter Plot

강의 홍보

산점도 그래프

산점도는 두 수치형 변수의 분포를 비교하고 두 변수 사이에 상관 관계가 있는지 여부를 확인하는 데 사용됩니다. 데이터 내에 구별되는 군집/분할이 있으면 산점도에서도 명확해집니다.

(1) 라이브러리 불러오기

필요한 라이브러리를 불러옵니다.

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

(2) 데이터 생성

이번에는 seaborn 패키지 내 tips 데이터를 활용합니다.

Seaborn intro - Correlation Heatmap

강의 홍보

Seaborn 개요

Matplotlib 라이브러리가 Python에서 제공하는 기본적인 시각화 도구이지만, 기본객체는 리스트 형태를 따르기 때문에, 엑셀 데이터, 즉 데이터 프레임에 익숙한 사용자들에게는 조금 불친절한 것은 아쉬움이 있습니다. 실제, 입문자를 대상으로 강의를 할 때에도 Seaborn부터 알려드리는데, 그 이유는 Pandas를 활용한 데이터 가공 직후에 보다 쉽게 연동할 수 있도록 Seaborn이 개발되었기 때문입니다. 또한, Matplotlib에서는 회귀선과 같은 통계적 내용의 그래프도 보다 쉽게 구현할 수 있도록 제작되었습니다. 보다 정교한 시각적인 디자인을 추가 및 수정하려면, Matplotlib를 보다 더 잘 활용해야 합니다. 이는 마지막 본 포스트의 마지막 장에서 다루도록 합니다.

Seaborn Intro - Countplot

강의 홍보

Seaborn 개요

Matplotlib 라이브러리가 Python에서 제공하는 기본적인 시각화 도구이지만, 기본객체는 리스트 형태를 따르기 때문에, 엑셀 데이터, 즉 데이터 프레임에 익숙한 사용자들에게는 조금 불친절한 것은 아쉬움이 있습니다. 실제, 입문자를 대상으로 강의를 할 때에도 Seaborn부터 알려드리는데, 그 이유는 Pandas를 활용한 데이터 가공 직후에 보다 쉽게 연동할 수 있도록 Seaborn이 개발되었기 때문입니다. 또한, Matplotlib에서는 회귀선과 같은 통계적 내용의 그래프도 보다 쉽게 구현할 수 있도록 제작되었습니다. 보다 정교한 시각적인 디자인을 추가 및 수정하려면, Matplotlib를 보다 더 잘 활용해야 합니다. 이는 마지막 본 포스트의 마지막 장에서 다루도록 합니다.

Seaborn intro - boxplot

강의 홍보

Seaborn 개요

Matplotlib 라이브러리가 Python에서 제공하는 기본적인 시각화 도구이지만, 기본객체는 리스트 형태를 따르기 때문에, 엑셀 데이터, 즉 데이터 프레임에 익숙한 사용자들에게는 조금 불친절한 것은 아쉬움이 있습니다. 실제, 입문자를 대상으로 강의를 할 때에도 Seaborn부터 알려드리는데, 그 이유는 Pandas를 활용한 데이터 가공 직후에 보다 쉽게 연동할 수 있도록 Seaborn이 개발되었기 때문입니다. 또한, Matplotlib에서는 회귀선과 같은 통계적 내용의 그래프도 보다 쉽게 구현할 수 있도록 제작되었습니다. 보다 정교한 시각적인 디자인을 추가 및 수정하려면, Matplotlib를 보다 더 잘 활용해야 합니다. 이는 마지막 본 포스트의 마지막 장에서 다루도록 합니다.

Seaborn Intro - Scatterplot, Histogram

강의 홍보

Seaborn 개요

Matplotlib 라이브러리가 Python에서 제공하는 기본적인 시각화 도구이지만, 기본객체는 리스트 형태를 따르기 때문에, 엑셀 데이터, 즉 데이터 프레임에 익숙한 사용자들에게는 조금 불친절한 것은 아쉬움이 있습니다. 실제, 입문자를 대상으로 강의를 할 때에도 Seaborn부터 알려드리는데, 그 이유는 Pandas를 활용한 데이터 가공 직후에 보다 쉽게 연동할 수 있도록 Seaborn이 개발되었기 때문입니다. 또한, Matplotlib에서는 회귀선과 같은 통계적 내용의 그래프도 보다 쉽게 구현할 수 있도록 제작되었습니다. 보다 정교한 시각적인 디자인을 추가 및 수정하려면, Matplotlib를 보다 더 잘 활용해야 합니다. 이는 마지막 본 포스트의 마지막 장에서 다루도록 합니다.