
Следующийэтот ответпри настройке ytick=\empty
для второй и третьей подфигур они распределяются неравномерно, так как я могу исправить этот вывод, позволив всем подфигурам иметь одинаковую ширину и равномерно распределяться по textwidth
?
\RequirePackage{luatex85}
\documentclass{article}
\usepackage{pgfplots,caption,subcaption,mwe,showframe}
\pgfplotsset{compat=newest}
\begin{document}
\begin{figure}
\centering
\pgfmathsetlengthmacro{\myaxiswidth}{0.33\textwidth-width(" 300 ")}% subtract width of widest ticklabel, with a space on each side
\begin{subfigure}[t]{0.33\textwidth}
\begin{tikzpicture}
\begin{axis}[enlargelimits=false,width=\myaxiswidth, height=0.3\textheight, scale only axis]
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-a};
\end{axis}
\end{tikzpicture}
\end{subfigure}%
%
\begin{subfigure}[t]{0.33\textwidth}
\begin{tikzpicture}
\begin{axis}[enlargelimits=false,width=\myaxiswidth, height=0.3\textheight, scale only axis, ytick=\empty]
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-b};
\end{axis}
\end{tikzpicture}
\end{subfigure}%
%
\begin{subfigure}[t]{0.33\textwidth}
\begin{tikzpicture}
\begin{axis}[enlargelimits=false,width=\myaxiswidth, height=0.3\textheight, scale only axis, ytick=\empty]
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-c};
\end{axis}
\end{tikzpicture}
\end{subfigure}
\end{figure}
\end{document}
решение1
Причиной различного пространства здесь является комбинация факторов. Во-первых, поскольку первый участок шире двух последних, расстояние от правой стороны оси до края subfigure
меньше для первого, чем для двух последних.
Далее, два последних графика уже, чем subfigure
среды, и по умолчанию текст внутри них выровнен по левому краю. Чтобы исправить эту часть, добавьте \centering
в начале каждой subfigure
среды, но этого недостаточно, чтобы получить равное расстояние между осями 1&2 и 2&3, из-за того, что описано в первом абзаце выше.
Теперь, вполне могут быть и другие способы, я определенно не хорош в поиске элегантных решений, но обходной путь, который я придумал, заключается в использовании \begin{tikzpicture}[trim axis left]
для всех трех графиков. trim axis left
— это стиль, который изменяет ограничивающую рамку tikzpicture
так, что все, что находится слева от axis
(ticklabels, ylabel), не учитывается при определении ограничивающей рамки. Это имеет нежелательный побочный эффект, заключающийся в том, что ticklabels первой оси могут попасть на левое поле, но вы можете противостоять этому, добавив немного горизонтального пространства перед первым подрисунком. (См. пример кода ниже.)
Я также сделал subfigure
sa немного уже и использовал \hfill
между ними, чтобы добавить пространство, которое заполняет линию.
Тем не менее, если вы не собираетесь добавлять отдельные подписи, то я бы сказал, что вы используете неподходящий инструмент для работы и делаете код длиннее, чем необходимо. Я бы предложил добавить библиотеку groupplots
и pgfplots
добавить все три изображения в одну и ту же groupplot
среду. (Я не подумал об этом в вашем предыдущем вопросе.) groupplots
делает такие вещи очень простыми.
С помощью \captionof
из caption
пакета вы также можете добавлять подзаголовки, размещая \node
s с указанным text width
относительно осей, пример ниже. figure
Хотя, похоже, для получения правильных перекрестных ссылок требуется некоторая манипуляция со счетчиком.
\RequirePackage{luatex85}
\documentclass{article}
\usepackage{pgfplots,caption,subcaption,showframe}
\captionsetup[subfigure]{labelformat=parens}
\usepgfplotslibrary{groupplots}
\pgfplotsset{compat=newest}
\usepackage{cleveref}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\begin{groupplot}[
group style={
group name=G,
group size=3 by 1,
y descriptions at=edge left,
horizontal sep=10pt % adjust as needed
},
enlargelimits=false,
width=0.33\textwidth-width("300"),
height=0.3\textheight,
scale only axis]
\nextgroupplot
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-a};
\nextgroupplot
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-b};
\nextgroupplot
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-c};
\end{groupplot}
\refstepcounter{figure} % to get correct
\node [text width=0.33\textwidth-width("300"),below right,align=center] at (G c1r1.south west) {\captionof{subfigure}{Subcaption for the first plot\label{a}}};
\node [text width=0.33\textwidth-width("300"),below right,align=center] at (G c2r1.south west) {\captionof{subfigure}{Subcaption for the second plot}};
\node [text width=0.33\textwidth-width("300"),below right,align=center] at (G c3r1.south west) {\captionof{subfigure}{Subcaption for the third plot}};
\addtocounter{figure}{-1}
\end{tikzpicture}
\caption{..}
\end{figure}
\begin{figure}
\centering
\pgfmathsetlengthmacro{\myaxiswidth}{0.33\textwidth-width("300 ")}
\hspace*{\dimexpr0.33\textwidth-\myaxiswidth}%
\begin{subfigure}[t]{0.3\textwidth}
\centering % added
\begin{tikzpicture}[trim axis left]
\begin{axis}[enlargelimits=false,width=\myaxiswidth, height=0.3\textheight, scale only axis]
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-a};
\end{axis}
\end{tikzpicture}
\caption{Subcaption for the first plot}
\label{b}
\end{subfigure}%
\hfill
\begin{subfigure}[t]{0.3\textwidth}
\centering % added
\begin{tikzpicture}[trim axis left]
\begin{axis}[enlargelimits=false,width=\myaxiswidth, height=0.3\textheight, scale only axis, ytick=\empty]
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-b};
\end{axis}
\end{tikzpicture}
\caption{Subcaption for the second plot}
\end{subfigure}%
\hfill
\begin{subfigure}[t]{0.3\textwidth}
\centering % added
\begin{tikzpicture}[trim axis left]
\begin{axis}[enlargelimits=false,width=\myaxiswidth, height=0.3\textheight, scale only axis, ytick=\empty]
\addplot graphics [xmin=0, xmax=50, ymin=0, ymax=150] {example-image-c};
\end{axis}
\end{tikzpicture}
\caption{Subcaption for the third plot}
\end{subfigure}
\caption{...}
\end{figure}
\end{document}
Сверху — groupplots
код, снизу — subfigure
код.