首页 > 解决方案 > 如何在 matplotlib 中连接两个不同大小的图形?

问题描述

我有两个来自 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() 

我想“收集”这两个数字(例如左边的第一个和右边的第二个)。我尝试了几个小时,GrisSpecadd_subplot我失败了......拜托,如果你有任何解决这个问题的线索,你能告诉我吗?

请你的!

标签: pythonmatplotlibsubplot

解决方案


您可以使用add_axesMatplotlib 的 Figure 的方法:

在这里,我只是一个 Q&D 示例,您肯定需要调整(很多)才能得到您想要的

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

在此处输入图像描述


推荐阅读