[Tex/LaTex] How to manually specify the ticks for the colorbar with matlab2tikz

matlab2tikzpgfplots

I have a matlab script, which creates some compound plot. When I export the figure using matlab2tikz, the manual ticks of the colorbar are lost.
Even if I try extraAxisOptions to do it manually, matlab2tikz inserts its colorbar code after my extraAxisOptions, thus my settings are overridden.

How can I set manual ticks for the colorbar?

Below are is the matlab and latex code as an example. Further below are two images demonstrating my problem. While matlab obeys my manual ticks for the colorbar, these are lost in translation. The output of latex uses default ticks for the colorbar.

figure(1)
hold off
plot(0:0.1:pi/2,sin(0:0.1:pi/2),'b')
hold on
grid on
plot(0:0.1:pi/2,cos(0:0.1:pi/2),'r')

hcb=colorbar('location','NorthOutside')
set(hcb,'XTick',[20,30,40,50])
xlabel(hcb, 'Water flow rate in L/min')


matlab2tikz('foo.tikz',...
    'extraAxisOptions',{'colorbar style={xtick={20,30,40,50}}'})

this is the latex code:

\documentclass[tikz]{standalone}
\usepackage{tikz,pgfplots,pgfkeys}
\pgfplotsset{compat=newest}

\begin{document}

\input{foo.tikz}

\end{document}

The result is
The matlab figure

and the latex output
enter image description here


The relevant section of the produced tikz code is listed below:

\begin{tikzpicture}
\begin{axis}[%
ymajorgrids,
colorbar style={xtick={20,30,40,50}},
colormap/jet,
colorbar horizontal,
colorbar style={at={(0.5,1.03)},anchor=south,xticklabel pos=upper,xlabel={Water flow rate in L/min}},
point meta min=0,
point meta max=1
]

Best Answer

It would appear (to me at least) that matlab2tikz does something not quite right here, so I would recommend that you post an issue at GitHub anyway.


That said, to fix the pgfplots code, you need to do two changes:

  1. Move the xtick setting of the colorbar to after the colorbar horizontal key, as you've already mentioned.

  2. Change point meta max to 64 (maybe, don't really know what Matlab used, but it looked similar)

point meta max defines the maximum value for the colorbar, which you can see from your image is 1 in the pgfplots version, and something else in Matlab.

enter image description here

\documentclass[tikz,border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}
\begin{tikzpicture}
\begin{axis}[%
ymajorgrids,
colormap/jet,
colorbar horizontal,
colorbar style={at={(0.5,1.03)},anchor=south,xticklabel pos=upper,xlabel={Water flow rate in L/min}},
colorbar style={xtick={20,30,40,50}}, % this was moved down
point meta min=0,
point meta max=64, % change from 1  
% the following line is just for this example, so remove it for your own code
xmin=0,xmax=1.5,samples at={0,0.25,...,1.5},xtick={0,0.5,1,1.5}
]

\addplot {rnd};
\addplot {rnd};
\end{axis}
\end{tikzpicture}
\end{document}