简体   繁体   English

matplotlib:一个图上的多个图

[英]matplotlib: multiple plots on one figure

I have some code: 我有一些代码:

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

My questions are: 我的问题是:

1) Why are two separate figures being created? 1)为什么要创建两个单独的数字? I thought the subplot command would combine them into one figure. 我认为subplot命令会将它们组合成一个图形。 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. 我认为它可能是多个plt.show()命令,但我尝试将这些命令注释掉,只从我的函数外部调用一次,我仍然有2个窗口。

2) How can I combine them into 1 figure properly? 2)如何将它们正确地组合成1个数字? Also, I would want figure 2 axes to have the same scale (ie so 400 m on the x axis is the same length as 400 m on the y-axis). 另外,我希望图2的轴具有相同的比例(即,x轴上的400米与y轴上的400米的长度相同)。 Similarly, I'd like to stretch the histogram vertically as well - how is this accomplished? 同样,我也想垂直拉伸直方图 - 这是如何实现的?

As you observed already, you cannot call figure() inside each function if you intend to use only one figure (one Window). 正如您已经观察到的那样,如果您打算只使用一个数字(一个Window),则不能在每个函数内调用figure() )。 Instead, just call subplot() without calling show() inside the function. 相反,只需调用subplot()而不在函数内调用show() The show() will force pyplot to create a second figure IF you are in plt.ioff() mode. 如果您处于plt.ioff()模式, show()将强制pyplot创建第二个数字。 In plt.ion() mode you can keep the plt.show() calls inside the local context (inside the function). plt.ion()模式中,您可以将plt.show()调用保留在本地上下文(函数内部)中。

To achieve the same scale for the x and y axes, use plt.axis('equal') . 要获得x和y轴的相同比例,请使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM