【问题标题】:How to assign axes from one figure to axes from another figure?如何将一个图形的轴分配给另一个图形的轴?
【发布时间】:2021-02-25 13:20:31
【问题描述】:

大家!

我想将一个图形的轴分配给另一个图形的轴,你能告诉我怎么做吗?

实际上,我有两个函数,它们都返回轴。我想创建一个带有两个轴的新图形,这两个轴将完全代表我从函数中得到的两个。我试图用属性来操作,但我失败了:(

这是我的代码示例:

def draw(data, markup_data, size = 7):

    ...

    _, ax2 = plt.subplots(figsize=(7, 7))
    ax2.scatter(x, y, s=size, c=data, linewidths=0, alpha=0.9)
    ax2.grid(False)
    return ax2

主要:

fig, axes = plt.subplots(1,2, figsize=(10,5))

axes[0] = draw(data_1)
axes[1] = draw(data_2)

fig.show()

【问题讨论】:

    标签: python function matplotlib figure axes


    【解决方案1】:

    轴不能移动到另一个图形。推荐的方法是将ax 作为参数提供给draw(....., ax=...)

    代码结构如下:

    from matplotlib import pyplot as plt
    
    def draw(data, size=7, ax=None):
        if ax is None:
            ax = plt.gca()  # use current axis if none is given
        ax.scatter(data['x'], data['y'], s=size, c=data['c'], linewidths=0, alpha=0.9)
        ax.grid(False)
    
    fig, axes = plt.subplots(1, 2, figsize=(10, 5))
    draw(data_1, ax=axes[0])
    draw(data_2, ax=axes[1])
    fig.show()
    

    通常还提供scatter 的参数。 Python 通过**kwargs 支持这些额外的关键字并将它们转换为字典。对于scatter 的参数不是用户提供的,draw 函数可以设置自己的默认值。这是一个更详细的示例:

    from matplotlib import pyplot as plt
    import numpy as np
    
    def draw(data, size=7, ax=None, **kwargs):
        if ax is None:
            ax = plt.gca()  # use current axis if none is given
        print(kwargs)
        if 's' not in kwargs:
            kwargs['s'] = 7
        if 'linewidths' not in kwargs:
            kwargs['linewidths'] = 0
        if 'alpha' not in kwargs:
            kwargs['alpha'] = 0.9
        print(kwargs)
        ax.scatter(data['x'], data['y'], c=data['c'], **kwargs)
        ax.grid(False)
    
    data_1 = {'x': np.random.rand(800), 'y': np.random.rand(800), 'c': np.random.rand(800)}
    data_2 = {'x': np.random.rand(200), 'y': np.random.rand(200), 'c': np.random.rand(200)}
    
    fig, axes = plt.subplots(1, 2, figsize=(10, 5))
    draw(data_1, ax=axes[0])
    draw(data_2, ax=axes[1], linewidths=1, edgecolor='gold', s=20)
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多