pgfplots 包 PGF 数学错误:无法解析输入

pgfplots 包 PGF 数学错误:无法解析输入

我在使用 pgfplots 包时遇到错误,我假设 x 轴(edad)将其解释为数字元素

有什么方法可以纠正这个问题吗?

m3.csv

tasa, edad
2.303, 0-4
0.212, 5-9
0.286, 10-14
0.875, 15-19
1.533, 20-24
2.041, 25-29
2.427, 30-34
3.128, 35-39
4.457, 40-44
6.760, 45-49
9.647, 50-54
15.164, 55-59
21.440, 60-64
30.204, 65-69
42.413, 70-74
60.921, 75-79
90.133, 80-84
160.425, 85+

主文本

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots,pgfplotstable}

\begin{document}
\begin{tikzpicture}
    \begin{axis}[width= \textwidth,
    axis x line = bottom,
    axis y line = left,
    %nodes near coords,
    %transpose legend,
    xlabel = {},
    x tick label style={
            /pgf/number format/1000 sep=%
    },
    x tick label as interval,
    xticklabel = {
        $\pgfmathprintnumber{\tick}$
    },
    ylabel = {Mortality by 1\;000},
    ]
        \addplot table[mark=otimes*,x=edad,y=tasa,col sep = comma] {m3.csv};
    \end{axis}
\end{tikzpicture}
\end{document}

错误

!PGF 软件包数学错误:无法将输入“65-69”解析为浮点数,抱歉。不可读部分位于“-69”附近

!PGF 软件包数学错误:无法将输入“85+”解析为浮点数,抱歉。不可读的部分位于“+”附近。

答案1

你说得对。x=edad希望数字数据能够将其放置在正确的 x 轴位置。要将“文本”标签放在轴上,有两种方法。

  1. 使用符号坐标 ( symbolic x coords) 或
  2. 使用“虚拟”数字 x 坐标并(仅)用文本标记它们。

您应该选择选项 2,因为它更加通用/灵活。请参阅以下代码及其注释,了解其工作原理。

% used PGFPlots v1.18.1
\begin{filecontents*}{m3.csv}
    tasa, edad
    2.303, 0-4
    0.212, 5-9
    0.286, 10-14
    0.875, 15-19
    1.533, 20-24
    2.041, 25-29
    2.427, 30-34
    3.128, 35-39
    4.457, 40-44
    6.760, 45-49
    9.647, 50-54
    15.164, 55-59
    21.440, 60-64
    30.204, 65-69
    42.413, 70-74
    60.921, 75-79
    90.133, 80-84
    160.425, 85+
    0, dummy        % <-- added this dummy line to plot the last bar which is needed for "intervals"
\end{filecontents*}
\documentclass[border={5pt}]{standalone}
\usepackage{pgfplots,pgfplotstable}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        width=\textwidth,
        axis x line=bottom,
        axis y line=left,
        ylabel = {Mortality by 1\;000},
        % I prefer to show this as bars instead of points
        ybar interval,
%        % (if you want to stick to points use this line instead of the previous)
%        x tick label as interval=true,
        % show a label at each data point
        xtick=data,
        % use the data from the table for the xticklabels
        xticklabels from table={m3.csv}{edad},
        % (rotate them so they don't overlap)
        x tick label style={rotate=90,anchor=east},
    ]
        \addplot table [
            mark=otimes*,
%            % this only works for numeric data
%            x=edad,
            % so simply use the coordinate index for positioning
            % (the correct label is handled by `xticklabels from table`
            x expr=\coordindex,
            y=tasa,
            col sep=comma,
        ] {m3.csv};
    \end{axis}
\end{tikzpicture}
\end{document}

该图显示了上述代码的结果

相关内容