搜索
首页后端开发Python教程图像同时共享x轴和y轴

图像同时共享x轴和y轴

问题内容

我有一张用 imshow 显示的图像。然后我添加所有行并显示最大值。我对列也做同样的事情。在显示图中,我想让图像的 x 轴和 y 轴与添加列的 x 轴和添加行的 y 轴重合。然而,尽管分别设置了 sharexsharey ,但它似乎不起作用。我希望我一次只能做一个:

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
import matplotlib.animation as animation

fig=        plt.figure()
gs=         fig.add_gridspec(2,2, height_ratios=[1, 0.1], width_ratios=[1, 0.1], hspace=0, wspace=0)
ax1=        fig.add_subplot(gs[0,0])
ax2=        fig.add_subplot(gs[1,0], sharex=ax1)
ax3=        fig.add_subplot(gs[0,1], sharey=ax1)
frameNumber= 10
imgs=   []

for i in range(frameNumber):
    np.random.seed(i)
    randomImage= np.random.random((5,5))
    sumX=   np.sum(randomImage, axis=0)
    sumY=   np.sum(randomImage, axis=1)
    dataRange=  np.arange(len(sumX))
    randomDataSet=  np.random.random((10))
    randomMaximalX= argrelextrema(sumX, np.greater)
    randomMaximalY= argrelextrema(sumY, np.greater)

    img1=   ax1.imshow(randomImage, animated=True)
    img2=   ax2.plot(dataRange, sumX,animated=True)[0]
    img3=   ax3.plot(sumY,dataRange,animated=True)[0]
    img4=   ax2.vlines(x=randomMaximalX, ymin=0, ymax=5, animated=True, linestyles="dashed")
    img5=   ax3.hlines(y=randomMaximalY, xmin=0, xmax=5, animated=True, linestyles="dashed")
    imgs.append([img1, img2, img3, img4, img5])
ani=    animation.ArtistAnimation(fig, imgs, interval=1000, blit=False)
plt.show()

当前结果是这样的:

实际上我想要这样的东西:

其中两个图的 h 值相同。非常感谢!


正确答案


有两种方法可以解决此问题:

  1. 使用 axes.pcolormesh 代替 axes.imshow
  2. 或更新相邻图的纵横比。

① 轴.pcolormesh

axes.pcolormesh 不会强制生成的图像为正方形(1:1 纵横比),因此您的单元格将是矩形,但它们会适当地填充所提供的空间。

from numpy.random import default_rng
import matplotlib.pyplot as plt

rng = default_rng(0)
image = rng.uniform(1, 10, size=(5, 5))

mosaic = [
    ['main',   'right'],
    ['bottom', '.'    ],
]

fig, axd = plt.subplot_mosaic(
    mosaic,
    gridspec_kw={
        'height_ratios': [1, .1], 'width_ratios': [1, .1],
        'wspace': .05, 'hspace': .05,
    },
    sharex=true,
    sharey=true,
)

axd['main'].pcolormesh(image)

plt.show()

② 方面更新

如果您想坚持使用 axes.imshow,那么您需要调整 手动调整每个图的纵横比。为了获得正确的比率,您需要 根据提供给 gridspecheight_ratiowidth_ratio 进行计算

from numpy.random import default_rng
import matplotlib.pyplot as plt

rng = default_rng(0)
image = rng.uniform(1, 10, size=(5, 5))

mosaic = [
    ['main',   'right'],
    ['bottom', '.'    ],
]

fig, axd = plt.subplot_mosaic(
    mosaic,
    sharex=True,
    sharey=True,
    gridspec_kw={
        'height_ratios': [1, .1], 'width_ratios': [1, .1],

        # change values to move adjacent plots closer to the main
        'wspace': .05, 'hspace': .05,
    },
)

axd['main'].imshow(image)
axd['main'].set_anchor('SE') # move main plot to bottom-right of bounding-box

# calculate the width and height scales
gs = axd['main'].get_gridspec() # you can also save these values from your `gridspec_kw`
width_scale = gs.get_width_ratios()[0]    / gs.get_width_ratios()[1]
height_scale = gs.get_height_ratios()[0]  / gs.get_height_ratios()[1]

# update the aspect ratios of the adjacent plots
#   set their anchors so they correctly align with the main plot
axd['right'].set_aspect(width_scale, anchor='SW')
axd['bottom'].set_aspect(1/height_scale, anchor='NE')

plt.show()

以上是图像同时共享x轴和y轴的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

阵列的同质性质如何影响性能?阵列的同质性质如何影响性能?Apr 25, 2025 am 12:13 AM

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

编写可执行python脚本的最佳实践是什么?编写可执行python脚本的最佳实践是什么?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy数组与使用数组模块创建的数组有何不同?Numpy数组与使用数组模块创建的数组有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,内存效率段

Numpy数组的使用与使用Python中的数组模块阵列相比如何?Numpy数组的使用与使用Python中的数组模块阵列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模块与Python中的数组有何关系?CTYPES模块与Python中的数组有何关系?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具