Home > Software design >  How to display multiple graphs with overlapping data in the same figure thank to matplotlib?
How to display multiple graphs with overlapping data in the same figure thank to matplotlib?

Time:12-08

I'm searching to plot multiple graphs (here is 2) from colormap or contourf functions with different axis X, Y and data Z in the same figure. However I only want to display the maximum of each data with a single color bar for all of the graphs.

In this example, I create a single figure in which I add each graph but the second graph overwrite the first one, regardless of whether its data are lower or higher.

import matplotlib.pyplot as plt
import numpy as np

a = [1,0.25]

fig = plt.figure(1)
ax = fig.gca()

for i in range(2):
    x = np.linspace(-3, 3, 51)
    y = np.linspace(-2*a[i], 2*a[i], 41)

    X, Y = np.meshgrid(x, y)
    if i == 0:
        Z = (1 - X/2   X**5   Y**3) * np.exp(-X**2 - Y**2)
    else:
        Z = 0.5*np.ones((41,51))

    graph = ax.contourf(X,Y,Z)  
    bar = fig.colorbar(graph)

plt.show()

Figure 1 displayed by the code

Here is what I want to display :

Figure 2 desired

Thank you a lot, Tristan

CodePudding user response:

According to the discussion we had in the comments to your post, I think you can edit your code to achieve what you want as below.

First, as a general comment, I suggest that you move your variables to the top of the script.

Second, and this is the main part, you can make do with plotting only one graph if you use comparisons to test which value to fill in your Z-array. You can chain several comparisons using np.logical_and and then use np.where to fill a Z-array with either the function values or the constant value, based on whether you are inside your desired box of x- and y-values and whether the function value or the desired constant value is largest.

fig = plt.figure()
ax = fig.gca()

xmin, xmax, nx = -3, 3, 51
ymin, ymax, ny = -2, 2, 41

# box values
xbmin, xbmax = -3, 3
ybmin, ybmax = -0.5, 0.5
zlevel = 0.5

x = np.linspace(xmin, xmax, nx)
y = np.linspace(ymin, ymax, ny)
X, Y = np.meshgrid(x,y)
Z = (1 - X/2   X**5   Y**3) * np.exp(-X**2 - Y**2)

test1 = Z<zlevel
test2 = np.logical_and(X>=xbmin, X<=xbmax)
test3 = np.logical_and(Y>=ybmin, Y<=ybmax)

mask = np.logical_and(np.logical_and(test1, test2), test3)
Z = np.where(mask, zlevel*np.ones(Z.shape), Z)

graph = ax.contourf(X,Y,Z)
bar = fig.colorbar(graph)

plt.show()
  • Related