6

In the following diagram, Graph of a function partitioned into three subintervals which is generated by the following TikZ code,

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{figure}[h] \centering
\begin{tikzpicture}[scale=2,
    % function
    declare function={ f(\x) = pow(\x,4)/16-pow(\x,3)/4+1.1*\x+0.5; },
    % styles
    faint/.style={thin, gray},
    normal/.style={thin, black}]
% axes
\draw [thick, ->] (0, 0) -- (0, 5);
\draw [thick, ->] (0, 0) -- (4.5, 0);
\foreach \x/\xstr/\ystr in {0.6/$a = x_1$\kern 21pt/$f(a) = y_1$, 2.0/$x_2$/$y_2$, 3.3/$x_3$/$y_3$, 3.8/$\kern 19pt x_4 = b$/$f(b) = y_4$} {
    % partitions (x-axis, y-axis)
    \draw [faint] (\x, {f(\x)}) -- (\x, 0) node [normal, below, text height=8pt] {\xstr};
    \draw [faint] (\x, {f(\x)}) -- (0, {f(\x)}) node [normal, left] {\ystr};
    % points
    \fill (\x, {f(\x)}) circle (1pt);
}
% curve
\draw [thick, <->, domain=-0.5:4, samples=50] plot(\x, {f(\x)});
\end{tikzpicture}
\end{figure}

\end{document}

I use \kern to offset the labels $a = x_1$ and $x_4 = b$ so that the $x$ is always directly under the partition lines on the graph. This seems hacky, and I think there ought to be a better way, like how I can insert an & in an align environment to make text align to a particular character.

So is there a better way?

  • 1
    Welcome to TeX.SX! – Adam Liter May 29 '15 at 18:05
5

You can also use \phantom for that since the amount of shift is not constant hence not worth automating. But instead I would go about with pgfplots.

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\begin{document}
\begin{tikzpicture}[declare function={f(\x)=pow(0.5*\x,4)-pow(\x,3)/4+1.1*\x+0.5;}]
\begin{axis}[
  axis lines*=middle,
  xtick={0.6,2,3.3,3.8},ytick=data,
  xticklabels={$a=x_1\phantom{a=}$,$x_2$,$x_3$,$\phantom{{}=b}x_4=b$},
  yticklabels={$f(a)=y_1$,$y_2$,$y_3$,$f(b)=y_4$},
  typeset ticklabels with strut]

\addplot[only marks,samples at={0.6,2,3.3,3.8}] {f(x)};
\addplot[thick, <->, domain=-0.2:4, samples=50] {f(x)};
\pgfplotsextra{
  \foreach\x in{0.6,2,3.3,3.8}{
    \draw[thin, gray] (\x,0) |- (0,{f(\x)});
  }
}
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

  • Perfect! \phantom was exactly what I was looking for. (I will probably not use pgfplots because the diagram actually has more components, which I removed from the MWE.) For future visitors, note that a small amount of spacing is lost when you use phantom unless you include a placeholder, like: a=x_1\phantom{{}=a} and \phantom{b={}}x_4=b. – Radon Rosborough May 29 '15 at 19:56
  • Alternatively, you could write, $\llap{$x={}$}x_1$. Or if you load the mathtools package, $\mathllap{x={}}x_1$. – A.Ellett May 29 '15 at 21:11

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.