将两个独立图与 matplotlib 结合的最佳方法是什么? [英] What is the best way of combining two independent plots with matplotlib?

查看:46
本文介绍了将两个独立图与 matplotlib 结合的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在问自己一个问题:如何以模块化方式轻松地将不同的地块与matplotlib结合起来?

I keep asking this question to myself: how to combine easily different plots with matplotlib, in a modular way?

例如,假设我编写了一个显示图节点位置的函数.同时,我制作了另一个绘制多边形的函数.现在,什么是合并输出的正确方法,所以节点似乎位于多边形内部?更改整个单个图的透明度、位置等的可能性如何?这两个初始函数的结构应该是什么?

Let's say for instance that I wrote a function displaying the positions of the nodes of a graph. In parallel, I made another function which plots some polygons. Now, what is the right way of combining the outputs, so the nodes appear to be inside the polygons? What about the possibility to change the transparency, positions, etc, of the entire individual plots? What should be the structure of the two initial functions?

是否有一种聪明而通用的方法?

Is there a smart and general way of doing this?

推荐答案

仅详细说明@Alan所说的内容,您通常会构建类似于以下内容的绘图函数:

Just to elaborate on what @Alan said, you'd typically structure your plotting functions somewhat similar to this:

import numpy as np
import matplotlib.pyplot as plt

def main():
    data = [np.random.random((2, 3)) for _ in range(5)]
    fig, ax = plt.subplots()
    plot_polygons(data, alpha=0.5, ax=ax)
    plot_verts(data, marker='^', color='black', ax=ax)
    plt.show()


def plot_polygons(data, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    artists = [ax.fill(x, y, **kwargs) for x, y in data]
    return artists

def plot_verts(data, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    artists = [ax.scatter(x, y, **kwargs) for x, y in data]
    return artists

main()

这种方法的优点是您可以隐式使用当前图形和/或自动创建一个.通过在绘图功能内执行类似于 ax = plt.gca()的操作(如果ax为其他ax ),可以根据需要混合pyplot状态机样式:

The advantage of this approach is that you could implicitly use the current figure and/or automatically create one. By doing something similar to ax = plt.gca() if ax is None else ax inside your plotting function, you can mix in the pyplot state-machine style if you'd like:

def main():
    data = [np.random.random((2, 3)) for _ in range(5)]
    plot_polygons(data, alpha=0.5)
    plot_verts(data, marker='^', color='black')
    plt.show()

或者您可以显式指定 Axes 实例(通常这是一种更好的方法).这使您可以通过不同的方式在特定的轴上进行绘制:

Or you can explicitly specify the Axes instance (which is a better approach in general). This allows you to plot on specific axes in different ways:

data = [np.random.random((2, 3)) for _ in range(5)]

fig, axes = plt.subplots(nrows=2, sharex=True)

axes[0].set(title='Simple Plot', ylabel='Y-label')
plot_verts(data, marker='o', ax=axes[0])

axes[1].set(title='More complex', xlabel='X-label')
plot_polygons(data, ax=axes[1], alpha=0.5, color='gray')
plot_verts(data, ax=axes[1], color='red', marker='s', s=200)

plt.show()

请注意,我将返回创建的艺术家,但在任何示例中都没有使用过它们.但是,最好返回艺术家,因为它允许您以后根据需要修改其属性.

Note that I'm returning the artists that are created, but I haven't used them in any example yet. However, it's a good idea to return the artists, as it allows you to modify their properties later if you need to.

例如,让我们将一个简单的交互式示例放在一起,该示例将在您单击时隐藏多边形.我将重新定义之前的函数,使其成为一个完整的示例,您可以复制粘贴并运行:

For example, let's put together a simple interactive example that will hide the polygons when you click. I'll redefine the functions from earlier to make this a complete example that you can copy-paste and run:

import numpy as np
import matplotlib.pyplot as plt

def main():
    data = [np.random.random((2, 3)) for _ in range(5)]
    fig, ax = plt.subplots()
    polygons = plot_polygons(data, alpha=0.5, ax=ax, color='gray')
    verts = plot_verts(data, marker='s', color='red', ax=ax, s=200)

    def on_click(event):
        visible = polygons[0][0].get_visible()
        plt.setp(polygons, visible=not visible)
        plt.setp(verts, color=np.random.random(3))
        plt.draw()
    fig.canvas.mpl_connect('button_press_event', on_click)

    ax.set(title='Click on plot to change')
    plt.show()


def plot_polygons(data, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    artists = [ax.fill(x, y, **kwargs) for x, y in data]
    return artists

def plot_verts(data, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    artists = [ax.scatter(x, y, **kwargs) for x, y in data]
    return artists

main()

这篇关于将两个独立图与 matplotlib 结合的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆