• How to name a string variable inside a \foreach loop using the loop variable
    by Plum Rapson on October 4, 2026 at 3:42 pm

    I am trying to simplify my document typing for schoolwork. For ODEs, we are asked to show multiple possible solutions for a given differential equation. I have been using TikZ, pgfplots, and a dash of audacity to place multiple functions on the same graph, changing either the value of y_0 or C or both to show different function outcomes. However, this takes up a lot of space and time, so I am hoping that I could define a new command to repeatedly \addplot with slightly different functions. Here's what I have so far, including the page setup and relevant preamble for a sanity check: \documentclass[12pt]{article} \usepackage{geometry} %I have my page set to weird sizes and small margins \usepackage{pgfplots} \usepackage{tikz} \usetikzlibrary{shapes.geometric,arrows.meta,calc,pgfplots.external} \pgfplotsset{compat=1.18} \usepackage{xstring} \newcommand{\addmultiplot}[3][2]{ %{sample}{variable}{equation} where sample is a number %determined by my own organization, variable is %the character variable to be changed, equation is %formatted exactly as it would in \addplot \IfEqCase{#1}{ {0.1}{ \def\a{-0.9} \def\b{-0.1} \def\c{0.1} \def\d{0.4} \def\e{0.75} \foreach \x in {\a, \b, \c, \d}{ \StrSubstitute{#3}{#2}{\x}[\NAME] \def\nums{\a, \b, \c, \d, \e} %%%% Haven't been able to test, want this to give me \nums = {-0.9, -0.1, 0.1, 0.4, 0.75} } } {2}{ \def\a{-10} \def\b{-5} \def\c{2} \def\d{5} \def\e{10} \foreach ... } } . . . [] }; \foreach \v in {\nums} {\addplot{\NAME}};} \begin{document} \begin{tikzpicture} \begin{axis}[xticks =\empty, yticks= \empty] \addmultiplot{2}{C}{3*(C)/((C) + exp(3*x^2)*(3 - (C)))}; \end{axis} \end{tikzpicture} \end{document} What I am struggling with is [\NAME], Where I would want something like eq\x so that the last line of the command sees nums as {-0.9, -0.1, 0.1, 0.4, 0.75} and outputs \addplot{eq-0.9}; \addplot{-0.1}; etc. Maybe trying to have the negative sign be a part of it would be a problem, but I haven't even gotten there yet. At first I had [eq\x], but it gave me a \def issue "please don't put \def cs {...} use \def\cs{...}" on the line where I called \addmultiplot, and after trimming things down and making sure all the numbers were going into clearly defined variables, I'm left with assuming it involves the names of my equations, but surely [\eq\x] would not result in the first string later being referred to by "eq-0.9" so that when the final \foreach looks at \nums and pulls -0.9, \addplot can receive the equation that has C replaced with -0.9.

  • use newline in f:write
    by flawr on September 28, 2026 at 10:08 pm

    I'd like to create a data file using lua in LuaTeX that I can reuse e.g. using pgfplots. But currently I'm stuck printing multiple lines as it seems the "\n" will always get interpreted as a TeX command and not as a newline. How would we correctly do that in this document? \documentclass{article} \usepackage{pgfplots} \usepackage{luacode} \begin{document} \begin{luacode} local f = io.open("data.txt", "w") for x = 0, 10, 0.5 do local y = math.sin(x) f:write(x .. " " .. y .. "\n") end f:close() \end{luacode} \begin{tikzpicture} \begin{axis} \addplot table {data.txt}; \end{axis} \end{tikzpicture} \end{document}

  • Controlling what appears in front in a 3d pgfplot
    by James on July 12, 2026 at 6:00 pm

    I'm trying to make a nice diagram to illustrate partial derivatives for my multivariable class. I have the graph of a function, a plane, the intersection of these in the graph, a tangent line, and some guide lines to show what's occurring, but (presumably because of the order in which they appear in the code) the diagram doesn't respect what object is behind a different object, i.e., the graph is drawn on top of the plane, or the plane is drawn on top of the graph, even though they ``should'' pass through one another. Is there any nice way to make whatever ``should'' be on top be drawn on top without manually finding intersections and having different domains/clip regions for different features? My code so far is below, along with the image that is produced \begin{standalone} \usepackage{tikz} \usepackage{pgfplots} \begin{document} \begin{tikzpicture} \begin{axis}[axis lines = center, xmin = 0, xmax = 3, ymin = 0, ymax = 3, view = {100}{30}, xlabel = {$x$}, ylabel = {$y$}, zlabel = {$z$}, xtick=\empty, ytick=\empty, ztick=\empty, ] % Using f(x,y) = 2 - (x-2)^3 - (y-1.5)^2 %graph \addplot3[ domain =1:3, y domain = 0.5:2.5,surf,colormap/viridis, opacity=0.9] {-(x-2)^3 - (y-1.5)^2 + 2}; %plane \draw[fill = blue!90, color = blue, opacity = 0.3] (2,0,0)--(2,3,0)-- (2,3,3) node[black, above, opacity = 0.9] {$x=a$}--(2,0,3)--cycle ; %intersection of line and plane \addplot3[domain = 0.5:2.5, blue, samples y = 1, thick] ({2},{x},{2 - (2-2)^3 - (x-1.5)^2}); %tangent line \addplot3[black, thick, domain = -1:1.23] ({2},{x+1},{-2*(1-1.5)*x + 2 - (1-1.5)^2}); %point of tangancy \draw[fill = black] (2,1, {2 - (1-1.5)^2}) circle (2pt); %guide lines for point \draw[dashed, thick] (2,0,0)--(2,1,0) node[below] {$(a,b,0)$}--(0,1,0); \draw[dashed, thick,] (2,1,0) -- (2,1,{2 - (1-1.5)^2}); \end{axis} \end{tikzpicture} \end{document}

  • Slope Field Uniform Plot
    by Nick B on February 16, 2026 at 11:36 am

    I am trying to create slope fields based on several examples I have seen on here. My issue is that when I change my equation (the slope field I want to draw) my image does not appear to be square. I would like it uniform. The uniformity changes based on what function I plot. Is there a way to fix this? The image attached is from AP Classroom. Note the uniformity all the way around and how it is square, or flush. that is what I am looking for. \documentclass{standalone} \usepackage{pgfplots} \usetikzlibrary{arrows.meta} \pgfplotsset{compat=1.18} \begin{document} \centering \begin{tikzpicture} \begin{axis}[ view={0}{90}, axis lines=middle, axis equal image, width=10cm, xmin=-5.5, xmax=5.5, ymin=-5.5, ymax=5.5, xtick={-4,-2,2,4}, ytick={-4,-2,2,4}, xlabel=$x$, ylabel=$y$, axis line style={thick, -{Triangle[scale=1.2]}}, clip=false ] \addplot3[ thick, color=red, declare function={ f(\x,\y) = \x; norm(\x,\y) = sqrt(1 + (f(\x,\y))^2); }, quiver={ u={1/norm(x,y)}, v={f(x,y)/norm(x,y)}, scale arrows=0.4, every arrow/.append style={-} }, % -------------------------------- samples=15, domain=-4.2:4.2, domain y=-4.2:4.2 ] {0}; \end{axis} \end{tikzpicture} \end{document}

  • Iterated plot with TikZ, PGFPlots and foreach loop
    by Dominique on November 5, 2025 at 4:31 pm

    I'm trying to plot an illustration of the fixed point method in which a function is evaluated repeatedly in a loop. The result should be a staircase or spiral plot on top of the plot of the function itself. I've read here about the use of \edef inside a foreach loop. The following MWE should show what I'm trying to do, but it seems to only perform a single iteration. Notes: the loop variable isn't used inside the loop. perhaps it's an illusion that only single iteration is performed and the real issue is that \xprev and \xnext aren not updated at each pass through the loop. I tried placing the updates inside the \edef, but that gives an undefined control sequence error. I also tried \pgfplotsinvokeforeach instead of \foreach, but only obtained other errors. \documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \pgfmathdeclarefunction{g}{1}{\pgfmathparse{#1^2 - 2}} \begin{tikzpicture} \begin{axis} [ xmin = -2.5, xmax = 2.5, ymin = -3, ymax = 3, axis x line = center, axis y line = center, domain=-2.5:2.5, samples=300, ] \addplot[ultra thick] {g(x)}; % graph of g \addplot[thin] {x}; % diagonal \def\xstart{-0.75} \pgfmathsetmacro{\xprev}{\xstart}; \pgfmathsetmacro{\xnext}{g(\xprev)}; \draw[thick, blue] (\xstart, 0) -- (\xstart, \xnext) -- (\xnext, \xnext); \foreach \i in {1, 2, 3}{ \pgfmathsetmacro{\xprev}{\xnext} \pgfmathsetmacro{\xnext}{g(\xprev)} % x <- g(x) \edef\plotoneiter{% \noexpand% \draw[thick, blue] ({\xprev}, {\xprev}) -- ({\xprev}, {\xnext}) -- ({\xnext}, {\xnext}); }\plotoneiter% } \end{axis} \end{tikzpicture} \end{document} Thanks in advance for any hints! EDIT: Here is a quick sketch of what I'm trying to achieve:

  • How to use `tkz-euclide` with `pgfplots`
    by Mr.Hedge on April 17, 2025 at 12:56 am

    Is there any way to make tkz-euclide compatible with pgfplots axis environment? Here is my code example where I want to add mark using \tkzMarkSegment but more often I want to find some line intersections or draw circles. Interestingly, simple \tkzLabelPoint works. \documentclass[tikz, margin=3mm]{standalone} \usetikzlibrary{ arrows.meta, positioning, } \usepackage{tkz-euclide} \usepackage{pgfplots} \usepackage[dvipsnames,table]{xcolor} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis}[ xmin=-2.9, xmax=15.9, ymin=-3.9, ymax=15.9, xtick distance=1, ytick distance=1, xticklabels=\empty, yticklabels=\empty, extra y ticks={1}, extra y tick labels={$1$}, extra x ticks={1}, extra x tick labels={$1$}, axis lines=middle, axis line style={-Stealth}, xlabel={$X$}, ylabel={$Y$}, xlabel style={at={(ticklabel* cs:1)}, anchor=north east, font=\footnotesize}, ylabel style={at={(ticklabel* cs:1)}, anchor=north west, font=\footnotesize}, grid=both, grid style={dotted, gray!50}, set layers, clip mode=individual, axis equal image=true, % scale only axis, % unit vector ratio=2,1, ] \coordinate (A) at (axis cs:2,8); \coordinate (B) at (axis cs:10,2); \coordinate (S) at (axis cs:6,5); \draw[thick, black] (A)--(B); \draw[black, fill=black] (A) circle(1.5pt) (B) circle(1.5pt); \tkzLabelPoint[above left](A){$A$} \tkzLabelPoint[below right](B){$B$} \addplot [name path = A,domain=-2:15, samples=2, thick, color=Red] {4/3*x-3} node[pos=0.8, sloped, above, font=\footnotesize]{$y=\frac{4}{3}x-3$}; \draw[Green, fill=Green] (S) circle(1.5pt); \tkzMarkSegment[mark=|, pos=0.5](S,B) \end{axis} \end{tikzpicture} \end{document}

  • Graphs of 1/|x| and sin(1/x) does not look good
    by Timo Chang on December 15, 2024 at 5:16 am

    I draw the graph of 1/|x| with the code: \begin{tikzpicture}[>=latex, scale=0.3] \draw[->] (-5,0)--(5,0)node[right]{$x$}; \draw[->] (0,-1)--(0,9)node[right]{$y$}; \draw [domain=-5:-1/8, samples=500, thick] plot (\x, {-1/(\x)}); \draw [domain=1/8:5, samples=500, thick] plot (\x, {1/(\x)}); \fill[black] (0,3) circle (4pt); \end{tikzpicture} But the resulting picture looks like this: As you can see, it is not symmetric at the highest point. I wonder what causes this happen? And how can we fix this? A similar problem also happens when I draw the graph of sin(1/x): \begin{tikzpicture}[>=latex, scale=1.5] \draw[->] (-2,0)--(2,0)node[right]{$x$}; \draw[->] (0,-2)--(0,2)node[right]{$y$}; \draw [domain=-1:-0.03, samples=1000, thick] plot (\x, {sin(1/(\x) r)}); \draw [domain=0.03:1, samples=1000, thick] plot (\x, {sin(1/(\x) r)}); \end{tikzpicture} The resulting picture is: The problem is that it doesn't look "smooth" when getting close to x=0. Is there a way to fix this?

  • How derive the projection of the curve intersection with specific x-axis notation in pgfplots?
    by Explorer on June 11, 2024 at 4:42 pm

    I encounter a confusing problem when deal with the projection of the function figure as below. I wonder how to modify my tex code's definition of \ShowIntersectionsAndVerticalLine with 4 arguments: name path global1 name path global2 the color of the intersection the notation of the x-axis (as in the figure x_1 x'_1 etc.). I found similar brilliant answer as below, but they didn't fit my case. Intersection -| of a named and a calculated coordinate TiKz-pgf: Project intersection points in the abscissa axis What I want to get is shown below: Here below is my MWE of the problem. \documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \usetikzlibrary{intersections} \usetikzlibrary{math} \usepackage{amsmath} \tikzset{elegant/.style={smooth,thick,samples=50}} % Define this as a command to ensure that it is same in both cases \newcommand*{\ShowIntersection}[3]{ \fill [name intersections={of=#1 and #2, name=i, total=\t}] [#3, opacity=1, every node/.style={above left, black, opacity=1}] \foreach \s in {1,...,\t}{(i-\s) circle (1pt)}; } \begin{document} \begin{tikzpicture} \begin{axis}[ axis x line = middle, axis y line = middle, xmin = -1, xmax = 4, ymin = -1, ymax = 3 ] \addplot[elegant,domain=-4:4,name path global=A]{(x-1)*ln(x)-x+1} node [left=2pt] {$f(x)$}; \addplot[blue,mark=*,mark size=1pt] coordinates {(1,0)}; \addplot[blue,mark=*,mark size=1pt] coordinates {(e,0)}; \addplot[blue,thick,name path global=B]{-x+1}; \addplot[blue,thick,name path global=C]{(1-1/e)*x-e+1}; \addplot[orange,thick,name path global=D] coordinates {(-1,0.5) (4,0.5)}; \ShowIntersection{A}{D}{orange} \ShowIntersection{B}{D}{blue} \ShowIntersection{C}{D}{blue} %% TBC \end{axis} \end{tikzpicture} \end{document}

  • Drawing a line graph
    by TKR on August 15, 2023 at 5:47 am

    For an unknown reason the code doesn't compile. \begin{figure} \centering \begin{tikzpicture} \begin{axis}[ xlabel=Month, ylabel=Rainfall (mm), ymin=80, ymax=450, date coordinates in=x, xticklabel style={rotate=45, anchor=near xticklabel}, xticklabel={\month}, date ZERO=2021.12.31, % reference date xtick={ 2022-01-01, 2022-02-01, 2022-03-01, 2022-04-01, 2022-05-01, 2022-06-01, 2022-07-01, 2022-08-01, 2022-09-01, 2022-10-01, 2022-11-01, 2022-12-01 }, xticklabel style={/pgf/number format/1000 sep=,rotate=45,anchor=north east}, ] \addplot coordinates { (2022-01-01, 81.9) (2022-02-01, 70) (2022-03-01, 104.9) (2022-04-01, 276.2) (2022-05-01, 311.6) (2022-06-01, 201.5) (2022-07-01, 132.5) (2022-08-01, 108.5) (2022-09-01, 248.8) (2022-10-01, 399.1) (2022-11-01, 362.4) (2022-12-01, 165.1) }; \end{axis} \end{tikzpicture} \caption{Average Monthly Total Rainfall} \end{figure}

  • pgfplots: 3D Axes System. Reverse xlabel
    by Dr. Manuel Kuehner on November 3, 2022 at 2:48 am

    This question is about a 3D coordinate system in pgfplots. Problem 1: I want to have the xlabel on the "other side" (tried x dir = reverse, already). Problem 2: This is less important (nice to have). I want to have the perspective as in my hand drawing (a perfect cross: y and z, and the 3rd dimension, depth, is indicated by a 45 degree line: x), see "Remark" in the hand drawing. Additional Remark: In the hand drawing I use different labels (this is a typical automotive coordinate system). But I can fake that by just naming the xlabel "y" and so on. \documentclass{standalone} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis}[ width = 80mm, height = 80mm, axis lines = center, no marks, axis line style = {latex-latex, ultra thick}, % unit vector ratio = 1 1 1, ticks = none, xmin = -1, xmax = 1, ymin = -1, ymax = 1, zmin = -1, zmax = 1, xlabel = $x$, ylabel = $y$, zlabel = $z$, ] % No plot \end{axis} \end{tikzpicture} \end{document} Related pgfplots: `x dir = reverse` --> Problem with x-label (`xlabel`) placement

  • How draw Bezier path with tikZ?
    by Saku on September 30, 2022 at 11:55 pm

    How draw Bezier path like this with tikz? This patch is x(1-x-y) I saw similar : https://tikz.net/torus/ How to use \addplot3 ?

  • Beamer theme Metropolis changes TikZ draw
    by rake on August 11, 2022 at 11:04 pm

    I am having trouble adding a TikZ graphic to my Beamer presentation which uses the theme Metropolis. Here is an example of the issue: \documentclass{beamer} \usepackage[utf8]{inputenc} \usepackage{pgfplots} %\usetheme{metropolis} \pgfplotsset{compat=1.18} \begin{document} \begin{frame} \begin{center} \begin{tikzpicture} \begin{axis}[ view = {135}{20}, xlabel=$x$, ylabel=$y$, zlabel=$z$, xmin=-1, xmax=1, ymin=-1, ymax=1, zmin=0, zmax=1, ] \draw (0, 1, 0) -- (1, 1, 1); \end{axis} \end{tikzpicture} \end{center} \end{frame} \end{document} This code does what I want, but uncommenting the line \usetheme{metropolis} changes the graphic and makes the line shorter. (I don't think it's invisible, just a very small length.) How can I get the desired image while still using the Metropolis theme?

  • Plot differential equation trajectories of a 3-system
    by Zaragosa on April 3, 2022 at 10:19 pm

    I was reading about drawing differential equation trajectories with latex, but I wonder... is there a way to graph this? Consider the system x'=-y+xz^2 y'=x+yz^2 z'=-z(x^2+y^2) The following image I have taken from Perko's book Differential Equations and Dynamical Systems

  • How to make multiple pgfplots share legend and Y label, retaining same size and ability to reference each plot?
    by Lars Kakavandi-Nielsen on August 25, 2021 at 7:01 am

    For some time now I have been trying to have two (or more) plots made with pgfplot side by side (figure below shows my goal for three), with the leftmost plot having the ylabel, the centre having the legend above it (or in case of an even number of plots having the legend centred between the two middle once). Finally, I would like for each plot to have a referencable label and caption (besides the xlabel) However, the plot with the ylabel and the one with the legend always gets smaller (due to the added graphics of the label and the legend, I know) and I have not been able to find a solution to the issue. Is there a way to achieve what I want? Below is the normal way I add three plots using subfigure: \documentclass{report} \usepackage{pgfplots} \pgfplotsset{compat=newest} \usepackage{subcaption} \begin{filecontents}{data.csv} X,Y,Z,N 0,1,2,3 1,2,3,4 2,3,4,5 4,4,5,6 \end{filecontents} \begin{document} \begin{figure} \centering \begin{subfigure}[t]{.3\textwidth} \centering \begin{tikzpicture} \begin{axis}[ylabel=DATA TEXT, width=.95\textwidth] \addplot+ table[x=X, y=Y, col sep=comma] {data.csv}; \end{axis} \end{tikzpicture} \caption{\label{fig:y} Shows Y} \end{subfigure}~ \begin{subfigure}[t]{.3\textwidth} \centering \begin{tikzpicture} \begin{axis}[width=.95\textwidth, legend style={at={(0.5,1.5)},anchor=north,legend columns=2}] \addplot+ table[x=X, y=Z, col sep=comma] {data.csv}; \legend{DATA} \end{axis} \end{tikzpicture} \caption{\label{fig:z} Shows Z} \end{subfigure}~ \begin{subfigure}[t]{.3\textwidth} \centering \begin{tikzpicture} \begin{axis}[width=.95\textwidth] \addplot+ table[x=X, y=N, col sep=comma] {data.csv}; \end{axis} \end{tikzpicture} \caption{\label{fig:n} Shows N} \end{subfigure} \end{figure} \end{document}

  • Shade between two cartesian lines and a polar curve
    by leogcam on August 23, 2021 at 12:56 pm

    I'm trying to shade the area between two cartesian lines (the two blue lines in the plot below) and a polar curve (the squiggly curve in the plot below). Using the fill command, I was only able to shade part of the area I wanted. I want to shade all the way to the origin, not just the section that is shaded now. Here is my current code: \documentclass[twocolumn, notitlepage, 11pt]{article} \usepackage[utf8]{inputenc} \usepackage{tikz} \usepackage{titling} \usepackage{pgfplots} \usepgfplotslibrary{polar} \usepgfplotslibrary{fillbetween} \setlength{\droptitle}{-12em} \pagenumbering{gobble} \pgfplotsset{width=12cm,compat=1.9} \begin{document} \begin{tikzpicture} \begin{axis}[ axis lines = left, xmin = 0, xmax = 1.25, ymin = 0, ymax = 1.25, yticklabels={,,}, xticklabels={,,} ] \addplot[color=red, domain=0:1,samples=100,smooth,ultra thick] {tan(20)*x} node[above,pos=1] {$\theta=\alpha$}; \addplot[name path = squiggle, color=black, data cs = polar, domain=0:90,smooth, ultra thick] {.15*sin(10*x-40) + .75} node[above, pos=0] {$r=f(\theta)$}; \addplot[name path = a, color=cyan, domain=0:1,samples=100,smooth,ultra thick] {tan(40)*x} node[above,pos=1] {$\theta=\theta_{i-1}$}; \addplot[name path = b, color=cyan, domain=0:.6,samples=100,smooth,ultra thick] {tan(60)*x} node[above,pos=1] {$\theta=\theta_i$}; \addplot[color=purple, domain=0:.2,samples=100,smooth,ultra thick] {tan(80)*x} node[above,pos=1] {$\theta=\beta$}; \addplot [domain=40:60, samples=30, smooth, black, ultra thick, fill=blue!40, data cs = polar] {.15*sin(10*x-40) + .75}; \end{axis} \end{tikzpicture} \end{document}

  • Alignment of pgfplots inside subfloats when using tikzplotlib
    by Marvin Noll on December 4, 2020 at 10:58 pm

    I'm using the tikzplotlib code below to generate two Plots. I then place them in two subfloats. As you can see in the final latex output, the figure looks rather ugly with the two plots differently sized and not aligned. What can i do to achieve the same size of the plots and to align them properly. Maybe worth noting, i have several of these figures with multiple subfloats in my document. Python: import matplotlib.pyplot as plt import tikzplotlib import numpy as np x1=np.arange(0,10)*10e9 x2=np.arange(0,1000) y1=np.random.randn(1,len(x1))[0] y2=0.01*x2*np.random.randn(1,len(x2))[0] KIT_green=(0/255,150/255,130/255) KIT_blue=(70/255,100/255,170/255) plt.figure() plt.plot(x2,y2,label="second trace",color=KIT_green) plt.xlabel(r"Time $t$ (in \si{\milli\second})") plt.ylabel(r"Amplitude $S_{11}$ \\ (some measurement) \\ (and another meaningless line) (in \si{\volt})"); tikzplotlib.save("subfigs_left.tikz",extra_axis_parameters=["ylabel style={align=center}"],axis_width="5cm",axis_height="5cm") plt.figure() plt.plot(x1,y1,label="first trace",color=KIT_blue) plt.xlabel(r"Time $t$ (in \si{\milli\second})") plt.ylabel(r"Amplitude $S_{11}$, $S_{35}$ (in \si{\volt})"); tikzplotlib.save("subfigs_right.tikz",extra_axis_parameters=["ylabel style={align=center}"],axis_width="5cm",axis_height="5cm") LaTeX: \documentclass[11pt]{article} \usepackage[utf8]{inputenc} \usepackage{graphicx} \usepackage{subfig} \usepackage{siunitx} \usepackage{tikz} \usepackage{pgfplots} \usepackage{tikzscale} \begin{document} \begin{figure} \centering \subfloat[Plot 1: this shows this]{\includegraphics[width=0.4\textwidth]{subfigs_left.tikz}} \qquad \subfloat[Plot 2: and this shows that. But this explanation is quite long. blablabla]{\includegraphics[width=0.4\textwidth]{subfigs_right.tikz}} \caption{Two plots} \label{fig:subfig} \end{figure} \end{document}

  • Best practice for plots (pgfplots, gnuplot, etc.)
    by burny on July 27, 2020 at 8:44 am

    I am writing a fairly large article with a lot of different plots. They range from simple ones like abs(x) or x^2 to high-polynomials with their first and second derivative, and nonlinearities (sigmoid, tan, etc.). Sometimes they are also in 3 dimensions. I am using pgfplot within tikzpicture and then gnuplot. For the easy plots, this is straightforward. However, the more complex plots (that may include non-continuity points), the gnuplot expression becomes harder and harder to understand and maintain. For some plots, I need randomly created points anyway (created once, and then fixed), which need to be "classified" according to a function. For all plots, I have (or could create) Python scripts to output a coordinates table that would be possible to use within the pgfplot table import functionality. This may seem overkill for x^2 but is really necessary for the more complex plots. And with the higher polynomials, I don't have to do the derivates manually. This works for plots that are points or lines in 2D but not in 3D because the number of points for the imported table exceeds LaTeX's memory (x and y have 1000 samples each, which results in 1,000,000 coordinates). As I have the functions in Python anyway, I could also use matplotlib (or seaborn, etc.) to create pdfs with the plot. This has the disadvantage that the plots do not look like they would when drawing with LaTeX/gnuplot (different colors, styles, etc.), so I would have to maintain the styles in two different places. Is there a best practice for this type plotting? I want one type of plot (either only gnuplot or only Python) and not a mixture of different methods.

  • Tikz/pgfplots shade to origin (polar)
    by Donnie Nathan Chad on October 27, 2019 at 4:54 am

    I'm trying to shade in just one petal of a polar function. Specifically, I was wondering if there was a way to shade in the bounded region that lives between my two rays: I've tried searching for examples elsewhere but most of the ones I've seen involve either shading in a region bounded by two curves or shading in the area under a function y=f(x). \documentclass[border=5pt]{standalone} \usepackage{pgfplots} \begin{document} \begin{tikzpicture} \begin{axis}[ smooth, trig format plots=rad, axis lines=middle, axis equal] \addplot [domain=0:pi, samples=150, red] ({2*sin(5*x)*cos(x)}, {2*sin(5*x)*sin(x)}); \draw [-stealth, ultra thick, dashed, draw=blue] (axis cs: 0,0) -- ++(canvas polar cs: radius=3cm,angle=0); \draw [-stealth, ultra thick, dashed, draw=blue] (axis cs: 0,0) -- ++(canvas polar cs: radius=4cm,angle=deg{pi/5}); \end{axis} \end{tikzpicture}% \end{document} Any feedback would be greatly appreciated!

  • How can I draw tangents at inflection points automatically?
    by minhthien_2016 on June 17, 2019 at 3:36 am

    The function f(x) = \frac{x^4}{12}-\frac{2x^3}{3}+\frac{3 x^2}{2} has two inflection points x = 1 and x = 3. I draw the tangents at the above points by hand. \documentclass[tikz,border=3.14mm]{standalone} \usepackage{pgfplots} \pgfplotsset{compat=1.16} \usepgfplotslibrary{fillbetween} \begin{document} \begin{tikzpicture}[>=latex] \begin{axis}[ xtick={-2,-1,...,5}, xticklabel=\empty, ytick={-2,-1,...,5}, yticklabel=\empty, grid=major, axis x line=center, axis y line=center, xlabel={$x$}, ylabel={$y$}, xlabel style={below}, ylabel style={left}, xmin=-2, xmax=5, ymin=-2, ymax=5] \addplot[color=blue,smooth,samples=501, thick,domain=-5:5] {(3* x^2)/2 - (2 *x^3)/3 + x^4/12}; \addplot[color=purple,smooth,samples=501, thick,domain=-5:5] {-(5/12) + (4 *x)/3}; \addplot[color=red,smooth,samples=501, thick,domain=-5:5] {9/4}; \end{axis} \end{tikzpicture} \end{document} How can I draw the tangents at inflection points of every function automatically

  • How can I repair incorrect tangents at the points on the curve?
    by minhthien_2016 on June 16, 2019 at 2:21 pm

    Let be the function f(x) = -(1/162) x^5 + 17/162 x^4 - 43/162*x^3 - 179/162*x^2 + 212/81* x + 134/81 The solutions of the equation f'(x) = 0 are x=-2\lor x=1\lor x=4\lor x=\frac{53}{5} I tried to draw the tangents at the points x = -2, x = 1 and x = 4. I got the incorrect result. My code \documentclass[tikz,border=3.14mm]{standalone} \usepackage{pgfplots} \pgfplotsset{compat=1.16} \usepgfplotslibrary{fillbetween} \usetikzlibrary{intersections} \makeatletter \def\parsenode[#1]#2\pgf@nil{% \tikzset{label node/.style={#1}} \def\nodetext{#2} } \tikzset{ add node at x/.style 2 args={ name path global=plot line, /pgfplots/execute at end plot visualization/.append={ \begingroup \@ifnextchar[{\parsenode}{\parsenode[]}#2\pgf@nil \path [name path global = position line #1-1] ({axis cs:#1,0}|-{rel axis cs:0,0}) -- ({axis cs:#1,0}|-{rel axis cs:0,1}); \path [xshift=1pt, name path global = position line #1-2] ({axis cs:#1,0}|-{rel axis cs:0,0}) -- ({axis cs:#1,0}|-{rel axis cs:0,1}); \path [ name intersections={ of={plot line and position line #1-1}, name=left intersection }, name intersections={ of={plot line and position line #1-2}, name=right intersection }, label node/.append style={pos=1} ] (left intersection-1) -- (right intersection-1) node [label node]{\nodetext}; \endgroup } } } \makeatother \begin{document} \begin{tikzpicture}[>=latex] \begin{axis}[ grid, %axis y line =none, %axis x line =none, axis x line=center, axis y line=center, xtick=\empty, ytick=\empty, %xtick={-5,-4,...,5}, %ytick={-5,-4,...,5}, xlabel={$x$}, ylabel={$y$}, xlabel style={below}, ylabel style={left}, xmin=-5.5, xmax=5.5, ymin=-5.5, ymax=5.5, tangent/.style={ add node at x={#1}{ [ sloped, append after command={(\tikzlastnode.west) edge [thick,black] (\tikzlastnode.east)}, minimum width=0.2\textwidth ] } }] \addplot[color=blue,smooth,samples=500, thick,tangent/.list={-2,1,4},domain=-5:5] {-(1/162)*pow(\x,5)+17/162*pow(\x,4)-43/162*pow(\x,3)-179/162*pow(\x,2)+212/81*\x+134/81}; \end{axis} \end{tikzpicture} \end{document}

  • Graphic in Latex document
    by chri11 on December 15, 2018 at 9:56 am

    i would like to have a function in my document. It shall be f(x)=0 für 0<=x<2.5 and g(x)=1 for 2.5<=x<5 and i might put another h(x)=2. I tried to plot it with the \addplot command but i dont like the looking with the quadratic system of coordinates. Is their any extern program to create something and put it into texmaker? Edit: i tried this here: \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{pgfplots} \begin{document} \begin{figure} \centering \begin{tikzpicture} \begin{axis}[xmin=0, xmax=10, ymin=0, ymax=4] \addplot[thick] {{0}}; \addplot[thick] {{1}}; \end{axis} \end{tikzpicture} \end{figure} \end{document} The first thing is that the graphic is above the text i put before i dont know why. Then i dont want it to be so quadratic and not closed on the upper and right side. And i dont even know how to really put the conditions in there so function g(x) starts where f(x) ends and so on. I dont know if all of this is possible in there :/. Thanks

  • Rotate 3D plot to top down view
    by Philipp on May 26, 2018 at 1:01 pm

    I have a function with 2 parameters that, when plotted in 3D, is rotated in such a way that a part of the surface is hidden: \begin{tikzpicture}[ declare function={ func(\x, \y) = ((\x<10) * (\x/10) + (\x>=10)) * ((\y<=30) * (\y/30) + (\y>30) * (1- (\y-30)/((\y-30)+3))); } ] \begin{axis}[ colormap name=whitered, axis z line=middle, xmin=0, xmax=50, xlabel=$d$, ymin=0, ymax=30, ylabel=$v$, zmin=0, zmax=1.1, zlabel=$\overline{f}$ ] \addplot3[domain=0:50, y domain=0:30, samples=50, surf] {func(\x, \y)}; \end{axis} \end{tikzpicture} To prevent this I would like to plot it from a "top-down" view and then rely purely on colors to indicate the value of the function. How can this be done?

  • Tikz isn't plotting the right function
    by John 545 on November 17, 2017 at 11:29 pm

    Im trying to plot a probability function in tikz, but the line plotted isn't even close to how the function should look. Im new to using latex and I have no idea why this isnt working, unless tikz just cant handle this function. Here is my code: \documentclass{article} \usepackage{pgfplots} \usepackage{tikz} \begin{document} \begin{tikzpicture}[ declare function={Probability(\n,\k) = 1-((\n!)/((\n^(\k))*((\n- \k)!)));} ] \begin{axis}[ no markers, domain=0:15, samples=2500, axis lines=left, xlabel=$k$, ylabel=$y$, every axis y label/.style={at=(current axis.above origin),anchor=east}, every axis x label/.style={at=(current axis.right of origin),anchor=north}, height=10cm, width=15cm, xtick={0,2,4,6,8,10,12,14}, ytick={0.1,0.2,0.3,0.4,0.5,.6,.7,.8,.9,1}, enlargelimits=false, clip=false, axis on top, grid = major, xmax=15 ] \addplot [very thin,cyan!20!black] {Probability(10,x)}; \end{axis} \end{tikzpicture} \end{document} This is what the function should look like, And this is what tikz is plotting I would appreciate it if someone could point me in the right direction. Thanks

  • Decorations using \draw inside axis environment
    by Jukka Aho on September 12, 2016 at 9:04 pm

    I'm trying to draw vectors normal to curved surface using pgfplots. Here's my MWE and result: \documentclass[tikz,margin=5pt]{standalone} \usetikzlibrary{decorations.markings} \usepackage{pgfplots} \pgfplotsset{compat=newest} \tikzset{test/.style={ postaction={decorate}, decoration={ markings, mark=between positions 0.0 and 0.1 step 0.01 with { \draw[-latex] (0,0) -- (0,-5); } } } } \begin{document} \begin{tikzpicture} \begin{axis}[ xmin=0, ymin=0, xmax=50, ymax=50, unit vector ratio*=1 1 1] \addplot[smooth cycle, test] coordinates { (0.0, 0.0) (20.0, 15.0) (40.0, 30.0) (0.0, 40.0)}; \end{axis}; \end{tikzpicture} \end{document} If I however change axis limits, for example setting \begin{axis}[ xmin=-20, ymin=0, xmax=50, ymax=50, unit vector ratio*=1 1 1] I get the following output: I also get similar behavior by setting some data coordinates to negative values, for example \addplot[smooth cycle, test] coordinates { (0.0, 0.0) (20.0, 15.0) (40.0, 30.0) (-20.0, 40.0)}; The question is how to properly use \draw to decorate inside pgfplots axis environment?

  • pgfplots: percentage in matrix plot
    by Gustav on April 20, 2016 at 2:05 pm

    I'm trying to draw a matrix plot with the shown values in percentage. I already tried: nodes near coords = {\pgfmathprintnumber\pgfplotspointmeta\%} Unfortunately this didn't work out. Here is my code: \documentclass[border=3pt]{standalone} \usepackage{pgfplots} \pgfplotsset{width=5cm, height=18cm, compat=1.13, colormap={blackwhite}{gray(0cm)=(1); gray(1cm)=(0.5)}, xticklabels={LPIBG, ALL, HPIBG }, xtick={0,...,2}, ytick=\empty } \begin{document} \begin{tikzpicture} \begin{axis}[enlargelimits=false, nodes near coords = {\pgfmathprintnumber\pgfplotspointmeta\%}, xlabel style={font=\footnotesize}, ylabel style={font=\footnotesize}, legend style={font=\footnotesize}, xticklabel style={font=\footnotesize}, yticklabel style={font=\footnotesize}, colorbar, colorbar style={ ytick={0,20,40,60,80,100}, yticklabels={0,20,40,60,80,100}, yticklabel={\pgfmathprintnumber\tick\%}, yticklabel style={font=\footnotesize}}, point meta min=0, point meta max=100, every node near coord/.append style={xshift=0pt,yshift=-7pt, black, font=\footnotesize}, ] \addplot[ matrix plot, nodes near coords, mesh/cols=3, point meta=explicit] table[meta=C]{ x y C 0 0 80 1 0 36 2 0 40 0 1 64 1 1 80 2 1 60 0 2 52 1 2 84 2 2 72 0 3 72 1 3 28 2 3 32 0 4 56 1 4 84 2 4 80 0 5 72 1 5 52 2 5 44 0 6 4 1 6 84 2 6 41 0 7 37 1 7 69 2 7 84 0 8 63 1 8 53 2 8 82 0 9 78 1 9 74 2 9 39 0 10 39 1 10 63 2 10 88 0 11 76 1 11 74 2 11 49 0 12 39 1 12 6 2 12 88 0 13 46 1 13 33 2 13 75 0 14 88 1 14 67 2 14 54 0 15 79 1 15 83 2 15 75 0 16 50 1 16 46 2 16 71 0 17 92 1 17 71 2 17 75 0 18 46 1 18 33 2 18 8 }; \end{axis} \end{tikzpicture} \end{document}

  • Draw closed section of sphere using pgfplots
    by Zac on November 15, 2014 at 2:50 pm

    I want to draw a section of a sphere to represent its volume. I have currently got the following: \documentclass{article} \usepackage{pgfplots} \pgfplotsset{compat=1.11} \begin{document} \begin{tikzpicture} \begin{axis}[ axis equal, axis lines = center, width = 10cm, height = 10cm, xlabel = {$x$}, ylabel = {$y$}, zlabel = {$z$}, view/h=45, ] \addplot3[surf, opacity = 0.5, samples=21, domain=0:1, y domain=0:0.5*pi, z buffer=sort] ({sqrt(1-x^2) * cos(deg(y))}, {sqrt( 1-x^2 ) * sin(deg(y))}, x); \end{axis} \end{tikzpicture} \end{document} Which gives me: But I want the sides to be closed, something like this: How can I do this?

  • Special decoration for TikZ pin feature
    by Chris on June 15, 2014 at 9:37 am

    I try to achieve the curvy pin style I sketched below. It would help to distinguish pin lines from grid and other lines in the diagram. How can I realize a decoration that automatically draws such a curve? How can I integrate this with the pin feature? The code for the picture: \documentclass[tikz,convert]{standalone} \usepackage{pgfplots} \begin{document} \begin{tikzpicture}[ pin distance=5mm, every pin edge/.style={ decorate, decoration={ snake, pre length=4pt } } ] \begin{axis}[ width=12cm, height=5cm, xmin=0,xmax=4, ] \addplot coordinates {(1,1) (3,3)} coordinate [pos=.5] (a) coordinate [pos=.7] (b); \node [pin=135:From the manual] at (a) {}; \path (a) ++(-45:1cm) node (c) {What I want}; \draw [gray] (c) to[out=110,in=-70] (a); \path (b) ++(-45:.8cm) node [right] (d) {What I want II}; \draw [gray] (d.west) to[out=160,in=-20] (b); \end{axis} \end{tikzpicture} \end{document} (I tagged with pgfplots as well since this would be a common application.)

  • Add arrow to 3D pgfplot
    by s__C on December 3, 2013 at 3:30 pm

    How to add an arrow (cf red arrows below) in a 3D plot (or 2D plot should be similar) in pgfplots ? The arrow has not to be specifically aligned with the label but could be placed closer to the axis.

  • plotting two time series with bounds
    by gVermandel on February 5, 2013 at 11:17 pm

    I've two times series (y_h, y_f) with a lower and upper bound (confidence interval). I'd like to plot all of them on the same picture. I've succeeded in plotting y_h with upper and lower bounds, but i fail when i add y_f and its bounds. (btw I want to fill in grey between the upper and lower bound) I can't find the trick to make it work, i'd be very pleased if anyone had the solution. \documentclass{standalone} \usepackage{pgfplots, tikz} \usepackage{pgfplotstable} \pgfplotstableread{ temps y_h y_h__inf y_h__sup y_f y_f__inf y_f__sup 1 0.237340 0.135170 0.339511 0.237653 0.135482 0.339823 2 0.561320 0.422007 0.700633 0.165871 0.026558 0.305184 3 0.694760 0.534205 0.855314 0.074856 -0.085698 0.235411 4 0.728306 0.560179 0.896432 0.003361 -0.164765 0.171487 5 0.711710 0.544944 0.878477 -0.044582 -0.211349 0.122184 6 0.671241 0.511191 0.831291 -0.073347 -0.233397 0.086703 7 0.621177 0.471219 0.771135 -0.088418 -0.238376 0.061540 8 0.569354 0.431826 0.706882 -0.094382 -0.231910 0.043146 9 0.519973 0.396571 0.643376 -0.094619 -0.218022 0.028783 10 0.475121 0.366990 0.583251 -0.091467 -0.199598 0.016664 }{\table} \begin{document} \begin{tikzpicture} \begin{axis} % y_h \addplot [stack plots=y, fill=none, draw=none, forget plot] table [x=temps, y=y_h__inf] {\table} \closedcycle; \addplot [stack plots=y, fill=gray!20, draw opacity=0, area legend] table [x=temps, y expr=\thisrow{y_h__sup}-\thisrow{y_h__inf}] {\table} \closedcycle; \addplot [stack plots=false, very thick,smooth,blue] table [x=temps, y=y_h] {\table}; % y_f \addplot [stack plots=y, fill=none, draw=none, forget plot] table [x=temps, y=y_f__inf] {\table} \closedcycle; \addplot [stack plots=y, fill=gray!20, draw opacity=0, area legend] table [x=temps, y expr=\thisrow{y_f__sup}-\thisrow{y_f__inf}] {\table} \closedcycle; \addplot [stack plots=false, very thick,smooth,blue] table [x=temps, y=y_f] {\table}; \end{axis} \end{tikzpicture} \end{document}

  • TikZ, 3d library and circle fading
    by Luigi on June 20, 2012 at 5:39 pm

    I'm using the 3d library to put a circle on the z=0 plane, and other things. I'd like to fade this circle radially, but the result isn't as I would expect because the fading is not proportional to the distance from the origin. How can I do? \documentclass{standalone} \usepackage{tikz} \usetikzlibrary{3d,fadings} \tikzfading [name=radialfade, inner color=transparent!0, outer color=transparent!100] \begin{document} \begin{tikzpicture} [x={(-0.3535,-0.3535cm)}, y={(1cm,0cm)}, z={(0cm,1cm)}, scale=3] \begin{scope} [canvas is xy plane at z=0] \fill [blue, path fading=radialfade] circle (1); \end{scope} \draw[-latex] (-1,0,0) -- (1,0,0) node [left] {$x$}; \draw[-latex] (0,-1,0) -- (0,1,0) node [below] {$y$}; \draw[-latex] (0,0,-0.5) -- (0,0,0.5) node [left] {$z$}; \end{tikzpicture} \end{document}