用排列在网格中的线图覆盖matplotlib imshow

2024-05-03 15:05:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在图像上绘制一些曲线

使用此代码,我相当接近:

G=plt.matplotlib.gridspec.GridSpec(64,1)
fig = plt.figure()
plt.imshow(img.data[:,:],cmap='gray')
plt.axis('off')
plt.axis([0,128,0,64])
for i in arange(64):
    fig.add_subplot(G[i,0])
    plt.axis('off')
    # note that vtc.data.shape = (64, 128*400=51200)
    # so every trace for each image pixel is 400 points long
    plt.plot(vtc.data[i,:])
    plt.axis([0, 51200, 0, 5])

我得到的结果是这样的: lineplots over image

问题是,虽然我似乎能够去除水平(x)方向上的所有填充,但图像和垂直方向上的堆叠图中的填充量不同。

我试着用

ax = plt.gca()
ax.autoscale_view('tight')

但这也没有降低利润率。

我怎样才能得到一个m-by-n的线图网格,与一个放大的(按因子f)版本的图像精确对齐(fm)-by-(fn)?


更新和解决方案: “RutgerKassies”的答案非常有效。我是这样用他的代码实现的:

fig, axs = plt.subplots(1,1,figsize=(8,4))
axs.imshow(img.data[:,:],cmap='gray', interpolation='none')
nplots = 64
fig.canvas.draw()
box = axs._position.bounds
height = box[3] / nplots
for i in arange(nplots):
    tmpax = fig.add_axes([box[0], box[1] + i * height, box[2], height])
    tmpax.set_axis_off()
    # make sure to get image orientation right and 
    tmpax.plot(vtc.data[nplots-i-1,:],alpha=.3)
    tmpax.set_ylim(0,5)
    tmpax.set_xlim(0, 51200)

improved image


Tags: 代码图像boxfordatafigpltvtc
1条回答
网友
1楼 · 发布于 2024-05-03 15:05:01

我认为最简单的方法是使用“imshow轴”的边界来手动计算所有“lineplot轴”的边界:

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(1,1,figsize=(15,10))

axs.imshow(np.random.rand(50,100) ,cmap='gray', interpolation='none', alpha=0.3)

nplots = 50

fig.canvas.draw()

box = axs._position.bounds
height = box[3] / nplots

for i in arange(nplots):

    tmpax = fig.add_axes([box[0], box[1] + i * height, box[2], height])
    tmpax.set_axis_off()

    tmpax.plot(np.sin(np.linspace(0,np.random.randint(20,1000),1000))*0.4)
    tmpax.set_ylim(-1,1)

上面的代码看起来不错,但我确实有一些问题与自动缩放切断部分情节。试着去掉最后一行看看效果,我不知道为什么会这样。

enter image description here

相关问题 更多 >