1

I'd like to achieve the following plot:

\documentclass[a4paper]{article}

\usepackage{pgfplots}
\pgfplotsset{compat=1.17}

\begin{document}

\begin{filecontents}{data.txt}
start,end
1,23
51,69
106,165
\end{filecontents}

\begin{tikzpicture}
    \begin{axis}[
        enlarge x limits=-1,
        xlabel = {Iterations},
        ylabel = {Cost},
        extra y ticks = {1},
        extra y tick style = {grid=major},
        ]
        \addplot[black, domain=1:165]{4*exp(-0.05*x)};

        % I want to read these from the external file data.txt and I don't know how many rows are in there
        \fill [black, opacity=0.2] (1,-1) rectangle (21,10);  
        \fill [black, opacity=0.2] (51,-1) rectangle (69,10);  
        \fill [black, opacity=0.2] (105,-1) rectangle (165,10);  
    \end{axis}    
\end{tikzpicture}

\end{document}

But instead of calling \fill three times with hard coded values, I'd like to read them in from the file data.txt.

How can I do that?

The plot should look like this: Sample Picture Thanks!

2
  • Off-topic: Besides the technicality, why do you think it’s a good visual communication? E.g. in your screenshot the fields seem to be arbitrary wrt the cost function shown? Commented Jun 8, 2024 at 9:14
  • 1
    @MS-SPO The cost function just a place holder. In the real plot, I'm gonna load some data and the shading is meant to show the alternating phases of the optimization which will also be visible in the cost. Commented Jun 10, 2024 at 6:46

1 Answer 1

3
\begin{filecontents*}{data.txt}
start   end
1   23
51  69
106 165
\end{filecontents*}

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usepackage{pgfplotstable}
\begin{document}
\begin{tikzpicture}
\pgfplotstableread{data.txt}\loadedtable
\begin{axis}
\pgfplotstablegetrowsof{\loadedtable}
\pgfmathsetmacro{\N}{\pgfplotsretval-1}  
\pgfplotsinvokeforeach {0,...,\N} {
\fill[lightgray] \pgfextra{\pgfplotstablegetelem{#1}{start}\of\loadedtable} (\pgfplotsretval,\pgfkeysvalueof{/pgfplots/ymin}) \pgfextra{\pgfplotstablegetelem{#1}{end}\of\loadedtable} rectangle (\pgfplotsretval,\pgfkeysvalueof{/pgfplots/ymax});
}
\addplot[black, domain=1:165]{4*exp(-0.05*x)};
\addplot[only marks] table[x=start, y expr=1] {\loadedtable};
\addplot[only marks] table[x=end,   y expr=1] {\loadedtable};
\end{axis}    
\end{tikzpicture}
\end{document}

Graph with vertical gray areas

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.