Как объединить две фигуры с разными размерами в matplotlib? - PullRequest
1 голос
/ 20 февраля 2020

У меня есть две разные цифры из matplotlib. Первый показывает размеры ячеек во времени:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mahotas 
import random

fig,ax_curves = plt.subplots(figsize=(8,6))

for cell in range(1,11):

    ax_curves.set_ylim(0,100)
    ax_curves.set_xlim(0,25)
    ax_curves.set_xticks(np.arange(0,21))


    ax_curves.plot(np.arange(0,21), random.sample(range(40, 61), 21), label = str(cell))
    ax_curves.legend(loc='right',frameon=False)
    ax_curves.spines['right'].set_visible(False)
    ax_curves.spines['top'].set_visible(False)
    ax_curves.set_title('Curves')

plt.show()

Второй показывает изображения этих ячеек в разные моменты времени:

fig, ax_images =plt.subplots(10,5,figsize=(9, 16))
columns = 5
rows = 10


for column in range(0, columns):

    cell = 1

    for row in range(0,rows):

        ax_images[row, column].axes.get_xaxis().set_visible(False)

        ax_images[row, column].tick_params(
                    axis='y',         
                    which='both',    
                    left=False,    
                    right=False,
                    labelleft=False)

        ax_images[row, 0].set_ylabel('Cell ' + str(cell), rotation = 0, color=tab10.colors[row])
        ax_images[row, 0].yaxis.set_label_coords(-0.4,0.5)

        if column == 0:
            plt.figtext(0.14 , 0.9, '0 hour',fontsize = 20)
            img = mahotas.imread('path/to/image_t0.tif')
        if column == 1:
            plt.figtext(0.28, 0.9, '5 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t5.tif')
        if column == 2:
            plt.figtext(0.44 , 0.9, '10 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t10.tif')
        if column == 3:
            plt.figtext(0.60, 0.9, '15 hours',fontsize = 20)
            img = mahotas.imread('path/to/image_t15.tif')
        if column == 4:
            plt.figtext(0.76 , 0.9, '20 hours', fontsize = 20)
            img = mahotas.imread('path/to/image_t20.tif')


        ax_images[row, column].imshow(img)

        cell = cell + 1

plt.figtext(0.5,0.95,'Cell size through time', fontsize = 20, horizontalalignment='center')
plt.show() 

Я хотел бы "собрать" эти две цифры (первый слева и второй справа для примера). Я пытался в течение нескольких часов с GrisSpec или add_subplot, но мне не удалось ... Пожалуйста, не могли бы вы дать мне знать, если у вас есть какие-либо подсказки для решения этой проблемы?

Пожалуйста, ваш!

Ответы [ 2 ]

1 голос
/ 20 февраля 2020

Благодаря ответу @gboffi мне удалось решить мою проблему:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import mahotas 
import random

f = plt.figure(figsize=(13,4))
ax_curves = f.add_axes((0.10,1.5, 0.33, 0.85))

for cell in range(1,11):

    ax_curves.set_ylim(0,100)
    ax_curves.set_xlim(0,30)
    ax_curves.set_xticks(np.arange(0,21,5))


    ax_curves.plot(np.arange(0,21), random.sample(range(40, 61), 21), label = 'Cell ' + str(cell))
    ax_curves.legend(loc='right',frameon=False)
    ax_curves.spines['right'].set_visible(False)
    ax_curves.spines['top'].set_visible(False)
    ax_curves.set_title('Curves')


for column in np.linspace(0.5, 0.9, 5):    


    cell = 1

    tab10 = matplotlib.cm.get_cmap('tab10')


    for row in np.linspace(2.8, 0.10, 10): 
    # LL corner, width, height in figure coordinates, 0 ≤ x,y,h,w ≤ 1
        ax_images = f.add_axes((column, row, 0.09, 0.27))

        ax_images.axes.get_xaxis().set_visible(False)

        ax_images.tick_params(
                    axis='y',          
                    which='both',     
                    left=False,     
                    right=False,
                    labelleft=False) 

        if column == 0.5:
            ax_images.set_ylabel('Cell ' + str(cell), rotation = 0, color=tab10.colors[cell-1])
            ax_images.yaxis.set_label_coords(-0.4,0.5)

        else :
            pass



        if column == 0.5:
            plt.figtext(column+0.01 , 3.1, '0 hour',fontsize = 20)
#             img = mahotas.imread('path/to/image_t0.tif')
        if column == 0.6:
            plt.figtext(column, 3.1, '5 hours',fontsize = 20)
#             img = mahotas.imread('path/to/image_t5.tif')
        if column == 0.7:
            plt.figtext(column , 3.1, '10 hours', fontsize = 20)
#             img = mahotas.imread('path/to/image_t10.tif')
        if column == 0.8:
            plt.figtext(column, 3.1, '15 hours',fontsize = 20)
#             img = mahotas.imread('path/to/image_t15.tif')
        if column == 0.9:
            plt.figtext(column , 3.1, '20 hours', fontsize = 20)
#             img = mahotas.imread('path/to/image_t20.tif')


#         ax[row, column].imshow(img)

        cell = cell + 1
plt.figtext(0.5,3.33,'Cell sizes through time', fontsize = 20, horizontalalignment='center')

Большое спасибо за вашу помощь !!!

enter image description here

1 голос
/ 20 февраля 2020

Вы можете использовать метод add_axes на рисунке Matplotlib:

Здесь у меня есть только пример вопросов и ответов, который вам определенно нужно настроить (много), чтобы получить именно то, что вы хотите

In [54]: f = plt.figure(figsize=(13,4)) 
    ...: f.add_axes((0.10,0.10, 0.25, 0.85));

In [55]: for y in np.linspace(0.87, 0.10, 10): 
    ...:     for x in np.linspace(0.40, 0.85, 5): 
    ...:         # LL corner, width, height in figure coordinates, 0 ≤ x,y,h,w ≤ 1
    ...:         f.add_axes((x, y, 0.09, 0.08))                                           

enter image description here

...