5

How do I plot a function of a logarithm with PGFplots? Say that I want to plot y=log_3(x). I have a simple Latex code for function y=log_2(x), but I don't know how I can write function of a logarithm with base 3 and others values of base.

Here is Latex code

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\begin{document}
\begin{tikzpicture}
\begin{axis}[grid=both,
          xmax=10,ymax=4,
          axis lines=middle,
          enlargelimits]
\addplot[latex-latex,smooth,black,mark=none,%samples=140,
line width=1.5pt,domain=-3.5:9.5,
samples=63,
color=red]  {log2(x)} node[above left] {$y=\log_2(x)$};
\end{axis}
\end{tikzpicture}
\end{document} 

Here is a graphic of the function

enter image description here

If someone knows how to solve this problem and show it through the example, I'll be grateful.

3
  • 4
    This is more a math question, log_3(x)=log_2(x)/log_2(3). So just do \addplot[latex-latex,smooth,black,mark=none,%samples=140, line width=1.5pt,domain=-3.5:9.5, samples=63, color=blue] {log2(x)/log2(3)} node[above] {$y=\log_3(x)$};.
    – user121799
    Aug 2, 2018 at 21:25
  • 1
    @current_user, i'm not sure, that all member of this site understand your comment :-). better is stay at official language of site (čeprav je mnogokrat lažje po domače).
    – Zarko
    Aug 2, 2018 at 21:49
  • 1
    Related to tex.stackexchange.com/questions/200316/…
    – Cragfelt
    Aug 2, 2018 at 22:48

2 Answers 2

5
\documentclass[border=5pt,tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\begin{document}
\begin{tikzpicture}
\begin{axis}[grid=both,
          xmax=10,ymax=4,
          axis lines=middle,
          enlargelimits]
\addplot[latex-latex,smooth,black,mark=none,%samples=140,
line width=1.5pt,domain=-3.5:9.5,
samples=63,
color=red]  {ln(x)/ln(3)} node[above left] {$y=\log_3(x)$};
\end{axis}
\end{tikzpicture}
\end{document} 

Here is the output:

enter image description here

3

As mentioned in the comment and by current_user, you only have to apply basic logarithm relations. One can actually define a function for this with

\tikzset{declare function={Log(\n,\x)=log2(\x)/log2(\n);}}

The MWE thus becomes

\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\tikzset{declare function={Log(\n,\x)=log2(\x)/log2(\n);}}
\begin{tikzpicture}
\begin{axis}[grid=both,
          xmax=10,ymax=4,
          axis lines=middle,
          enlargelimits,xmax=12.5]
\pgfplotsinvokeforeach{2,3,10}
{
\addplot+[latex-latex,smooth,mark=none,
line width=1.5pt,domain=-3.5:9.5,
samples=63]  {Log(#1,x)} node[right] {$\log_{#1}(x)$};
}
\end{axis}
\end{tikzpicture}
\end{document} 

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .