Plot data from a file in LaTeX (pgfplots)

\addplot table {data.dat}; reads a text file with one data point per line and plots the first column against the second. For a CSV file add col sep=comma, and pick the columns by name with x= and y=.

Preamble

The snippets on this page need these lines before \begin{document}:

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

Plot points written in the document

For a few values, write the points as (x,y) pairs after coordinates. mark=* draws a filled circle at every point.

\begin{tikzpicture}
\begin{axis}[xlabel={Time in h}, ylabel={Temperature in $^\circ$C}]
\addplot[blue, mark=*] coordinates {
  (0,20.1) (1,21.4) (2,23.0) (3,24.2) (4,23.5) (5,22.8)
};
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Read a file with columns separated by spaces

The file data.dat starts with the line time temp, followed by lines such as 0 20.1. The first line names the columns, and x=time, y=temp selects them. The file name is relative to the folder of the main .tex file.

\begin{tikzpicture}
\begin{axis}[xlabel={Time in h}, ylabel={Temperature in $^\circ$C}]
\addplot[blue, mark=*] table[x=time, y=temp] {data.dat};
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Read a CSV file

The file data.csv starts with the line time,temp,humidity. col sep=comma tells pgfplots that commas separate the columns; col sep=semicolon and col sep=tab exist as well. Two \addplot commands plot two columns of the same file.

\begin{tikzpicture}
\begin{axis}[xlabel={Time in h}, legend pos=outer north east]
\addplot[blue, mark=*] table[col sep=comma, x=time, y=temp] {data.csv};
\addlegendentry{Temperature}
\addplot[red, mark=square*] table[col sep=comma, x=time, y=humidity] {data.csv};
\addlegendentry{Humidity}
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Show points only, or a line only

only marks draws the points without a connecting line, which gives a scatter plot. no markers draws the line without points.

\begin{tikzpicture}
\begin{axis}[xlabel={Temperature in $^\circ$C}, ylabel={Humidity in \%}]
\addplot[only marks, mark=*, blue] table[col sep=comma, x=temp, y=humidity] {data.csv};
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Use a logarithmic axis

ymode=log in the axis options makes the y axis logarithmic, xmode=log the x axis.

\begin{tikzpicture}
\begin{axis}[ymode=log, xlabel={Step}, ylabel={Error}]
\addplot[blue, mark=*] coordinates {
  (1,0.5) (2,0.06) (3,0.008) (4,0.0009) (5,0.0001)
};
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

File data.dat:

time temp
0 20.1
1 21.4
2 23.0
3 24.2
4 23.5
5 22.8

File data.csv:

time,temp,humidity
0,20.1,45
1,21.4,44
2,23.0,41
3,24.2,39
4,23.5,40
5,22.8,42

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages