我正在尝试使用 tikz 创建一个图,其中有几个放置的矩形,其中包裹着文本。我在网上查看了几个示例,出于某种原因,tikz 忽略了我的手动换行符。这是为什么?
如果有更好的方法将文本换入矩形内,请告诉我。
我尝试过放入align=center
,node[Smokey, opacity=1]
但没有任何效果。推荐自TikZ/pgf:为什么 `\newline` 和 `\\` 不能在节点中拆分文本?
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\definecolor{Smokey}{RGB}{88, 89, 91}
\definecolor{TennesseeOrange}{RGB}{255, 130, 0}
\begin{document}
\begin{tikzpicture}[font=\small]
\begin{axis}[%
scale only axis,
axis lines=middle,
axis line style={->},
xmin=0, xmax=8,
xtick={1, 2, 3, 4, 5, 6, 7},
xticklabel style={text height=2ex},
xticklabels={$ps$,$ns$,$\mu s$,$ms$,$s$, $hours$, $years$},
ymin=0,
ymax=5,
ytick={1, 2, 3, 4},
yticklabels={$nm$, $\mu m$, $mm$, $m$}]
\draw [TennesseeOrange, thick,rounded corners, fill=TennesseeOrange, fill opacity=0.2]
(axis cs:.1,.1) rectangle node[Smokey, opacity=1]{I ignore newlines \\ why is \\ this \\ I don't know?} (axis cs:3,3);
\end{axis}
\end{tikzpicture}
\end{document}
答案1
在节点的选项中添加 align=center
:
\documentclass{article}
\usepackage{pgfplots}
\usepackage{siunitx}
\definecolor{Smokey}{RGB}{88, 89, 91}
\definecolor{TennesseeOrange}{RGB}{255, 130, 0}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
scale only axis,
axis lines=middle,
axis line style={->},
xmin=0, xmax=8,
xtick={1, 2, 3, 4, 5, 6, 7},
xticklabel style={text height=2ex},
xticklabels={\si{\ps},\si{\ns},\si{\us},\si{\us},\si{\s}, \si{\hour} , year},
ymin=0,
ymax=5,
ytick={1, 2, 3, 4},
yticklabels={\si{\nm}, \si{\um}, \si{\mm}, \si{\m}}]
\draw [TennesseeOrange, thick, rounded corners, fill=TennesseeOrange, fill opacity=0.2]
(axis cs:.1,.1) rectangle node[Smokey, opacity=1,align=center]{I don't\\ ignore\\ newlines} (axis cs:3,3);
\end{axis}
\end{tikzpicture}
\end{document}
答案2
stackengine
例如,使用包(与您的问题无关)siunitx
来正确显示单位:
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage[usestackEOL]{stackengine}
\usepackage{siunitx}
\definecolor{Smokey}{RGB}{88, 89, 91}
\definecolor{TennesseeOrange}{RGB}{255, 130, 0}
\begin{document}
\begin{tikzpicture}[font=\small]
\begin{axis}[%
scale only axis,
axis lines=middle,
axis line style={->},
xmin=0, xmax=8,
xtick={1, 2, 3, 4, 5, 6, 7},
xticklabel style={text height=2ex},
xticklabels={\si{\ps},\si{\ns},\si{\us},\si{\us},\si{\s}, \si{\hour} , year},
ymin=0,
ymax=5,
ytick={1, 2, 3, 4},
yticklabels={\si{\nm}, \si{\um}, \si{\mm}, \si{\m}}]
\draw [TennesseeOrange, thick,rounded corners, fill=TennesseeOrange, fill opacity=0.2]
(axis cs:.1,.1) rectangle node[Smokey, opacity=1]{\Centerstack{I ignore newlines \\ why is \\ this \\ I don't know?}} (axis cs:3,3);
\end{axis}
\end{tikzpicture}
\end{document}