在Python的Matplotlib中,如何获得薄图像来为主图像加边框?

2024-04-19 22:41:02 发布

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

我有一个二维矩阵Main,一个高度与Main匹配的Left矩阵,还有一个宽度与Main匹配的Top矩阵。我希望所有3个都有颜色条(以各自的限制为界),并将它们缝合到一个图像中,Top到顶部,LeftMain的左侧。你知道吗

最后,我希望能够在其他绘图的子绘图区中绘制整个区块。你知道吗

到目前为止,我一直在尝试axes_grid1,但我无法让薄矩阵(和颜色条)粘到它们适当的边上。我应该完全用别的东西吗?你知道吗

enter image description here

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

# Data
n = 20
Main = np.random.randn(n, n)
Left = np.random.randn(n, 1)
Top  = np.random.randn(n, 2)

# Setup
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
ax_top   = divider.append_axes("top",   1., pad=0.)
ax_left  = divider.append_axes("left",  1., pad=0.)
ax_right = divider.append_axes("right", 1., pad=0.)

# Main
im_main = ax.imshow(Main)
clrbar_right = plt.colorbar(im_main, cax=ax_right)

# Top
im_top  = ax_top.imshow(Top.T)
ax_top_divider = make_axes_locatable(ax_top)
ax_top_top = ax_top_divider.append_axes('top', 1., pad=0.)
ax_top_clrbar = plt.colorbar(im_top, cax=ax_top_top, orientation='horizontal')

# Left
im_left = ax_left.imshow(Left)
ax_left_divider = make_axes_locatable(ax_left)
ax_left_left = ax_left_divider.append_axes('left', 1., pad=0.)
ax_left_clrbar = plt.colorbar(im_left, cax=ax_left_left)
plt.show()

Tags: makemaintopnpplt矩阵axleft
1条回答
网友
1楼 · 发布于 2024-04-19 22:41:02

Axes_Grid

我想你几乎正确了,但是没有必要创建多个分隔符来附加颜色条轴。我们可以使用原来的分隔器本身。我不得不使用sizeappend_axes参数来获得下面代码的正确间距。关于将整个块添加到另一个图的子图中,这可能会带来更多我还没有检查的挑战。你知道吗

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

# Data
n = 20

Main = np.random.randn(n, n)
Left = np.random.randn(n, 1)
Top  = np.random.randn(n, 2)

# Setup
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)

# The top and left axes for images
ax_top = divider.append_axes('top',size='10%',pad=0.0)
ax_left = divider.append_axes('left',size='5%', pad=0.)

# The color bar axes
ax_top_top  = divider.append_axes('top', size='5%',pad=0.1)
ax_left_left = divider.append_axes('left',size='5%', pad=0.1)
ax_right = divider.append_axes('right',size='5%', pad=0.1)


# Main
im_main = ax.imshow(Main)
clrbar_right = plt.colorbar(im_main, cax=ax_right)

# Top
im_top  = ax_top.imshow(Top.T)
ax_top_clrbar = plt.colorbar(im_top, cax=ax_top_top, orientation='horizontal')

# Left
im_left = ax_left.imshow(Left)
ax_left_clrbar = plt.colorbar(im_left, cax=ax_left_left)

# Turn off the axis labels for the images if you like
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax_top.axes.get_xaxis().set_visible(False)
ax_top.axes.get_yaxis().set_visible(False)
ax_left.axes.get_xaxis().set_visible(False)
ax_left.axes.get_yaxis().set_visible(False)

# Switch the ticks for the color bars on the left and the top
ax_left_left.yaxis.tick_left()
ax_top_top.xaxis.tick_top()

plt.show()

相关问题 更多 >