Python ぐりぐり動く三次元散布図を作成する「Plotly Express」

 本記事では、 下図2つのような3次元散布図を作成する雛形コードを載せました。ライブラリは、plotlyを用います。

f:id:HK29:20220319122627p:plain

 作成した図は、下記リンク先のようにグリグリ動かせるため、視野角によってデータの特徴を把握し易くなります。

www.youtube.com

 下図は、例題に用いた機械学習でお馴染みのアイリスデータセットです。列名「species」がカテゴリ変数です。色分けしてグラフにプロットします。

f:id:HK29:20220319124857p:plain

 

パッケージPlotlyのインストールは、pipで次のようにします。

pip install plotly

Jupyterのコマンドセル上でインストールする場合には、頭に%を付けます。

%pip install plotly

 

■図1のプログラム

#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()

DF = pd.DataFrame(iris.data, columns=iris.feature_names)
DF['species'] = iris.target_names[iris.target]
DF


# In[2]:


# カテゴリ変数をチェック
label_list = DF.groupby('species').count().index.to_list()
print(label_list)


# In[3]:


my_title = 'iris dataset'
x_name = 'petal length (cm)'
y_name = 'sepal length (cm)'
z_name = 'sepal width (cm)'
my_label = 'species'


import plotly.express as px
import plotly.io as pio

# グラフオブジェクトの生成
fig = px.scatter_3d(
    DF,
    x = x_name, y = y_name, z = z_name,
    color = my_label,
    #color_discrete_sequence = px.colors.sequential.Plasma_r, # .Plasma_r .Plotly3 .Reds
    color_discrete_sequence = ['red', 'yellow', 'blue'],
    #symbol = my_label,
)

# マーカー、ラインの設定
fig.update_traces(
    mode = 'markers+lines', # 'markers+lines', 'markers'
    marker = dict(size = 3),
    line = dict(width = 2), #color = 'Black',
)

# グラフの見栄えの設定
fig.update_layout(
    # タイトル
    title = dict(
        text = my_title,
        font = dict(size = 25, color = 'black'),
        x = 0.15, y = 0.9,
    ),
    # 凡例
    legend = dict(
        xanchor = 'right',
        yanchor = 'bottom',
        x = 1.37, y = 0.5,
        font = dict(size = 20),
    ),
    # フォント
    font = dict(
        family = 'Courier New, monospace', # Times New Roman, Arial, Balto, Droid Sans
        size = 15,
        color = 'RebeccaPurple',
    ),
    # グラフの画面サイズ
    width = 750, height = 600,
)
fig.show()

# グラフをファイルに保存
pio.write_html(fig, my_title + '_1.html')

 

■図2のプログラム

#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()

DF = pd.DataFrame(iris.data, columns=iris.feature_names)
DF['species'] = iris.target_names[iris.target]
DF


# In[2]:


# カテゴリ変数を数値で作成
from sklearn.preprocessing import LabelEncoder

# カテゴリ変数をリストで取得
label_list = DF.groupby('species').count().index.to_list()
print(label_list)

# オブジェクトの生成
my_class = LabelEncoder()
# 0, 1, 2, … へ数値化するカテゴリをリストで指定
my_class.classes_ = label_list

# pandasデータフレームへ新列名「category」で追記
DF['category'] = my_class.fit_transform(DF['species'])
DF


# In[3]:


my_title = 'iris dataset'
x_name = 'petal length (cm)'
y_name = 'sepal length (cm)'
z_name = 'sepal width (cm)'
my_label = 'category'


import plotly.express as px
import plotly.io as pio

# グラフオブジェクトの生成
fig = px.scatter_3d(
    DF,
    x = x_name, y = y_name, z = z_name,
    color = my_label,
    color_discrete_sequence = px.colors.sequential.Plasma_r, # .Plasma_r .Plotly3 .Reds
    #color_discrete_sequence = ['red', 'yellow', 'blue'],
    #symbol = my_label,
)

# マーカー、ラインの設定
fig.update_traces(
    mode = 'markers', # 'markers+lines', 'markers'
    marker = dict(size = 3),
    line = dict(width = 2), #color = 'Black',
)

# グラフの見栄えの設定
fig.update_layout(
    # タイトル
    title = dict(
        text = my_title,
        font = dict(size = 25, color = 'black'),
        x = 0.15, y = 0.9,
    ),
    # 凡例
    legend = dict(
        xanchor = 'right',
        yanchor = 'bottom',
        x = 1.37, y = 0.5,
        font = dict(size = 20),
    ),
    # フォント
    font = dict(
        family = 'Courier New, monospace', # Times New Roman, Arial, Balto, Droid Sans
        size = 15,
        color = 'RebeccaPurple',
    ),
    # グラフの画面サイズ
    width = 750, height = 600,
)
fig.show()

# グラフをファイルに保存
pio.write_html(fig, my_title + '_2.html')

以上

<広告>