tikzplotlib icon indicating copy to clipboard operation
tikzplotlib copied to clipboard

Legend not displayed for bar plots

Open mkatliar opened this issue 5 years ago • 1 comments
trafficstars

Example:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

ax.bar([1, 2], [3, 4])
ax.bar([1, 2], [2, 5])
ax.legend(['data', 'more data'])

import tikzplotlib
tikzplotlib.save("bar_legend.tex")

TikZ output:

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

\definecolor{color0}{rgb}{0.12156862745098,0.466666666666667,0.705882352941177}
\definecolor{color1}{rgb}{1,0.498039215686275,0.0549019607843137}

\begin{axis}[
legend cell align={left},
legend style={fill opacity=0.8, draw opacity=1, text opacity=1, at={(0.03,0.97)}, anchor=north west, draw=white!80!black},
tick align=outside,
tick pos=left,
x grid style={white!69.0196078431373!black},
xmin=0.51, xmax=2.49,
xtick style={color=black},
y grid style={white!69.0196078431373!black},
ymin=0, ymax=5.25,
ytick style={color=black}
]
\draw[draw=none,fill=color0] (axis cs:0.6,0) rectangle (axis cs:1.4,3);
\draw[draw=none,fill=color0] (axis cs:1.6,0) rectangle (axis cs:2.4,4);
\draw[draw=none,fill=color1] (axis cs:0.6,0) rectangle (axis cs:1.4,2);
\draw[draw=none,fill=color1] (axis cs:1.6,0) rectangle (axis cs:2.4,5);
\end{axis}

\end{tikzpicture}

The legend labels are not present in the TikZ output. The same holds for barh().

mkatliar avatar Mar 18 '20 17:03 mkatliar

I just figured out that a workaround is to use the label parameter in plt.bar() and use legend() without the array argument.

Instead of

ax.bar([1, 2], [3, 4])
ax.bar([1, 2], [2, 5])
ax.legend(['data', 'more data'])

do

ax.bar([1, 2], [3, 4], label='data')
ax.bar([1, 2], [2, 5], label='more data')
ax.legend()

emanuel-metzenthin avatar Sep 08 '20 08:09 emanuel-metzenthin