python - 调整单个子图宽度的简单方法?

标签 python matplotlib

aspect='equal' 为长向量绘制几乎一条线,而 ='auto' 将其绘制为矩阵,这也是不需要的。如何强制 vec 显示为 SMALLVEC?我见过相关的 SO,但它们都相当冗长,并且在我的应用程序中添加了很多代码 - 是否有一些简短的内容,例如 ax.set_width()?优选地,ax来自plt.subplots()axes

<小时/>

<小时/>

代码:

import matplotlib.pyplot as plt
import numpy as np

KWS = dict(weight='bold', fontsize=14)

def plot_auto(mat, vec):
    fig, axes = plt.subplots(1, 2)
    plt.suptitle("AUTO", **KWS)
    axes[0].imshow(mat, aspect='auto')
    axes[1].imshow(vec, aspect='auto')
    plt.show()

def plot_equal(mat, vec):
    fig, axes = plt.subplots(1, 2)
    plt.suptitle("EQUAL", **KWS)
    axes[0].imshow(mat, aspect='auto')
    axes[1].imshow(vec, aspect='equal')
    plt.show()

def plot_smallvec(smallvec):
    plt.imshow(smallvec)
    plt.title("SMALLVEC", **KWS)

np.random.seed(0)
mat = np.random.randn(500, 500)
vec = np.random.randn(500, 1)
smallvec = np.random.randn(25, 1)

plot_auto(mat, vec)
plot_equal(mat, vec)
plot_smallvec(smallvec)

最佳答案

归功于@ImportanceOfBeingErnest建议使用 aspect 的第三个选项参数(num)。我认为如果您想匹配不同形状数组生成的方面,包含通用公式可能会很有用。公式为

(reference.shape[0] / reference.shape[1]) / (target.shape[0] / target.shape[1])

其中 reference 是您希望匹配其绘制方面的数组,target 是要使用匹配方面绘制的数组。将此包含在您的示例代码中,

# ...
def plot_equal(mat, vec, smallvec):
    fig, axes = plt.subplots(1, 2)
    plt.suptitle("EQUAL", **KWS)
    axes[0].imshow(mat, aspect='auto')
    axes[1].imshow(vec, aspect=(smallvec.shape[0] / smallvec.shape[1]) / 
                   (vec.shape[0] / vec.shape[1]))
    plt.show()

# ...
plot_equal(mat, vec, smallvec)

给予

enter image description here

<小时/>

注意   -   此公式可能会因图形的其他变化而崩溃,但在示例代码的范围内它可以正常工作。

关于python - 调整单个子图宽度的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60045811/

相关文章:

python - 使用 TensorFlow 在 google colab 上同时使用 CPU 和 GPU

python - 有什么方法可以使用 vscode 在绘图查看器中显示交互式绘图吗?

python - 如何在matplotlib中先绘制线,最后绘制点

Python 日志记录 : how to represent newlines in the format string in a logging config file?

python - 如何正确使用 python 访问系统命令并使我的脚本工作?

python - matplotlib 内联 Python 2.7 %

python - 具有自定义渐变着色的单堆积条形图

python - 我怎样才能在轴上绘制

python - 在 Python 的 sqlite3 模块中,为什么 cursor.rowcount() 不能告诉我 select 语句返回的行数

java - 适用于 Android 应用的 Kivy 和 Java 之间的区别