tikzplotlib icon indicating copy to clipboard operation
tikzplotlib copied to clipboard

Rectangle patch and colorbar are missing in tikz file

Open albflo opened this issue 4 years ago • 2 comments

Hi,

currently I struggle to export a matplotlib (v3.1.0) plot with tikzplotlib (v0.8.2) to tikz. I made simple example of a plot with two rectangles with different colors and a colorbar. The resulting tikz plot doesn't show both rectangles and additional the colorbar and its ticks are missing.

python code

import matplotlib as mpl
import matplotlib.pyplot as plt
import tikzplotlib as tikz

plt.style.use('ggplot')
plt.rc('text', usetex=True)
plt.rc('font', family='serif')

fig = plt.figure()
axes = fig.add_subplot(111, aspect='equal')
axes.set_xlabel('$x$ axis')
axes.set_ylabel('$y$ axis')

c = [0, 1]
norm = mpl.colors.Normalize(vmin=c[0], vmax=c[-1])
cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.viridis)
cmap.set_array([])

box0 = mpl.patches.Rectangle(xy=(0.1, 0.1), width=0.2, height=0.2,
                             color=cmap.to_rgba(0))
axes.add_patch(box0)

box1 = mpl.patches.Rectangle(xy=(0.6, 0.6), width=0.2, height=0.2,
                             color=cmap.to_rgba(1))
axes.add_patch(box1)

cbar = fig.colorbar(cmap, ticks=c)
cbar.set_label('$z$ axis')

tikz.save('test.tex')

plt.show()

output tex

here it's already visible that the two rectangles and colorbox are missing

% This file was created by tikzplotlib v0.8.2.
\begin{tikzpicture}

\definecolor{color0}{rgb}{0.267004,0.004874,0.329415}
\definecolor{color1}{rgb}{0.993248,0.906157,0.143936}

\begin{axis}[
axis background/.style={fill=white!89.80392156862746!black},
axis line style={white},
tick align=outside,
tick pos=left,
x grid style={white},
xlabel={\(\displaystyle x\) axis},
xmajorgrids,
xmin=0, xmax=1,
xtick style={color=white!33.33333333333333!black},
y grid style={white},
ylabel={\(\displaystyle y\) axis},
ymajorgrids,
ymin=0, ymax=1,
ytick style={color=white!33.33333333333333!black}
]
\end{axis}

\end{tikzpicture}

expected pgfplot

Figure_1

let me know if I can help somehow!

albflo avatar Sep 11 '19 09:09 albflo

Caused by these lines:

https://github.com/nschloe/tikzplotlib/blob/cd04740b0125b2ecd8c3d0f4aee9958ff762ccda/tikzplotlib/_patch.py#L116-L122

eric-wieser avatar Jan 10 '20 12:01 eric-wieser

Because I also stumbled over missing rectangles, I had a quick look through the code, but basically the comment of @eric-wieser contains everything necessary for a quick hack. So until it is fixed elsewhere, a hacky workaround is possible by giving your rectangle the _nolegend_ label. So you would have to call

box0 = mpl.patches.Rectangle(xy=(0.1, 0.1), width=0.2, height=0.2,
                             color=cmap.to_rgba(0), label='_nolegend_')

It might cause some side effects but at least for me it was working and good enough to get the figures ready for my paper ;)

senselessDev avatar Mar 17 '21 18:03 senselessDev