Getting the same subtask size using matplotlib imshow and scatter

I am trying to build an image (using matplotlib.imshow) and a scatter plot in the same drawing. When you try this image, the image is smaller than the scatter plot. The following is a small code example:

import matplotlib.pyplot as plt
import numpy as np

image = np.random.randint(100,200,(200,200))
x = np.arange(0,10,0.1)
y = np.sin(x)

fig, (ax1, ax2) = plt.subplots(1,2)
ax1.imshow(image)
ax2.scatter(x,y)

plt.show()

Which gives the following figure:

enter image description here

How can I get two subwords of the same height? (and apparently width)

I tried using gridspecas shown in this :

fig=plt.figure()
gs=GridSpec(1,2)

ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1])
ax1.imshow(image)
ax2.scatter(x,y)

But it gives the same result. I also tried to manually adjust the sizes of the subheadings using:

fig = plt.figure()
ax1 = plt.axes([0.05,0.05,0.45,0.9])
ax2 = plt.axes([0.55,0.19,0.45,0.62])

ax1.imshow(image)
ax2.scatter(x,y)

As a result of trial and error, I can get two subtitles to the desired size, although any change in the overall size of the figure will mean that the subtitles will no longer be the same size.

imshow scatter ?

Python 2.7 matplotlib 2.0.0

+17
3

, .

  1. ax.imshow(z, aspect="auto")
    

    enter image description here

  2. , , ( , x y)

    asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
    ax2.set_aspect(asp)
    

    enter image description here :

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0,10,20)
    y = np.sin(x)
    z = np.random.rand(100,100)
    
    fig, (ax, ax2) = plt.subplots(ncols=2)
    
    ax.imshow(z)
    ax2.plot(x,y, marker=".")
    
    asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
    ax2.set_aspect(asp)
    
    plt.show()
    

    ( ), :

    asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
    asp /= np.abs(np.diff(ax1.get_xlim())[0] / np.diff(ax1.get_ylim())[0])
    ax2.set_aspect(asp)
    
  3. :

    • .

    • mpl_toolkits , .

+21

, SO. , @ImportanceOfBeingErnest, , , ( @Yilun Zhang), :

, , .

:

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))

:

Desired Result

+2

Here is the code I'm using:

fig, axis_array = plt.subplots(1, 2, figsize=(chosen_value, 1.05 * chosen_value / 2),
                               subplot_kw={'aspect': 1})

I clearly choose that there will be 2 subtitles on my figure, and that this figure will be chosen equal to the value, and each subtask will be approximately half as large as the width, and that the subtitles will have an aspect ratio of 1 (i.e. they will be square). Shape size is a specific ratio that forces an interval.

+1
source

All Articles