
Я придумал несколько небольших команд, чтобы иметь удобную «выноску» для моих заметок; пожалуйста, рассмотрите следующий MWE (там также объясняется проблема):
\documentclass{book}
\usepackage{tikz}
\tikzset{remember picture,
round mark/.style={
circle, draw=yellow, minimum size=5mm, fill opacity=0.5, fill=yellow,
},
}
\usepackage{pgfplots}\pgfplotsset{compat=1.9}
\usepackage{siunitx}
\DeclareSIUnit{\krypt}{\ensuremath{\mathcal{K}r}}
\usepackage{xparse}
\newcommand{\roundmark}[1]{\tikz[overlay, remember picture, baseline=-0.5ex]
\node [round mark, anchor=west] (#1) {};}
\NewDocumentCommand \addline {O{} m m }{%
\begin{tikzpicture}[overlay,remember picture]
\draw[ultra thick, yellow, ->, #1 ] (expl@#2) -- (#3);
\end{tikzpicture}%
}
\NewDocumentCommand \margincallout {O{} m +m }{%
\marginpar{
\begin{tikzpicture}[overlay,remember picture]
\node [ anchor=west, draw=orange, fill=yellow!20,
text width=\marginparwidth, align=left, font=\small,
#1 ] (expl@#2)
at (0,0) {
#3
};
\draw[ultra thick, yellow,->] (expl@#2) -- (#2);
\end{tikzpicture}}%
}
\begin{document}
I can mark thing in \roundmark{a}the main text and then have nice callouts from the marginpar to this point.
\margincallout{a}{This is a callout, a nice one and it's ok.}
% thanks @bloodworks http://tex.stackexchange.com/a/62285/38080
% require package capt-of
\begin{figure}[htb]
\begin{center}
\begin{tikzpicture}[remember picture,
]
\begin{axis}[
width=7cm,
xmin=0, xmax=10, domain=0:10,
enlarge y limits = 0.2,
ylabel = {Sensor R (\si{k\ohm})},
xlabel = {Kryporad (\si{\krypt})},
legend pos = north west,
legend style={nodes=right},
]
\addplot[red] {134 + 18.5*x + 15.0*sin(deg(0.664*x))};
\addplot[blue, dashed] {143 + 16.8*x};
\legend{non-linear fit, linear fit}
\end{axis}
\node [round mark] (hor-axis) at (4,-0.5) {};
\node [round mark] (ver-axis) at (-0.5,4) {};
%\draw (0,0) grid (5,5);
\end{tikzpicture}
\end{center}
\caption{With a bit of guesswork I can mark things in the graphics, too}
\label{fig:calibR}
\end{figure}
\margincallout[yshift=3cm]{hor-axis}{\textbf{Always} name the axis and columns, and use units when needed}
\addline{hor-axis}{ver-axis}
Uncomment the following to see the error:
%But if I want to put the callout \textbf{before} the mark,
%as in \margincallout{future}{A forward callout} it will not work, and give me an error.
%The mark will be \roundmark{future}here, for example.
\end{document}
что выводит приятную (ИМХО) вещь:
Проблема в том, что иногда бывает полезно иметь \margincallout
командудо, который \roundmark
определяет имя узла.
Документу в любом случае потребуется два прохода; я думал, что, возможно, можно написать что-то вроде прямых ссылок для метки... но не могу найти никакого решения.
Можно ли ссылаться на узлы, которые будут решены на следующем проходе?
ОБНОВЛЯТЬ:
Итак, я попробовал с tikzmark
, но, должно быть, здесь что-то странное. Смотрите:
\documentclass{book}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\tikzset{remember picture,
round mark/.style={
circle, draw=yellow, minimum size=5mm, fill opacity=0.5, fill=yellow,
},
}
\usepackage{pgfplots}\pgfplotsset{compat=1.9}
\usepackage{siunitx}
\DeclareSIUnit{\krypt}{\ensuremath{\mathcal{K}r}}
\usepackage{xparse}
\newcommand{\rtikzmark}[1]{\tikzmark[{
\node [baseline=-0.5ex, round mark, anchor=west]{}}]{#1}}
\NewDocumentCommand \addline {O{} m m }{%
\begin{tikzpicture}[overlay,remember picture]
\draw[ultra thick, yellow, ->, #1 ] (expl@#2) -- (pic cs:#3);
\end{tikzpicture}%
}
\NewDocumentCommand \margincallout {O{} m +m }{%
\marginpar{
\begin{tikzpicture}[overlay,remember picture]
\node [ anchor=west, draw=orange, fill=yellow!20,
text width=\marginparwidth, align=left, font=\small,
#1 ] (expl@#2)
at (0,0) {
#3
};
\draw[ultra thick, yellow,->] (expl@#2) -- (pic cs: #2);
\end{tikzpicture}}%
}
\begin{document}
I can mark thing in \rtikzmark{a}the main text and then have nice callouts from the marginpar to this point.
\margincallout{a}{This is a callout, a nice one and it's ok.}
% thanks @bloodworks http://tex.stackexchange.com/a/62285/38080
% require package capt-of
\begin{figure}[htb]
\begin{center}
\begin{tikzpicture}[remember picture,
]
\begin{axis}[
width=7cm,
xmin=0, xmax=10, domain=0:10,
enlarge y limits = 0.2,
ylabel = {Sensor R (\si{k\ohm})},
xlabel = {Kryporad (\si{\krypt})},
legend pos = north west,
legend style={nodes=right},
]
\addplot[red] {134 + 18.5*x + 15.0*sin(deg(0.664*x))};
\addplot[blue, dashed] {143 + 16.8*x};
\legend{non-linear fit, linear fit}
\end{axis}
\node [round mark] at (4,-0.5) {}; \tikzmark{hor-axis};
\node [round mark] at (-0.5,4) {}; \tikzmark{ver-axis};
%\draw (0,0) grid (5,5);
\end{tikzpicture}
\end{center}
\caption{With a bit of guesswork I can mark things in the graphics, too}
\label{fig:calibR}
\end{figure}
\margincallout[yshift=3cm]{hor-axis}{\textbf{Always} name the axis and columns, and use units when needed}
\addline{hor-axis}{ver-axis}
Uncomment the following to see the error:
But if I want to put the callout \textbf{before} the mark,
as in \margincallout{future}{A forward callout} it will not work, and give me an error.
The mark will be \rtikzmark{future}here, for example.
\end{document}
Первый вызов (в тексте) вроде работает, но потом линия не рисуется. А второй и третий вызов (тот, который отмечает точки)вграфик) преобразует всю фигуру в наложение...
Хорошо, что прямой вызов работает, но линия не проведена. Озадачен.
решение1
(Я добавляю этовышепотому что он заменяет исходный ответ, и поэтому кто-то ищет толькочтои не беспокоился окак,когда, и уж точно непочему(Не стоит тратить время на чтение оригинального ответа.)
Stop Press: tikzmark
снова развивается
tikzmark
претерпел значительную эволюцию с момента своего первого появления, в первую очередь, благодаря вопросам на этом сайте. Одной из ключевых особенностей, которые он приобрел на этом пути, была возможность использовать сохраненную им координатупрежнийк его появлению в документе.
Одной из его особенностей, которая была у него с самого начала, было то, что он был предназначен для использованияснаружикоманда \tikz
или tikzpicture
среда. Внутри, думали, тогда у вас будет полный доступ к обычной службе запоминания координат TikZ, и поэтому не было необходимости в \tikzmark
.
Однако вышеупомянутая ключевая особенность заключается в том, чтонетчто-то, что предоставляет TikZ. Нет способа ссылаться на координату внутри tikzpicture
до ее объявления. Так что если кто-то хочет это сделать, нужно что-то новое.
Ключевая особенность этого вопроса в том, что кверент хочет использовать тот же механизм для ссылки на координаты внутри и tikzpicture
снаружи. Так что это предполагает, что правильный способ предоставить эту ясновидческую координатную способность внутри tikzpictures — это расширить tikzmark.
Это оказалось довольно просто. Короче говоря, tikzmark связывает метку с началом tikzpicture, а вся тяжелая работа выполняется в системе координат. Расширение заключается в добавлении потенциального смещения, так что как только tikz определит, где на странице находится начало указанного tikzpicture, он применит смещение. Объедините это с проверкой, чтобы увидеть, находимся ли мы внутри tikzpicture, и все готово.
(Стоит отметить, что если вы перейдете на эту новую версию, вам следует удалить aux-файл перед перекомпиляцией, в противном случае вы получите множество ошибок при первой перекомпиляции.)
Синтаксисвнутриtikzpicture — это \tikzmark{label}{coordinate}
, например \tikmark{a}{(3,4)}
, . Это означает, что координата (pic cs:a)
будет указывать на точку (3,4)
на текущем изображении.
Вы можете загрузить эту новую версию tikzmark с сайтагитхаб: загрузите tikzmark.dtx
и запустите tex tikzmark.dtx
для генерации файлов.
Итак, сновый, улучшенный \tikzmark
, код теперь снова вернулся в разумное состояние:
\documentclass{book}
%\url{http://tex.stackexchange.com/q/295903/86}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\tikzset{remember picture,
round mark/.style={
circle, draw=yellow, minimum size=5mm, fill opacity=0.5, fill=yellow,
},
}
\usepackage{pgfplots}\pgfplotsset{compat=1.9}
\usepackage{siunitx}
\DeclareSIUnit{\krypt}{\ensuremath{\mathcal{K}r}}
\usepackage{xparse}
\newcommand{\rtikzmark}[1]{\tikzmark[{
\node [baseline=-0.5ex, round mark, anchor=west]{}}]{#1}}
\NewDocumentCommand \addline {O{} m m }{%
\begin{tikzpicture}[overlay,remember picture]
\draw[ultra thick, yellow, ->, #1 ] (expl@#2) -- (pic cs:#3);
\end{tikzpicture}%
}
\NewDocumentCommand \margincallout {O{} m +m }{%
\marginpar{
\begin{tikzpicture}[overlay,remember picture]
\node [ anchor=west, draw=orange, fill=yellow!20,
text width=\marginparwidth, align=left, font=\small,
#1 ] (expl@#2)
at (0,0) {
#3
};
\draw[ultra thick, yellow,->] (expl@#2) -- (pic cs:#2);
\end{tikzpicture}}%
}
\begin{document}
I can mark thing in \rtikzmark{a}the main text and then have nice callouts from the marginpar to this point.
\margincallout{a}{This is a callout, a nice one and it's ok.}
% thanks @bloodworks http://tex.stackexchange.com/a/62285/38080
% require package capt-of
\begin{figure}[htb]
\begin{center}
\begin{tikzpicture}[remember picture,
]
\begin{axis}[
width=7cm,
xmin=0, xmax=10, domain=0:10,
enlarge y limits = 0.2,
ylabel = {Sensor R (\si{k\ohm})},
xlabel = {Kryporad (\si{\krypt})},
legend pos = north west,
legend style={nodes=right},
]
\addplot[red] {134 + 18.5*x + 15.0*sin(deg(0.664*x))};
\addplot[blue, dashed] {143 + 16.8*x};
\legend{non-linear fit, linear fit}
\end{axis}
\node [round mark] at (4,-0.5) (hor-axis) {};
\node [round mark] at (-0.5,4) (ver-axis) {};
\node [round mark] at (0,0) (origin) {};
\tikzmark{hor-axis}{(hor-axis)}
\tikzmark{ver-axis}{(ver-axis)}
\tikzmark{origin}{(origin)}
%\draw (0,0) grid (5,5);
\end{tikzpicture}
\end{center}
\caption{With a bit of guesswork I can mark things in the graphics, too}
\label{fig:calibR}
\end{figure}
\margincallout[yshift=4cm]{hor-axis}{\textbf{Always} name the axis and columns, and use units when needed}
\addline{hor-axis}{ver-axis}
\addline{hor-axis}{origin}
Uncomment the following to see the error:
But if I want to put the callout \textbf{before} the mark,
as in \margincallout{future}{A forward callout} it will not work, and give me an error.
The mark will be \rtikzmark{future}here, for example.
\end{document}
(То же изображение, что и ниже)
Исходный ответ:
Вот несколько вещей...
(Во-первых, я нашел ошибку tikzmark
во взаимодействии с marginpar
. У меня есть подозрение, что версия с ошибкой новее, чем версия на CTAN, так как вы не должны были ее получитьчто-либово втором примере, если вы использовали глючную версию. В любом случае, обновленная версиядоступно на github.)
Во-вторых, и что более важно, \tikzmark
он не предназначен для использованиявнутрисреда tikzpicture
. Дела пойдут не так, если вы это сделаете. Это даже серьезнее, чем использование регулярных выражений для разбора HTML. Дело в том, что если вы находитесь внутри tikzpicture
среды, то у вас есть доступ ко всем узлам и координатам позиционирования tikz, и вам не нужен tikzmark.
(Заметьте, неважно, сколько раз я говорю: «Не используйте tikzmark внутри tikzpicture», люди, похоже, хотят его использовать. Может, мне стоит стиснуть зубы и придумать, как заставить это работать.)
Конечно, это означает, что вам нужны две версии кода выноски: одна для случая, когда метка находится в tikzpicture, и одна, когда ее там нет. Вероятно, есть изящные способы закодировать это, чтобы избежать этого, но я медведь с маленьким мозгом и не могу думать так широко в этот час.
Итак, хотя этот вариант никогда не победит в конкурсе стилей, вот рабочая версия вашего кода, которая, по моему мнению, должна дать правильный результат.
\documentclass{book}
%\url{http://tex.stackexchange.com/q/295903/86}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\tikzset{remember picture,
round mark/.style={
circle, draw=yellow, minimum size=5mm, fill opacity=0.5, fill=yellow,
},
}
\usepackage{pgfplots}\pgfplotsset{compat=1.9}
\usepackage{siunitx}
\DeclareSIUnit{\krypt}{\ensuremath{\mathcal{K}r}}
\usepackage{xparse}
\newcommand{\rtikzmark}[1]{\tikzmark[{
\node [baseline=-0.5ex, round mark, anchor=west]{}}]{#1}}
\NewDocumentCommand \addline {O{} m m }{%
\begin{tikzpicture}[overlay,remember picture]
\draw[ultra thick, yellow, ->, #1 ] (expl@#2) -- (pic cs:#3);
\end{tikzpicture}%
}
\NewDocumentCommand \addlineb {O{} m m }{%
\begin{tikzpicture}[overlay,remember picture]
\draw[ultra thick, yellow, ->, #1 ] (expl@#2) -- (#3);
\end{tikzpicture}%
}
\NewDocumentCommand \margincallout {O{} m +m }{%
\marginpar{
\begin{tikzpicture}[overlay,remember picture]
\node [ anchor=west, draw=orange, fill=yellow!20,
text width=\marginparwidth, align=left, font=\small,
#1 ] (expl@#2)
at (0,0) {
#3
};
\draw[ultra thick, yellow,->] (expl@#2) -- (pic cs:#2);
\end{tikzpicture}}%
}
\NewDocumentCommand \margincalloutb {O{} m +m }{%
\marginpar{
\begin{tikzpicture}[overlay,remember picture]
\node [ anchor=west, draw=orange, fill=yellow!20,
text width=\marginparwidth, align=left, font=\small,
#1 ] (expl@#2)
at (0,0) {
#3
};
\draw[ultra thick, yellow,->] (expl@#2) -- (#2);
\end{tikzpicture}}%
}
\begin{document}
I can mark thing in \rtikzmark{a}the main text and then have nice callouts from the marginpar to this point.
\margincallout{a}{This is a callout, a nice one and it's ok.}
% thanks @bloodworks http://tex.stackexchange.com/a/62285/38080
% require package capt-of
\begin{figure}[htb]
\begin{center}
\begin{tikzpicture}[remember picture,
]
\begin{axis}[
width=7cm,
xmin=0, xmax=10, domain=0:10,
enlarge y limits = 0.2,
ylabel = {Sensor R (\si{k\ohm})},
xlabel = {Kryporad (\si{\krypt})},
legend pos = north west,
legend style={nodes=right},
]
\addplot[red] {134 + 18.5*x + 15.0*sin(deg(0.664*x))};
\addplot[blue, dashed] {143 + 16.8*x};
\legend{non-linear fit, linear fit}
\end{axis}
\node [round mark] at (4,-0.5) (hor-axis) {};
\node [round mark] at (-0.5,4) (ver-axis) {};
\node [round mark] at (0,0) (origin) {};
%\draw (0,0) grid (5,5);
\end{tikzpicture}
\end{center}
\caption{With a bit of guesswork I can mark things in the graphics, too}
\label{fig:calibR}
\end{figure}
\margincalloutb[yshift=4cm]{hor-axis}{\textbf{Always} name the axis and columns, and use units when needed}
\addlineb{hor-axis}{ver-axis}
\addlineb{hor-axis}{origin}
Uncomment the following to see the error:
But if I want to put the callout \textbf{before} the mark,
as in \margincallout{future}{A forward callout} it will not work, and give me an error.
The mark will be \rtikzmark{future}here, for example.
\end{document}