1

I have a scenario where my table of data has some number of columns, but I don't necessarily know exactly how many since they're generated based on how many data points fall within a certain window. I want to plot the first and last columns with specific styles to differentiate them, and have the intervening points plotted in a uniform color. An example table might be...

x first last A B C D (...)
(data goes here)

where A, B, C, etc are the data points that lie between first and last. I will always have x, first, and last, and at least one more column, but I don't necessarily know how many additional columns there may be. The columns are also all the same length so they can always be plotted with x. In practice these don't actually have column names, but I can add them if need be. This data is stored in a file, which I'll call my_data.dat.

It's easy enough to add plots for first and last since I know their column names. Where I'm struggling is plotting those intermediate columns in a way that doesn't require already knowing the number of columns.

In Python syntax I'm looking to do something like plt.plot(x, my_data[2:-1]). Is there a command to return the number of columns in the data table so I could just do a for-loop for each column? Or a way to tell pgfplots in \addplot to use a range of column indexes for one plot?

Can this be done in pgfplots? Or is my only option to just count up the number of columns by hand and do something like I saw in this post? It's certainly doable, but if I can generalize it so I don't always have to manually count the number of columns that'd be great.

fergu
  • 189

1 Answers1

2

You can get the number of columns in a table with \pgfplotstablegetcolsof, so I suppose you can do something like this:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotstableread{
x first last A B C D
0 1 2 3 4 5 6
1 1 2 3 4 5 6
}\mydata
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot table[x=x, y=first] {\mydata};
\addplot table[x=x, y=last] {\mydata};

% get number of columns in table \pgfplotstablegetcolsof{\mydata} % subtract one because column indexing is zero based \pgfmathtruncatemacro\NumCols{\pgfplotsretval-1} % iterate over columns from the fourth (with index 3 because starts at zero) \pgfplotsinvokeforeach{3,...,\NumCols}{ \addplot [black] table[x=x, y index=#1] {\mydata}; } \end{axis} \end{tikzpicture} \end{document}

Torbjørn T.
  • 206,688
  • I just realized this was not quite the right thing, I assumed your example file was correct, but your description and Python example say something different. Anyways, the general principle will be the same, so there won't be large changes. – Torbjørn T. Apr 25 '21 at 17:35
  • I had a typo in my python code it seems :) This is perfect, thank you! – fergu Apr 29 '21 at 22:32