4

Is there a way to import & auto-plot a graph containing text in one column?

Eg. Here's my table

Period,Unit Sales (in thousands)
Q1 '07,24943
Q2 '07,27855
Q3 '07,32752
Q4 '07,36766

Edit:

Here's what I've tried:

\begin{tikzpicture}
\begin{axis}[
xlabel = Period,
ylabel = Unit Sales (thousands)]
\addplot table [col sep=comma]{data.csv};
\end{axis}
\end{tikzpicture}
0
2

This turns out to be a bit trickier than it looks: you need to turn the symbolic input into a number and back again to allow plotting. For example, the following seems to work:

\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{\jobname.csv}
Period,Unit Sales (in thousands)
Q1 '07,24943
Q2 '07,27855
Q3 '07,32752
Q4 '07,36766
\end{filecontents*}
\usepackage{pgfplots}
\newcommand*{\parseperiod}{}
\def\parseperiod Q#1 '#2\relax{\def\pgfmathresult{0.20#2#1}}
\newcommand*{\parseinvperiod}{}
\def\parseinvperiod #1.#2#3#4#5#6#7\relax{\def\pgfmathresult{Q#6 '#4#5}}
\begin{document}

\begin{tikzpicture}
  \begin{axis}[
    ybar,
    x coord trafo/.code = {\expandafter\parseperiod#1\relax},
    x coord inv trafo/.code = {\parseinvperiod#1\relax},
    xticklabel = {\tick},
    xtick = data,
    xlabel = Period,
    ylabel = Unit Sales (thousands)]
    \addplot table [col sep=comma]{\jobname.csv};
  \end{axis}
\end{tikzpicture}

\end{document}

The idea here is to parse the horizontal labels and turn them into numbers using the low-level x coord trafo key. I've done that by grabbing the quarter and the year, and making them into numbers that read 0.20<year><quarter>. To actually print the labels, you then have to turn that back into text using x coord inv trafo. Ther is also a bit of trickery to only have x-axis labels for the data itself (xtick = data) and to avoid any parsing of the labels at that point (xticklabel = {\tick}).

3
  • And people wonder why I just want to insert a screenshot from Excel :/ ... On a serious note, thank you very much for your effort. Much appreciated :) – James Jan 28 '14 at 10:00
  • I suspect a better demo is needed for this in the manual: it took a bit of effort! I might ask the package author, at least if there are no better answers than mine. – Joseph Wright Jan 28 '14 at 10:08
  • Surely a \text{} solution would work? \text{Q1 '07},24943 etc... – James Jan 28 '14 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.