5

See this example code:

\documentclass{article} 
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\begin{document}
  \begin{tikzpicture}
    \begin{axis}[
                 xmin=-0.1,
                 xmax=1.1,
                 ymin=-1.1,
                 ymax=1.1,
                 domain=0:1,
                 samples=30
                ]
      \addplot[blue] {sqrt(x)};
      \addplot[purple] {-sqrt(x)};
    \end{axis}
  \end{tikzpicture}
\end{document}

The result appears acceptable far from zero, but near zero it's too much undersampled:

result of the above code

Increasing samples value makes the plot nice, but it considerably slows down processing. As a workaround I could just plot the inverse in a parametric plot (i.e. (y^2,y)), but in my actual code it'd require quite a bit of additional work.

Is there a way to provide a custom sampling function or specify different density of samples in different parts of the domain?

1 Answer 1

10

samples and domain can be used as plot options and you can repeat same function for several domains. This is not a solution but more a workaround. An example is shown as upper part (orange+blue) in following graph.

Another option (suggested by percusse) consists in specifying samples with samples at option. This options follows a foreach (TikZ - pgffor) syntax. An example is shown as lower part (purple) below.

enter image description here

\documentclass{article} 
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\begin{document}
  \begin{tikzpicture}
    \begin{axis}[
                 xmin=-0.1,
                 xmax=1.1,
                 ymin=-1.1,
                 ymax=1.1,
                 domain=0:1,
                % samples=30
                ]
      \addplot[blue, domain=0:.2,samples=30] {sqrt(x)};
      \addplot[orange, domain=0.2:1,samples=10] {sqrt(x)};
      \addplot[purple, samples at={0,0.005,...,0.1,0.15,...,1}] {-sqrt(x)};
    \end{axis}
  \end{tikzpicture}
\end{document}
5
  • Looks like a viable workaround, but still only a workaround. What if the function is more complicated? Do I necessarily have to copy&paste it?
    – Ruslan
    Mar 8, 2016 at 8:49
  • 1
    Or you can go about it with samples at={0,0.005,...,0.1,0.15,...,1}
    – percusse
    Mar 8, 2016 at 8:51
  • @percusse this looks like a completely another answer. If you posted it, I think I'd accept it.
    – Ruslan
    Mar 8, 2016 at 11:24
  • @Ruslan. I've included percusse's solution.
    – Ignasi
    Mar 8, 2016 at 14:51
  • It is my pleasure
    – percusse
    Mar 8, 2016 at 15:05

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.