1

I've drawn the following graph

Graph

Using this code:

\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}

\begin{filecontents*}{data.csv}
a,b
2019-05,64
2019-06,66
2019-07,59
2019-08,56
2019-09,64
2019-10,55
2019-11,57
2019-12,51
2020-01,50
2020-02,54
2020-03,51
2020-04,53
2020-05,49
2020-06,49
2020-07,52
2020-08,52
2020-09,48
2020-10,38
2020-11,37
2020-12,36
2021-01,32
2021-02,33
2021-03,37
2021-04,43
2021-05,37
2021-06,34
2021-07,39
2021-08,36
2021-09,36
2021-10,34
2021-11,42
2021-12,38
2022-01,40
\end{filecontents*}

\begin{document}
\pgfplotsset{width=\textwidth, compat=1.18}
\pgfplotstableread[col sep=comma,]{data.csv}\datatable
\begin{tikzpicture}
\begin{axis}[
    xtick=data,
    xticklabels from table={\datatable}{a},
    x tick label style = {font=\small, align=center, rotate=70, anchor=north east},
]
\addplot table [x=a, y=b, col sep=comma, x expr=\coordindex]{\datatable};
\end{axis}
\end{tikzpicture}
\end{document}

I don't want the x-axis to be so crowded. It would be nice if I could somehow only draw a label for every 5th data point. Is this possible?

1 Answer 1

1

Since the data is categorical, it is impossible to specify the xtick distance the normal way. The below codes first capture the number of rows from the table, then set the xtick based on your desired interval.

\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}

\begin{filecontents*}{data.csv}
a,b
2019-05,64
2019-06,66
2019-07,59
2019-08,56
2019-09,64
2019-10,55
2019-11,57
2019-12,51
2020-01,50
2020-02,54
2020-03,51
2020-04,53
2020-05,49
2020-06,49
2020-07,52
2020-08,52
2020-09,48
2020-10,38
2020-11,37
2020-12,36
2021-01,32
2021-02,33
2021-03,37
2021-04,43
2021-05,37
2021-06,34
2021-07,39
2021-08,36
2021-09,36
2021-10,34
2021-11,42
2021-12,38
2022-01,40
\end{filecontents*}

\begin{document}
%\pgfplotsset{width=\textwidth, compat=1.18}
\pgfplotstableread[col sep=comma,]{data.csv}\datatable
\begin{tikzpicture}
\pgfplotstablegetrowsof{\datatable}
\pgfmathsetmacro\numrows{\pgfplotsretval}
\begin{axis}[
    xtick={0,5,...,\numexpr\numrows-1},
    xticklabels from table={\datatable}{a},
    x tick label style = {font=\small, align=center, rotate=70, anchor=north east},
]
\addplot table [x=a, y=b, col sep=comma, x expr=\coordindex]{\datatable};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .