首页 > 解决方案 > matplotlib imshow 上切片数据框轴对齐

问题描述

下面的代码是该问题的一个示例。

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

setData = [0]*15
for x in range(15):
    exData = np.random.random((256,1024))
    
    index = list(range(0,256))
    cols = list(range(0,1024))
    
    df = pd.DataFrame(exData,index=index,columns=cols)
    df = df.iloc[8:df.shape[0]-8,10:df.shape[1]-10]
    setData[x] = df

bProjections = True


if bProjections:
    for frame in range(len(setData)):
        img = setData[frame]
        print(img.shape)
        #Projections
        xProj = img.sum(axis=1)
        yProj = img.sum(axis=0)

        fig,ax = plt.subplots(2,2, figsize=(12,6))
        ax[0][0].imshow(img,aspect='auto',cmap='plasma',vmin=img.stack().mean()-2*img.stack().std(),vmax=img.stack().mean()+2*img.stack().std())
        ax[0][1].plot(xProj,img.index)
        ax[1][0].plot(yProj)
        ax[1][0].sharex(ax[0][0])
        ax[0][1].sharey(ax[0][0])
        
        ax[1][1].axis('off')
        
        plt.show()

结果是这样的图:为什么是空白 为什么轴不更新以反映我已经对数据框进行了切片?如果我打印数据框的形状,它会将其识别为 240x1004,但轴仍显示为 256x1024 ...

我发现有趣的是,注释掉共享轴确实允许 imshow 图生成适当的轴限制,但为什么投影不更新?无轴共享

标签: pythondataframematplotlibimshow

解决方案


似乎有一些关于从 sum 函数和/或数据帧后切片索引生成的 pandas 系列中的索引值的剩余信息。

通过使用 pandas 系列中的原始 np 数组并为水平投影提供新的递增索引,获得了所需的输出。附上修改后的代码和示例输出。

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

setData = [0]*15
for x in range(15):
    exData = np.random.random((256,1024))
    
    index = list(range(0,256))
    cols = list(range(0,1024))
    
    df = pd.DataFrame(exData,index=index,columns=cols)
    ndf = df.iloc[8:df.shape[0]-8,10:df.shape[1]-10]
    setData[x] = ndf

bProjections = True


if bProjections:
    for frame in range(len(setData)):
        img = setData[frame]
        print(img.shape)
        
        #Projections
        xProj = img.sum(axis=1).values
        yProj = img.sum(axis=0).values
        fig,ax = plt.subplots(2,2, figsize=(12,6))
        ax[0][0].imshow(img,aspect='auto',cmap='plasma',vmin=img.stack().mean()-2*img.stack().std(),vmax=img.stack().mean()+2*img.stack().std())
        ax[0][1].plot(xProj,list(range(0,240,1)))
        ax[1][0].plot(yProj)
        ax[1][0].sharex(ax[0][0])
        ax[0][1].sharey(ax[0][0])
        
        ax[1][1].axis('off')
        
        plt.show()

在此处输入图像描述


推荐阅读