matplotlib:一个图形上有多个图 [英] matplotlib: multiple plots on one figure

查看:132
本文介绍了matplotlib:一个图形上有多个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码:

import matplotlib.pyplot as plt

def print_fractures(fractures):
    xpairs = []
    ypairs = []
    plt.figure(2)
    plt.subplot(212)
    for i in range(len(fractures)):
        xends = [fractures[i][1][0], fractures[i][2][0]]
        yends = [fractures[i][1][1], fractures[i][2][1]]
        xpairs.append(xends)
        ypairs.append(yends)
    for xends,yends in zip(xpairs,ypairs):
        plt.plot(xends, yends, 'b-', alpha=0.4)
    plt.show()


def histogram(spacings):
    plt.figure(1)
    plt.subplot(211)
    plt.hist(spacings, 100)
    plt.xlabel('Spacing (m)', fontsize=15)
    plt.ylabel('Frequency (count)', fontsize=15)
    plt.show()

histogram(spacings)    
print_fractures(fractures)

此代码将产生以下输出:

This code will produce the following output:

我的问题是:

1)为什么要创建两个单独的图形?我认为subplot命令会将它们组合成一个图形.我以为可能是多个plt.show()命令,但是我尝试将其注释掉,并且只从函数外部调用了一次,但仍然有2个窗口.

1) Why are two separate figures being created? I thought the subplot command would combine them into one figure. I thought it might be the multiple plt.show() commands, but I tried commenting those out and only calling it once from outside my functions and I still got 2 windows.

2)如何将它们正确地组合成1个图形?另外,我希望图2的轴具有相同的比例(即x轴上的400 m与y轴上的400 m长度相同).同样,我也想垂直拉伸直方图-这是如何完成的?

2) How can I combine them into 1 figure properly? Also, I would want figure 2 axes to have the same scale (i.e. so 400 m on the x axis is the same length as 400 m on the y-axis). Similarly, I'd like to stretch the histogram vertically as well - how is this accomplished?

推荐答案

正如您已经观察到的,如果只打算使用一个数字(一个Window),则不能在每个函数内调用figure().相反,只需调用subplot()而不在函数内部调用show()即可.如果您处于plt.ioff()模式,show()将强制pyplot创建第二个图形.在plt.ion()模式下,您可以将plt.show()调用保留在本地上下文中(在函数内部).

As you observed already, you cannot call figure() inside each function if you intend to use only one figure (one Window). Instead, just call subplot() without calling show() inside the function. The show() will force pyplot to create a second figure IF you are in plt.ioff() mode. In plt.ion() mode you can keep the plt.show() calls inside the local context (inside the function).

要在x和y轴上达到相同的比例,请使用plt.axis('equal').在下面,您可以看到此原型的图示:

To achieve the same scale for the x and y axes, use plt.axis('equal'). Below you can see an illustration of this prototype:

from numpy.random import random
import matplotlib.pyplot as plt

def print_fractures():
    plt.subplot(212)
    plt.plot([1,2,3,4])

def histogram():
    plt.subplot(211)
    plt.hist(random(1000), 100)
    plt.xlabel('Spacing (m)', fontsize=15)
    plt.ylabel('Frequency (count)', fontsize=15)

histogram()
print_fractures()
plt.axis('equal')
plt.show()

这篇关于matplotlib:一个图形上有多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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