我正在尝试从 .csv 文件生成一个图。
我的.csv 文件包含以下数据,其名称为HeightsAndWeights.csv
:
为了生成图表,我使用以下代码:
\documentclass{article}
\usepackage{siunitx}
\usepackage{tikz} % To generate the plot from csv
\usepackage{pgfplots}
\pgfplotsset{compat=newest} % Allows to place the legend below plot
\usepgfplotslibrary{units} % Allows to enter the units nicely
\sisetup{
round-mode = places,
round-precision = 2,
}
\begin{document}
\begin{figure}[h!]
\begin{center}
\begin{tikzpicture}
\begin{axis}[
width=\linewidth, % scales the plot to the line width of the sheet.
grid=major, % displays a grid
grid style={dashed,gray!30}, % grid style
xlabel=Heights $h$, % set axis labels
ylabel=Weights $w$,
x units=\si{cm},
y units=\si{kg},
legend style={at={(0.5,-0.2)},anchor=north}, % put the legend below the plot
x tick label style={rotate=90,anchor=east}, % display label sideways
]
\addplot % add the plot from the table
table[x index=1,y index=2,sep=comma]{HeightsAndWeights.csv};
\legend{Plot}
\end{axis}
\end{tikzpicture}
\caption{Plot of the data from the file containing students' heights and weights.}
\end{center}
\end{figure}
\end{document}
结果如下:
我做错了什么?我应该纠正、添加或删除什么?
评论后更新:
以下是我正在使用的软件包的完整列表:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[russian,english]{babel}
\usepackage{dirtytalk} % to allow quotations with \say{}
\usepackage{amsmath} % to allow removal of equation numbering.
\usepackage{graphicx} % to allow use of images and pictures.
\usepackage{subcaption} % to allow the use of multiple images.
\usepackage[table]{xcolor} % to allow colored tables.
\usepackage{booktabs} % for \toprule, \midrule, \bottomrule.
\usepackage{siunitx} % for formatting units and values.
\usepackage{pgfplotstable} % for generating tables form .csv files.
\usepackage{tikz} % for generating plots from .csv files.
\pgfplotsset{compat=newest} % for legends below the plot.
\usepgfplotslibrary{units} % for using measuring units.
\sisetup{ % setting up the siunitx package
round-mode=places, % round numbers
round-precision=2 % up to the second digit
}
更新 2:
\begin{filecontents*}{file.csv}
Peter, 150, 45
Jason, 134, 39
Stefan, 139, 41
Noa, 132, 38
Liv, 137, 36
Beti 135, 34
\end{filecontents*}
答案1
正如 daleif 在他的(几条)评论中所述:在删除所有(拼写)错误后,MWE 可以按预期工作......
% used PGFPlots v1.16
\begin{filecontents*}{HeightsAndWeights.csv}
Peter, 150, 45
Jason, 134, 39
Stefan, 139, 41
Noa, 132, 38
Liv, 137, 36
Beti 135, 34
\end{filecontents*}
\documentclass[border=5pt]{standalone}
\usepackage{siunitx}
\usepackage{pgfplots}
\usepgfplotslibrary{units}
\pgfplotsset{compat=1.3}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
grid=major,
grid style={dashed,gray!30},
xlabel=Heights $h$,
ylabel=Weights $w$,
x unit=\si{\centi\metre},
y unit=\si{\kilogram},
legend style={
at={(0.5,-0.2)},
anchor=north,
},
x tick label style={
rotate=90,
anchor=east,
},
table/col sep=comma,
]
\addplot table [x index=1,y index=2] {HeightsAndWeights.csv};
\legend{Plot}
\end{axis}
\end{tikzpicture}
\end{document}