Skip to content

並行座標グラフなど、matplotlib単体では難しい可視化を簡単に作成するためのライブラリ

License

Notifications You must be signed in to change notification settings

remokasu/plotlib

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

plotlib

Python License Version

機能

  • 学習曲線、特徴量重要度、決定境界
  • t-SNE/UMAP埋め込み、平行座標、相関行列
  • 最適化収束履歴、パラメータスイープ、パレートフロント

インストール

# 依存関係をインストール
pip install numpy matplotlib scipy scikit-learn umap-learn

クイックスタート

import plotlib as pl
import numpy as np

# シンプルな線グラフ
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
pl.line(x, y, title="Sine Wave")

# 学習曲線の可視化
train_loss = [2.3, 1.8, 1.2, 0.9, 0.7, 0.5]
val_loss = [2.5, 1.9, 1.4, 1.1, 1.0, 1.0]
pl.learning_curve(train_loss, val_loss, ylabel="Loss")

ギャラリー

パレートフロント

np.random.seed(42)
obj1 = np.random.uniform(0, 10, 200)
obj2 = np.random.uniform(0, 10, 200)
objectives = np.column_stack([obj1, obj2])

pl.pareto_front(objectives,
               xlabel="Cost", ylabel="Time",
               title="Multi-Objective Optimization")

Pareto Front

パラメータスイープ

x = np.linspace(-2, 2, 50)
y = np.linspace(-1, 3, 50)
X, Y = np.meshgrid(x, y)
Z = (1 - X)**2 + 100 * (Y - X**2)**2

pl.parameter_sweep(x, y, Z,
                  param1_name="x", param2_name="y",
                  title="Rosenbrock Function Optimization")

Parameter Sweep

埋め込み可視化

X = np.random.randn(300, 50)
labels = np.random.randint(0, 4, 300)

pl.embedding(X, labels=labels, method="tsne",
             title="t-SNE Embedding",
             class_names=["Class A", "Class B", "Class C", "Class D"])

t-SNE Embedding

決定境界

from sklearn.datasets import make_moons

X, y = make_moons(n_samples=300, noise=0.2)

def nonlinear_predict(x):
    return ((x[:, 0]**2 + x[:, 1]**2 - 0.5) >
            (x[:, 0] * 2 - x[:, 1])).astype(int)

pl.decision_boundary(nonlinear_predict, X, y,
                     title="Nonlinear Decision Boundary",
                     resolution=200)

Decision Boundary

平行座標

from sklearn.datasets import load_iris

iris = load_iris()
pl.parallel_coordinates(iris.data, labels=iris.target,
                        feature_names=iris.feature_names,
                        class_names=iris.target_names,
                        title="Iris Dataset")

Parallel Coordinates

学習曲線

epochs = 100
train_loss = 2.0 * np.exp(-np.arange(epochs) / 15) + 0.05
val_loss = 2.2 * np.exp(-np.arange(epochs) / 18) + 0.1

pl.learning_curve(train_loss, val_loss,
                  title="Training Progress",
                  xlabel="Epoch", ylabel="Loss",
                  smooth=5)

Learning Curve

収束履歴

iterations = np.arange(100)
obj_vals = 100 * np.exp(-iterations / 20) + np.random.normal(0, 0.5, 100)

pl.optimization_history(obj_vals, 
                       title="Gradient Descent Convergence",
                       ylabel="Loss")

Optimization History

特徴量重要度

importances = np.array([0.28, 0.22, 0.18, 0.14, 0.10, 0.08])
features = ["Age", "Income", "Education", "Experience", "Location", "Skills"]
errors = np.array([0.03, 0.02, 0.025, 0.02, 0.015, 0.01])

pl.feature_importance(importances,
                      feature_names=features,
                      error_bars=errors,
                      title="Feature Importance Analysis")

Feature Importance

相関行列

X = np.random.randn(200, 6)
pl.correlation_matrix(X,
                      feature_names=['Var A', 'Var B', 'Var C',
                                   'Var D', 'Var E', 'Var F'],
                      title="Correlation Matrix Analysis")

Correlation Matrix

ヒートマップ

X = np.random.randn(200, 8)
corr_matrix = np.corrcoef(X.T)

pl.heatmap(corr_matrix,
           title="Feature Correlation Matrix",
           xticklabels=[f"F{i+1}" for i in range(8)],
           yticklabels=[f"F{i+1}" for i in range(8)],
           cmap='RdBu_r', vmin=-1, vmax=1, annot=True)

Heatmap

散布図

from sklearn.datasets import make_blobs

X, labels = make_blobs(n_samples=300, centers=4, n_features=2)
pl.scatter(X, labels=labels,
           title="Clustered Data",
           class_names=["Cluster A", "Cluster B", "Cluster C", "Cluster D"])

Scatter Plot

線グラフ

x = np.linspace(0, 4*np.pi, 200)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.cos(x)

pl.line(x, np.column_stack([y1, y2, y3]),
        labels=["sin(x)", "cos(x)", "sin(x)cos(x)"],
        title="Trigonometric Functions")

Line Plot

サブプロット

fig, axes = pl.subplots(2, 2, figsize=(12, 10))

# 各axesに直接プロット
axes[0, 0].plot(x, y1)
axes[0, 0].set_title("Sin")

axes[0, 1].scatter(X[:, 0], X[:, 1], c=labels)
axes[0, 1].set_title("Clusters")

im = axes[1, 0].imshow(corr, cmap='RdBu_r')
axes[1, 0].set_title("Correlation")

axes[1, 1].plot(train, label="Train")
axes[1, 1].plot(val, label="Val")
axes[1, 1].set_title("Learning")
axes[1, 1].legend()

fig.tight_layout()

Subplot Layout

スタイル

pl.set_style('publication')  # デフォルト
pl.set_style('presentation') # 大きいフォント
pl.set_style('poster')       # さらに大きいフォント

pl.set_palette('vibrant')    # 鮮やかな色
pl.set_palette('muted')      # 落ち着いた色
pl.set_palette('colorblind') # 色覚異常配慮

高度な使い方

カスタムプロッターの登録

from plotlib import BasePlotter, register_plotter

class MyCustomPlotter(BasePlotter):
    plot_type = "custom"
    supported_dims = (2,)

    def plot(self, ax, data, **kwargs):
        # カスタムプロッティングロジック
        ax.plot(data[:, 0], data[:, 1], 'o-', **kwargs)
        return ax

register_plotter('custom', MyCustomPlotter)

# 使用方法
pl.plot(data, kind='custom')

About

並行座標グラフなど、matplotlib単体では難しい可視化を簡単に作成するためのライブラリ

Topics

Resources

License

Stars

Watchers

Forks

Languages