【问题标题】:Matplotlib imshow() issues: title on top of top xlabels, and ylabels not aligned in pdfMatplotlib imshow() 问题:顶部 xlabel 顶部的标题和 pdf 中未对齐的 y 标签
【发布时间】:2018-05-22 22:25:47
【问题描述】:

我在使用 matplotlib 中的 imshow() 时遇到了一些问题,特别是从它创建 pdf 时。

我正在处理一个 500x500 矩阵,就这个问题而言,它只是随机值:

np.random.seed(1)
arr = np.array(np.random.random((500, 500)))

行和列都标有不同的名称,但为了这个问题,让我们把它们简单化:

labels = ["Big_Label" if x % 2 == 0 else "Bigger_Big_Label" for x in range(500)]  

所以,我有以下代码来绘制该矩阵:

plt.rc('figure', figsize=(5,5), dpi=500)
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(arr)

# defining the same labels for rows and columns
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
# showing the labels for all the ticks
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
# personalising the ticks. In particular, labels on top
ax.tick_params(axis='both', which='both', labelsize=0.5, length=0)
ax.tick_params(axis='x',which='both', labelbottom='off', labeltop='on')
ax.tick_params(axis='both', pad=1)
# vertical labels
for label in im.axes.xaxis.get_ticklabels():
    label.set_rotation(90)

plt.colorbar(im)
plt.title("Just a Big Title With Words")

# Removing outer lines because they hide part of the lines/columns
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

plt.savefig("fig.pdf")
plt.show() 

第一个问题是标题,因为它位于 xlabels 之上:

第二个问题是,当缩放以查看 ylabels 和 xlabels 时,它们没有对齐。关于左边的标签,当我专门编码ax.tick_params(axis='both', pad=1)时,它们和情节之间有不同的空间;如果我在 IDE 或终端中执行此 python 代码,则不会发生此问题(它们都接近情节)。所以我猜想把这张图片放入pdf时会发生什么?关于这两个标签,您可以看到它们与实际的行和列不对齐;例如,顶部的第二个标签在蓝色和橙色方块的中间,此时它应该与橙色方块的中间对齐:

最后,我尝试在plt.savefig() 之前调用fig.autofmt_xdate(),但结果更糟,因为顶部标签完全没有对齐:

你能帮我解决这个问题吗?我知道你必须放大才能看到标签,但对于我拥有的真实矩阵来说,这是必要的。我还告知我正在使用 matplotlib 1.5;由于与其他工具的兼容性问题,我无法使用 2.x

【问题讨论】:

  • 你能试试plt.tight_layout()吗?
  • 我在plt.savefig("fig.pdf") 之前调用了那个方法 结果在这里:imgur.com/a/yK0Th 结果更奇怪,因为方块的颜色发生了变化(我每次都使用相同的种子,所以方块'颜色不应该改变),对齐问题仍然存在
  • @ImportanceOfBeingErnest 对不起,你是对的。这是一个我忘记纠正的错误。我相应地编辑了我的问题
  • 我提交了an issue 关于我可以重现的问题部分。对于其余部分,我担心如果它仅存在于 matplotlib 1.5 中,则几乎无能为力。

标签: python python-3.x matplotlib


【解决方案1】:

有一个用于自动移动标题的 PR。应包含在 v2.2(2 月时间范围)https://github.com/matplotlib/matplotlib/pull/9498 中,另一个用于标题填充 https://github.com/matplotlib/matplotlib/pull/9816。所以我们正在努力。

至于您在 PDF 中的标签未对齐,如果labelsize 小于 1.0,则标签对齐似乎存在错误,所以不要这样做:https://github.com/matplotlib/matplotlib/issues/9963 这是一个错误,但我想一个低- 第一优先。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2015-09-29
    • 1970-01-01
    相关资源
    最近更新 更多