Skip to content

Idea to simplify multi plot #17

@guneco

Description

@guneco

(日本語で失礼します)

記事でコメントいただいた件について、
こういう解決策もあるのかな…? と思いついたことをシェアします。
https://qiita.com/mochi_gu_ma/items/aea51bb986092783f073

要点は

  1. fig,pltの処理とaxを設定する処理を分ける
  2. axの設定をクロージャに移譲する
  3. コンテキストマネージャにクラスではなく、関数を渡す

とりあえずのアイデアなので、プルリク出せるかたちにはできていません。
ご参考までm(_ _)m

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


class CorePlot():
    def __init__(self):
        self.fig = plt.figure(figsize=(5,3))
        self.ax = None
        self.axes = None

    def __enter__(self):
        return(self)

    def __exit__(self, exc_type, exc_value, exc_traceback):
        plt.show()


def plot(ax_func):
    cp = CorePlot()
    ax = cp.fig.add_subplot(111)

    ax = ax_func(ax)
        
    cp.ax = ax
    return cp


def multiplot(ax_funcs, indices):
    cp = CorePlot()
    axes = []
    
    for func, index in zip(ax_funcs, indices):
        ax = cp.fig.add_subplot(index)
        ax = func(ax)
        axes.append(ax)
        
    cp.axes = axes
    return cp


def set_ax(xlim:list[float]):
    # 今回は簡単のためxlimだけ設定する
    def _set_ax(ax):
        ax.set_xlim(*xlim)
        return ax

    return _set_ax
    
xx = np.linspace(-5,5,20)
yy = xx*xx

ax0 = set_ax(xlim=[0,5])
ax1 = set_ax(xlim=[0,2])
ax2 = set_ax(xlim=[-5,0])

with plot(ax0) as p:
    p.ax.plot(xx,yy)

with multiplot([ax0, ax1, ax2],[221,222,223]) as p:
    p.axes[0].plot(xx,yy)
    p.axes[1].plot(xx,yy)
    p.axes[2].plot(xx,yy)

```

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions