【问题标题】:Matplotlib: align bar plots with imgshow once on x axis and once on y axisMatplotlib:在 x 轴和 y 轴上将条形图与 imgshow 对齐一次
【发布时间】:2021-03-24 14:01:30
【问题描述】:

我正在尝试绘制一个显示沿 x 和 y 轴的像素强度总和的图。

目前我有以下代码:

def example():
    import matplotlib.pyplot as plt
    from matplotlib.gridspec import GridSpec
    
    ## <not under my control>
    
    np.random.seed(1455)
    
    width = 5
    height = 8
    
    sample = np.random.rand(height,width)
    
    x_hist = np.sum(sample, axis=0)
    y_hist = np.sum(sample, axis=1)
    
    ## </not under my control>
    
    fig = plt.figure()
    gs = fig.add_gridspec(2, 2)
    ax_joint  = fig.add_subplot(gs[1, 0])
    ax_marg_x = fig.add_subplot(gs[0, 0],sharex=ax_joint)
    ax_marg_y = fig.add_subplot(gs[1, 1],sharey=ax_joint)
    
    ax_joint.imshow(sample, cmap="Reds") 
    
    ax_marg_x.bar(range(width),x_hist)
    ax_marg_y.barh(range(height),y_hist)
    
    plt.show()

产生以下结果:

但是,上方条形图和图像的 x 轴具有相同的限制,但未缩放或对齐 图像和右侧条形图之间也有很大的差距。

我想要的结果是这样的:

【问题讨论】:

  • 在imshow中使用aspect="auto"?
  • 那只是拉伸图像,我宁愿保留图像,使每个像素都是正方形

标签: python matplotlib


【解决方案1】:

如 cmets 中所述,将纵横比更正为自动,并将图形的大小设置为纵向。另外,使每个之间的间距变窄。

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

np.random.seed(1455)

width = 5
height = 8

sample = np.random.rand(height,width)

x_hist = np.sum(sample, axis=0)
y_hist = np.sum(sample, axis=1)

fig = plt.figure(figsize=(6,8))
gs = fig.add_gridspec(2, 2, hspace=0.1, wspace=0.1)
ax_joint  = fig.add_subplot(gs[1, 0])
ax_marg_x = fig.add_subplot(gs[0, 0],sharex=ax_joint)
ax_marg_y = fig.add_subplot(gs[1, 1],sharey=ax_joint)

ax_joint.imshow(sample, cmap="Reds", aspect='auto') 

ax_marg_x.bar(range(width),x_hist)
ax_marg_y.barh(range(height),y_hist)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多