条形图不工作

条形图不工作

使用此代码:

 \documentclass{article}
\usepackage{tikz} 
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}

  \begin{tikzpicture}
          \begin{axis}[
               ybar,
                bar width=.5cm,
                width=0.48\textwidth,
                height=.5\textwidth,
                symbolic x coords={\xcoords},
                xtick=data,
                nodes near coords,
                nodes near coords align={vertical},
                ymin=0,ymax=50,
                ylabel={\%},
            ]
            \addplot  table[x=column 1,y=column 2,col sep=comma] {cfets.csv}; 

          \end{axis}
        \end{tikzpicture}
\end{document}

我收到此错误:

Package pgfplots Error: Sorry, the input coordinate `8' has not been defined 
with 'symbolic x coords={8,14,24,4,15,19,13,23,18,5,1,3,11,2,7,17,20}... Maybe 
it has been misspelled?.

我已将其设置为,每当我更新结果时,它都会自动使用这些结果更新 .sty 和 .csv 文件,从而轻松进行修改。显而易见,\xcoords 是一个 .sty 命令,在本例中,它只写入:

\newcommand*{\xcoords}{8,14,24,4,15,19,13,23,18,5,1,3,11,2,7,17,20}

cfets.csv 文件有两列,如下所示:

column 1    column 2
8   44
14  44
24  44
4   20
15  17
19  16
13  13
23  13
18  12
5   10
1   4
3   2
11  2
2   1
7   1
17  1
20  1

删除了逗号,因为我是从 Excel 中复制粘贴的。

到底是怎么回事?

答案1

您也可以使用xticklabels from table它,从数据文件中获取刻度标签。

在此处输入图片描述

\documentclass[border=5mm]{standalone}
\usepackage{filecontents} % this is just for example, the environment below writes its contents to the specified file
\begin{filecontents*}{cfets.csv}
column1 column2 % note changed column headings (removed spaces)
8  44
14 44
24 44
4  20
15 17
19 16
13 13
23 13
18 12
5  10
1  4
3  2
11 2
2  1
7  1
17 1
20 1
\end{filecontents*}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\begin{document}
\begin{tikzpicture}
      \begin{axis}[
           ybar,
            bar width=.4cm, % modified
            enlarge x limits={abs=.4cm}, % added
            width=0.8\textwidth, % modified
            height=.5\textwidth,
            xtick=data,
            xticklabels from table={cfets.csv}{column1}, % added
            nodes near coords,
            nodes near coords align={vertical},
            ymin=0,ymax=50,
            ylabel={\%},
        ]
        % node x expr=\coordindex instead of x=
        \addplot  table[x expr=\coordindex,y=column2] {cfets.csv}; 

      \end{axis}
    \end{tikzpicture}
\end{document}

相关内容