Matplotlib: multiple charts on one shape

I have a 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 result: Fig1

My questions:

1) Why are two separate shapes created? I thought the subplot team would combine them into one shape. I thought it could be a few plt.show () commands, but I tried to comment on them and only call them once from outside my functions, and I still have 2 windows.

2) How can I correctly combine them into 1 figure? In addition, I would like the axes of figure 2 to have the same scale (i.e. 400 m along the x axis would be the same length as 400 m along the y axis). Similarly, I would also like to stretch the histogram vertically - how is this achieved?

+7
python matplotlib plot
source share
1 answer

As you have already noticed, you cannot call figure() inside each function if you intend to use only one digit (one window). Instead, just call subplot() without calling show() inside the function. show() will cause pyplot to create a second digit if you are in plt.ioff() mode. In plt.ion() mode, you can save plt.show() calls inside the local context (inside a 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() 
+8
source share

All Articles