python - Imshow - 用不同的像素大小分割

标签 python numpy matplotlib pixel imshow

我尝试得到以下内容,应如下图所示。

为了简单起见,让我们假设我有一个 numpy 数组(10x10),我想用 matplotlib imshow 绘制它。条件是具有不同的像素大小,例如:前五行的大小应为0.5cm,后五行的大小应为1cm。列应具有相同的大小。

我怎样才能轻松实现这个?我已经尝试过这样做,但我不喜欢这个解决方案;特别是我仍然有白色边框,缩放效果很糟糕。

from matplotlib import pyplot as pl
import numpy as np

data = np.arange((100))
data = np.reshape(data, (10,10))

figure, (ax1, ax2) = pl.subplots(2, 1, sharex='col')
figure.subplots_adjust(hspace=0)
data1=data[5:10,:]
ax1.imshow(data1, origin="lower", interpolation="none", aspect=0.5, extent=[-0.5,10.5,5.5,10.5], vmax=np.amax(data), vmin=np.amin(data))
ax1.set_ylim([5.5,10.5])
##
data2=data[0:5,:]
ax2.imshow(data2, origin="lower", interpolation="none", aspect=1, extent=[-0.5,10.5,-0.5,5.5], vmax=np.amax(data), vmin=np.amin(data))
ax2.set_ylim([-0.5,5.5])
pl.show()

Output of the code 谢谢 Example for different pixel sizes / desired picture

最佳答案

如果您只使用单个轴对象,这会更简单。然后缩放也可以完美地工作。

代码:

from matplotlib import pyplot as plt
import numpy as np

# prepare the data
data = np.arange((100))
data = np.reshape(data, (10,10))
data1=data[0:5,:]
data2=data[5:10,:]

# create the figure and a single axis
fig, ax = plt.subplots()

# common arguments to imshow
kwargs = dict(
        origin='lower', interpolation='nearest', vmin=np.amin(data),
        vmax=np.amax(data), aspect='auto')

# draw the data
ax.imshow(data1, extent=[0, 10, 0, 5], **kwargs)
ax.imshow(data2, extent=[0, 10, 5, 7.5], **kwargs)

# optional black line between data1 and data2
ax.axhline(5, color='k')

# set the axis limits
ax.set_ylim(0, 7.5)
ax.set_xlim(0, 10)

# set the xticklabels
xticks = np.arange(0,10)
ax.set_xticks(xticks + 0.5)
ax.set_xticklabels(map(str, xticks))

# set the yticks and labels
yticks = np.concatenate((
        np.arange(0, 5) + 0.5,
        np.arange(5, 7.5, 0.5) + 0.25
        ))
ax.set_yticks(yticks)
ax.set_yticklabels(map(str, xticks))

# show the figure
plt.show()

结果:

enter image description here

评论:

  • 我冒昧地以更直观的方式重命名了 data1/2 对象
  • 感谢 @kazemakase 指出需要调整轴刻度。

关于python - Imshow - 用不同的像素大小分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35126402/

相关文章:

Python - NumPy - 从数组中删除多行和多列

numpy - 在 numpy 中优雅地生成结果数组

python - 在一个颜色条上绘制两个范围

python - 两个(双)轴上的线交织 zorder

python - 用正则表达式模式替换

python - 在 Pandas 中导入 csv 数据时如何删除空格 "before"列名

python - Python 中的 Voronoi 分割

python - Numpy 中的逻辑索引与 MATLAB 中的两个索引

python - Matplotlib - 财务量叠加

python - 从python中的.eml文件解析excel附件