16

How do I plot a function of a binary logarithm with TikZ? Say that I want to plot f(x) = log_2 x.

  • 1
    You should look at the pgfplots package (page 33). It's much better than tikz for plots and it can use the external program gnuplot! – Spike Jun 1 '11 at 12:05
  • 1
    @Spike The problem is that I don't find a command for binary logarithms for TikZ or gnuplot. Also you don't need pgfplots to call gnuplot from TikZ. – N.N. Jun 1 '11 at 12:30
  • Do you need the horizontal axis in semi-log scale? :) – xport Jun 2 '11 at 16:17
19

The pgfmath function that you can use directly in TikZ is called log2. PGFplots uses the fpu library, which doesn't have this function, but you can get the same result by using ln(x)/ln(2) instead:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}[scale=0.7]
\draw [help lines] (0,-4) grid [step=1] (10,4);
\draw (0,0) -- (10,0);
\draw plot [domain=0.1:10,samples=100] (\x,{log2(\x)});
\draw plot [domain=0.1:10,samples=100] (\x,{log2(\x)});
\end{tikzpicture}

\vspace{1cm}

\begin{tikzpicture}[trim axis left]
\begin{axis}[domain=0:10,
  samples=100,
  enlarge x limits=false,
  grid=both,
  no markers,
  axis equal]
\addplot +[thick] {ln(x)/ln(2)};
\end{axis}
\end{tikzpicture}
\end{document}

log2

  • I get ! Package PGF Math Error: Unknown function log2'.` from the top graph (using log2()). Maybe it's my TikZ version (2008/02/13 v2.00 (rcs-revision 1.27)). – N.N. Jun 1 '11 at 14:09
  • @N.N. Yes, v. 2.0 is outdated, you should upgrade to the current version 2.1 – Jake Jun 1 '11 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.