【问题标题】:imshow colormap figure and the suptitle don't align in the centerimshow colormap figure 和 suptitle 不在中心对齐
【发布时间】:2017-08-08 16:34:06
【问题描述】:

这是一个很小的问题,但我仍然无法弄清楚。 我正在使用 imshow 和 matplotlib 来绘制颜色图 - 但结果是图形和标题没有对齐:

我用于绘图的代码是:

fig, ax = plt.subplots(figsize=(27, 10))

cax1 = ax.imshow(reversed_df, origin='lower', cmap='viridis', interpolation = 'nearest', aspect=0.55)

ylabels = ['0:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00']
major_ticks = np.arange(0, 24, 3)
ax.set_yticks(major_ticks)
ax.set_yticklabels(ylabels, fontsize = 15)

xlabels = ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan17']
xmajor_ticks = np.arange(0,12,1)
ax.set_xticks(xmajor_ticks)
ax.set_xticklabels(xlabels, fontsize = 15)
fig.autofmt_xdate()

fmt = '%1.2f'
cb = plt.colorbar(cax1,fraction=0.046, pad=0.04, format=fmt)
cb.update_ticks

fig.suptitle('2016 Monthly Pressure Data (no Normalization) $[mbar]$',fontsize=20, horizontalalignment='center')

fig.savefig('Pressure 2016 Full.jpeg', dpi=300)
plt.show()

有什么想法吗?

谢谢!

【问题讨论】:

    标签: python matplotlib imshow


    【解决方案1】:

    当轴纵横比设置为 "equal"imshow 绘图就是这种情况)并添加了颜色条时,会出现此问题。

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.random.rand(5,5)
    fig, ax = plt.subplots(figsize=(12, 3))
    fig.patch.set_facecolor('#dbf4d9')
    
    im = ax.imshow(x)
    
    fig.colorbar(im)
    plt.show()
    

    一种解决方法是设置子图参数leftright,使图像位于中心。这可能需要一些试验和错误,但工作原理如下:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.random.rand(5,5)
    fig, ax = plt.subplots(figsize=(12, 3))
    plt.subplots_adjust(left=0.2, right=0.68)
    fig.patch.set_facecolor('#dbf4d9')
    
    im = ax.imshow(x)
    
    fig.colorbar(im)
    plt.show()
    

    【讨论】:

    • 这是唯一的解决方案吗?有没有办法让整个情节自动居中?
    • @CMCDragonkai 我添加了一个替代解决方案。
    【解决方案2】:

    我无法使用上述方法;可能是因为我另外在 PyQt5 中绘图。

    如果其他人在这里被难住了,我最终在不同的链接上使用了公认的解决方案来解决这个问题 (Matplotlib 2 Subplots, 1 Colorbar)。只需为一个情节设置它,然后为该情节添加cbar_ax。您仍然需要稍微调整一下数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多