Flux Capacitor
Flux Capacitor

Reputation: 1231

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: Fig1

My questions are:

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) 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?

Upvotes: 8

Views: 18456

Answers (1)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58985

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).

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()

Upvotes: 8

Related Questions