使用 pgfplots 绘制条形图

使用 pgfplots 绘制条形图

我想用 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

尝试了一些方法之后,比如删除未使用的包、指定行分隔符等,结果是:

  • 条形图是一维的
  • 因此您只需指定一个值
 \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}

相关内容