pgfplots – Handling PGFplots Tables with Different Number of Elements in Columns

pgfplotspgfplotstable

I am trying to plot a table where I have different number of elements in the columns. In the MWE, the pairs (x1,y1),…,(x4,y4) all have different number of elements, can I use PGFplots in such situation, ithout having to manually arrange the table or spit it in 4 different tables?

\documentclass{standalone}

\usepackage{pgfplots}
\usepackage{pgfplotstable}

\pgfplotstableread{
x1 y1  x2 y2   x3 y3  x4 y4
1  0.5 1  0.2  1  0.1 1  0.3
2  0.7 2  0.4  2  0.2 2  0.5
3  0.3 3  0.6  3  0.4 3  0.6
4  0.1 4  0.3  4  0.4
       5  0.2  5  0.2
               6  0.2 
               7  0.1
}\mytable

\pgfplotsset{%
    compat=1.8,
    compat/show suggested version=false,
}

\begin{document}
\begin{tikzpicture}
\begin{axis}[xlabel={x-axis},ylabel={y-axis}]
    \addplot table[x=x1,y=y1] {\mytable};
    \addplot table[x=x2,y=y2] {\mytable};
    \addplot table[x=x3,y=y3] {\mytable};
    \addplot table[x=x4,y=y4] {\mytable};
    \legend{1,2,3,4}
\end{axis}
\end{tikzpicture}
\end{document}

Best Answer

Unless you use a different col sep, you will need to use empty groups.

From the pgfplotstable manual, section 2.1 “Text Table Input Format”, p. 5f:

Furthermore, if you need empty cells in case col sep≠space, you have to provide {} to delimit such a cell since col sep=space uses at least one white space (consuming all following ones).

This is the usual way how TeX treats spaces.

An alternative solution would be to use a different column seperator, e.g. a comma:

\pgfplotstableread[col sep=comma]{
x1, y1,x2, y2,x3, y3,x4, y4
 1,0.5, 1,0.2, 1,0.1, 1,0.3
 2,0.7, 2,0.4, 2,0.2, 2,0.5
 3,0.3, 3,0.6, 3,0.4, 3,0.6
 4,0.1, 4,0.3, 4,0.4,  ,
  ,   , 5,0.2, 5,0.2,  ,
  ,   ,  ,   , 6,0.2,  ,
  ,   ,  ,   , 7,0.1,  ,
}\mytable

(The spaces here are only for a visual reference.) For simple numbers that get parsed by pgfplots anyway, the additional spaces do not hurt, but for various other use cases, the option /pgfplots/table/trim cells might be helpful.

Code

\documentclass{standalone}

\usepackage{pgfplots}
\usepackage{pgfplotstable}

\pgfplotstableread{
x1 y1  x2 y2   x3 y3  x4 y4
1  0.5 1  0.2  1  0.1 1  0.3
2  0.7 2  0.4  2  0.2 2  0.5
3  0.3 3  0.6  3  0.4 3  0.6
4  0.1 4  0.3  4  0.4 {} {}
{} {}  5  0.2  5  0.2 {} {}
{} {}  {} {}   6  0.2 {} {} 
{} {}  {} {}   7  0.1 {} {}
}\mytable

\pgfplotsset{%
    compat=1.8,
    compat/show suggested version=false,
}

\begin{document}
\begin{tikzpicture}
\begin{axis}[xlabel={x-axis},ylabel={y-axis}]
    \addplot table[x=x1,y=y1] {\mytable};
    \addplot table[x=x2,y=y2] {\mytable};
    \addplot table[x=x3,y=y3] {\mytable};
    \addplot table[x=x4,y=y4] {\mytable};
    \legend{1,2,3,4}
\end{axis}
\end{tikzpicture}
\end{document}

Output

enter image description here