【问题标题】:Plotting difference between two images with matplotlib/seaborn使用 matplotlib/seaborn 绘制两个图像之间的差异
【发布时间】:2018-04-01 01:31:45
【问题描述】:

我正在尝试绘制两个我修补过的 1000x1000 图像之间的差异。 MWE 如下(右上角和左下角是这些图像):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import matplotlib.ticker as tck
import seaborn as sns
import numpy

sns.set(style='dark')

imagen2 = plt.figure(1, figsize=(5, 5))
imagen2.suptitle('StackOverflow Matplotlib colorbar demo')

dat = numpy.random.randn(1000, 1000)
top_left = plt.subplot(221)
top_left.imshow(dat)

top_right = plt.subplot(222, sharex=top_left, sharey=top_left)
top_right.imshow(dat)

bottom_left = plt.subplot(223, sharex=top_left, sharey=top_left)
bottom_left.imshow(dat)

bottom_right = plt.subplot(224, sharex=top_left, sharey=top_left)
# problem_plot = bottom_right.imshow(dat)
# plt.colorbar(problem_plot, fraction=0.045, pad=0.04)
problem_plot = sns.heatmap(dat)
problem_plot.xaxis.set_major_locator(tck.MultipleLocator(200))
problem_plot.xaxis.set_major_formatter(tck.ScalarFormatter())
problem_plot.yaxis.set_major_locator(tck.MultipleLocator(200))
problem_plot.yaxis.set_major_formatter(tck.ScalarFormatter())

plt.tight_layout(rect=(0, 0, 1, 0.95))

plt.show()

matplotlib 的imshow 很容易保存为 PDF(尽管颜色条存在一些对齐和大小问题)。 但是,seaborn 的 heatmap 以牺牲大量矢量的 PDF 为代价解决了这个问题:使用 ps2pdf14 -dPDFSETTINGS=/prepress 压缩后为 6.2MB 与 3.7MB。

有没有其他有效的方法来绘制这个同时保留 seaborn 的美学优势?

【问题讨论】:

  • 我不清楚你喜欢右下角的什么情节。是彩条吗?旋转的 x 轴标签?
  • 对我来说不清楚为什么你会突然只在最后一个子图上使用 seaborn 图?似乎如果您只使用与其他三个绘图相同的 imshow,则不会出现文件大小问题。所以这就是这里的解决方案,不是吗?
  • @OscarBenjamin - 如果我用imshow 绘制它,我必须手动对齐和调整颜色条的大小(参见示例中的注释行),它仍然不完美。
  • @ImportanceOfBeingErnest - 是的,我可以使用imshow,但我想问问社区是否还有其他可能性。
  • 是的,总是有“其他可能性”。但究竟是为了什么?

标签: python matplotlib seaborn


【解决方案1】:

我想要做的是有一个热图,它不会将每个单元格呈现为单独的矢量对象。即我希望对热图进行光栅化,就像 imshow 对数组所做的那样。

seaborn's heatmap 在幕后使用matplotlib's pcolormesh(这隐藏在其文档的一角)。它有一个可选的 Bool 参数 rasterized,这正是我想要的。

我将heatmap 调用编辑为如下所示:

problem_plot = sns.heatmap(dat, rasterized=True)

性能

使用time caffeinate python stackoverflow.py、Python 3.6.5(来自 Homebrew)、MacOS Sierra 10.12.6 测量。

matplotlib 的imshow:2.4MB pdf 未压缩,1.1MB 压缩后。

real    0m2,089s
user    0m1,797s
sys     0m0,211s

seaborn 的 heatmap w/o rasterized:未压缩 23.8MB pdf,压缩后 7.5MB。而且它仍然需要大量加载(尝试在 pdf.js 查看器中执行它以查看它呈现 热图的每个单元格)。

real    4m36,585s
user    4m27,727s
sys     0m3,512s

seaborn 的 heatmap w/rasterized:未压缩 2.5MB pdf,压缩后 1.2MB(与 imshow 大致相同)。

real    0m3,306s
user    0m2,932s
sys     0m0,313s

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多