我想用 pgfplots 建立一個長條圖。
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepackage{pgfplotstable}
\begin{document}
\pgfplotstableread[col sep=comma] {
name,value
A,1
B,2
C,1
D,3
}\mytable
\pgfplotsset{%
compat=1.8,
ybar,
compat/show suggested version=false,
}
\begin{tikzpicture}
\begin{axis}[
xlabel=name,
xtick=data,
xticklabels from table={\mytable}{name},
ylabel=value
]
\addplot table[x=name,y=value] {\mytable};
\end{axis}
\end{tikzpicture}
\end{document}
但出現以下錯誤:
! Package PGF Math Error: Could not parse input 'A' as a floating point number,
sorry. The unreadable part was near 'A'..
See the PGF Math package documentation for explanation.
Type H <return> for immediate help.
...
l.26 ...\addplot table[x=name,y=value] {\mytable};
答案1
在嘗試了一些事情之後,例如刪除未使用的套件、指定 row sep 等,結果發現:
- 長條圖是一維的
- 所以你只指定一個值
\begin{tikzpicture}
\begin{axis}[
xlabel=name,
xtick=data,
xticklabels from table={\mytable}{name}, % <<<
ylabel=value
]
\addplot table[x=value] {\mytable}; % <<<
\end{axis}
\end{tikzpicture}
如果您指定y=value
,您會再次收到錯誤:
\addplot table[y=value] {\mytable};
嘗試讀取以名稱(字元)作為值的列將導致錯誤:
\addplot table[x=name ...
% https://tex.stackexchange.com/questions/705829/plot-bar-chart-with-pgfplots
\documentclass{standalone}
%\usepackage{tikz}
\usepackage{pgfplots}
%\pgfplotsset{compat=newest}
%\usepackage{pgfplotstable}
\begin{document}
\pgfplotstableread[row sep=\\,col sep=comma] {
name,value\\
A,1\\
B,2\\
C,1\\
D,3\\
}\mytable
\pgfplotsset{%
compat=1.8,
ybar,
compat/show suggested version=false,
}
\begin{tikzpicture}
\begin{axis}[
xlabel=name,
xtick=data,
xticklabels from table={\mytable}{name}, % <<<
ylabel=value
]
\addplot table[x=value] {\mytable}; % <<<
\end{axis}
\end{tikzpicture}
\end{document}