nschloe / tikzplotlib

:bar_chart: Save matplotlib figures as TikZ/PGFplots for smooth integration into LaTeX.
MIT License
2.42k stars 218 forks source link

Relative axis coordinates #205

Open andreassch opened 7 years ago

andreassch commented 7 years ago

Relative axis coordinates in text objects in matplotlib via transform=plt.gca().transAxes are not taken over in the generated pgfplots figure.

Python code for minimal example:

from matplotlib import pyplot as plt
from matplotlib2tikz import save as tikz_save

plt.plot([0, 10], [0, 10])
plt.text(0.5, 0.5, 'Centered text', transform=plt.gca().transAxes, horizontalalignment='center', verticalalignment='top')
#plt.savefig("matplotlib2tikz_text_relaxiscs.png", dpi=300)
tikz_save("matplotlib2tikz_text_relaxiscs.tikz")
plt.show()

The resulting matplotlib figure is: matplotlib2tikz_text_relaxiscs But the compiled pgfplots figure is: matplotlib2tikz_text_relaxiscs_pgfplots

The generated pgfplots code is:

% This file was created by matplotlib2tikz v0.6.13.
\begin{tikzpicture}

\definecolor{color0}{rgb}{0.12156862745098,0.466666666666667,0.705882352941177}

\begin{axis}[
xmin=-0.5, xmax=10.5,
ymin=-0.5, ymax=10.5,
tick align=outside,
tick pos=left,
x grid style={lightgray!92.026143790849673!black},
y grid style={lightgray!92.026143790849673!black}
]
\addplot [semithick, color0, forget plot]
table {%
0 0
10 10
};
\node at (axis cs:0.5,0.5)[
  scale=0.5,
  anchor=north,
  text=black,
  rotate=0.0
]{\bfseries Centered text};
\end{axis}

\end{tikzpicture}

The expected code in the \node command would be \node at (rel axis cs:0.5,0.5) to respect the relative coordinate system. Moreover, I would not expect the text to be scaled (i.e. no scale=0.5 key).

Dustin1358 commented 4 years ago

Can confirm the bug. Also adding "rel" before the axis solved the issue. For me the scale is 0.7 which looks good.

A fix for me which had no side effects as far as I can see is changing this line: tikz_pos = f"(axis cs:{pos[0]:{ff}},{pos[1]:{ff}})" in _text.py to: tikz_pos = f"(rel axis cs:{pos[0]:{ff}},{pos[1]:{ff}})"

HendrikLamar commented 4 years ago

Probably obvious, but the same error appears with the plt.annotate command as well.