如何使用 pgfplotstable 对主食图中的结果进行排序

如何使用 pgfplotstable 对主食图中的结果进行排序

我希望能够按升序排列数据。在下面的代码中,我注释掉了我想要实现的顺序。我已经使用表格排序完成了这个操作。但我想做的是使用 pgfplots 中的命令进行排序。

\documentclass[border=10mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\usepackage{pgfplotstable}

\begin{filecontents}{data.csv}
Manufacturer,BEV
Tesla Inc.,1314319
BYD, 913866
VW Group,578231
GM,568647
Stellantis,301577
Hyundai Motor,372092
BMW Group,218882
Geely Auto Group,265811
Mercedes-Benz Group,162909
R-N-M Alliance,259164
GAC,287599
SAIC,203205
Geely-Volvo Car Group,118029
Chery Automobile,235533
Changan Automobile Group,201589
Dongfeng Motor,222841
Ford,105544
Hozon Auto,149285
\end{filecontents}

\begin{document}

\begin{tikzpicture}

\begin{axis}[
    ybar,
        width=18cm,
    height=12cm,
    bar width=0.5cm,
    xlabel={Manufacturer},
    ylabel={Number of vehicles},
    % symbolic x coords={Tesla Inc., BYD, VW Group, GM, Hyundai Motor, Stellantis, GAC, Geely Auto Group, R-N-M Alliance, Chery Automobile, Dongfeng Motor, BMW Group, SAIC, Changan Automobile Group, Mercedes-Benz Group, Hozon Auto, Geely-Volvo Car Group,  Ford},
    symbolic x coords={BYD, Tesla Inc., VW Group, GM, Stellantis, Hyundai Motor, BMW Group, Geely Auto Group, Mercedes-Benz Group, R-N-M Alliance, GAC, SAIC, Geely-Volvo Car Group, Chery Automobile, Changan Automobile Group, Other, Dongfeng Motor, Ford, Hozon Auto, CHJ Automotive},
    xtick=data,
    xticklabel style={rotate=45, anchor=east},
    nodes near coords,
    nodes near coords={},
    ymin=0,
]

\addplot table[col sep=comma, x=Manufacturer, y=BEV] {data.csv};

\end{axis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

对比

在此处输入图片描述

答案1

我设法用一种略有不同的方法实现了我想要做的事情。排序很完美,我不再需要手动排序了。手动创建单个图表不是问题,但是当您需要生成多个图表时,自动化该过程会变得非常方便。

\documentclass[border=10mm]{standalone}
\usepackage{pgfplots, pgfplotstable}
\pgfplotsset{compat=1.18} 

\pgfplotstableread[col sep=comma]{
Manufacturer,BEV
Tesla Inc.,1314319
BYD, 913866
VW Group,578231
GM,568647
Stellantis,301577
Hyundai Motor,372092
BMW Group,218882
Geely Auto Group,265811
Mercedes-Benz Group,162909
R-N-M Alliance,259164
GAC,287599
SAIC,203205
Geely-Volvo Car Group,118029
Chery Automobile,235533
Changan Automobile Group,201589
Dongfeng Motor,222841
Ford,105544
Hozon Auto,149285
}\data

\begin{document}

\pgfplotstablesort[sort key={BEV},sort cmp={int >}]\sorteddata{\data}

\begin{tikzpicture}
  \begin{axis}[
    ybar,
    width=18cm,
    height=12cm,
    bar width=0.5cm,
    xlabel={EV Manufacturer},
    ylabel={Number of vehicles},
    xtick=data,
    xticklabels from table={\sorteddata}{Manufacturer},
    xticklabel style={rotate=45,anchor=north east},
    nodes near coords,
    nodes near coords={},
    ymin=0,
    ]
    \addplot table[x expr=\coordindex, y=BEV] {\sorteddata};
  \end{axis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

相关内容