我尝试对齐两个 tikz 子图。但由于某种原因,它无法完全工作,并且根据此屏幕截图,它们在水平方向上未对齐。
我在这里做错了什么?
\documentclass[12pt, a4paper]{article}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{booktabs}
\usepackage{tabularx}
\usepackage{array}
\usepackage{subcaption}
\usepackage[hmargin=1in, vmargin=1.2in]{geometry}
\usepackage[labelfont=bf]{caption}
\captionsetup{width=.98\linewidth}
\usepackage{setspace}
\setstretch{1.3}
\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{figure}[h]
\begin{subfigure}{\linewidth}
\centering
\begin{tikzpicture}
\begin{axis}[
scaled y ticks = false,
y tick label style={/pgf/number format/fixed, /pgf/number format/fixed zerofill, /pgf/number format/precision=2},
]
\addplot[color=black] coordinates {
(1, 1)
(2, 2)
(3, 3)
(4, 4)
(5, 5)
(6, 6)
(7, 7)
(8, 8)
};
\end{axis}
\end{tikzpicture}
\caption{}
\end{subfigure}%
\\[5mm]
\begin{subfigure}{\linewidth}%
\centering
\begin{tikzpicture}
\begin{axis}[
scaled y ticks = false,
y tick label style={/pgf/number format/fixed, /pgf/number format/fixed zerofill, /pgf/number format/precision=2},
]
\addplot[color=black] coordinates {
(-100, -1)
(200, 2)
(300, 3)
};
\end{axis}
\end{tikzpicture}
\caption{}
\end{subfigure} %
\caption{asd}
\end{figure}
\end{document}
答案1
您必须扩大分配给 y 标签的宽度(在两个图中)以容纳减号。
\documentclass[12pt, a4paper]{article}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{booktabs}
\usepackage{tabularx}
\usepackage{array}
\usepackage{subcaption}
\usepackage[hmargin=1in, vmargin=1.2in]{geometry}
\usepackage[labelfont=bf]{caption}
\captionsetup{width=.98\linewidth}
\usepackage{setspace}
\setstretch{1.3}
\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{figure}[h]
\pgfplotsset{yticklabel style = {text width=2.5em, align=right}}% added <<<<<<<<<<<<
\begin{subfigure}{\linewidth}
\centering
\begin{tikzpicture}
\begin{axis}[
scaled y ticks = false,
y tick label style={/pgf/number format/fixed, /pgf/number format/fixed zerofill, /pgf/number format/precision=2},
]
\addplot[color=black] coordinates {
(1, 1)
(2, 2)
(3, 3)
(4, 4)
(5, 5)
(6, 6)
(7, 7)
(8, 8)
};
\end{axis}
\end{tikzpicture}
\caption{}
\end{subfigure}%
\\[5mm]
\begin{subfigure}{\linewidth}%
\centering
\begin{tikzpicture}
\begin{axis}[
scaled y ticks = false,
y tick label style={/pgf/number format/fixed, /pgf/number format/fixed zerofill, /pgf/number format/precision=2},
]
\addplot[color=black] coordinates {
(-100, -1)
(200, 2)
(300, 3)
};
\end{axis}
\end{tikzpicture}
\caption{}
\end{subfigure} %
\caption{asd}
\end{figure}
\end{document}
答案2
发生这种情况的原因是您正在使用\centering
并且您的图的宽度不完全相同:底部图中的减号使其略宽。如果我将其放在\phantom{+}
第一个环境之前tikzpicture
,它几乎但不是完全完美地排列,您可以替换它或使用\hspace
命令对其进行增强,以使其手动完美排列。