nschloe/tikzplotlib

Wrong grayscale colorbars

qwenger opened this issue · 0 comments

Python code:

import numpy as np
import matplotlib.pyplot as plt
import tikzplotlib

x = np.linspace(0.0, 1.0, 50)
y = np.linspace(0.0, 1.0, 50)
x_2d, y_2d = np.meshgrid(x, y)
z = np.where((0.25 <= x_2d), 1.0, 0.0)

fig, ax = plt.subplots()
im = ax.imshow(z, origin="lower", cmap="binary", vmin=0.0, vmax=1.0)
fig.colorbar(im)

tikzplotlib.save("out.tex")

TeX output:

% This file was created with tikzplotlib v0.10.1.
\begin{tikzpicture}

\definecolor{darkgray176}{RGB}{176,176,176}

\begin{axis}[
colorbar,
colorbar style={ylabel={}},
colormap/blackwhite,
point meta max=1,
point meta min=0,
tick align=outside,
tick pos=left,
x grid style={darkgray176},
xmin=-0.5, xmax=49.5,
xtick style={color=black},
y grid style={darkgray176},
ymin=-0.5, ymax=49.5,
ytick style={color=black}
]
\addplot graphics [includegraphics cmd=\pgfimage,xmin=-0.5, xmax=49.5, ymin=-0.5, ymax=49.5] {out-000.png};
\end{axis}

\end{tikzpicture}

out-000.png:

out-000

When exporting a colormap, if it is gray (https://github.com/texworld/tikzplotlib/blob/main/src/tikzplotlib/_axes.py#L678) it will always be exported as pgf's blackwhite.

However, this is wrong in most cases - it mostly only works for matplotlib colormaps gray and gist_gray.

matplotlib's is_gray() checks whether all three color components have always the same value. So any colormap containing only gray scales - in whichever order - will be converted to blackwhite, which is incorrect in general. In particular, the colormap binary gets reversed output.

Workaround for now: use a colormap with a bit of color, such as bone_r.

Proper fix: do not assume any predefined pgf colormap such as blackwhite for gray scales matplotlib colormaps, except maybe for gray and gist_gray. Others should be exported along the standard path, color by color.