我必须绘制多个像这样的节点:
\node[circle, minimum size=2cm] (P0) at (0,0) {$1$};
\node[circle, minimum size=2cm, fill=red] (P1) at (1,0) {$2$};
\node[circle, minimum size=2cm, fill=black] (P2) at (2,0) {$3$};
但每次我有共同的圆和最小尺寸时,我都会尝试做这样的事情:
\newcommand{\NodeClassic}{circle, minimum size=2cm}
\newcommand{\NodeRed}{circle, minimum size=2cm, fill=red}
\newcommand{\NodeBlack}{circle, minimum size=2cm, fill=black}
之后 :
\node[\NodeClassic] (P0) at (0,0) {$1$};
\node[\NodeRed] (P1) at (1,0) {$2$};
\node[\NodeBlack] (P2) at (2,0) {$3$};
像这样,我可以添加一些参数:
\node[\NodeClassic, yellow] (P0) at (0,0) {$1$};
我的文件:
\documentclass[14pt]{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\newcommand{\NodeClassic}{circle, minimum size=2cm}
\newcommand{\NodeRed}{circle, minimum size=2cm, fill=red}
\newcommand{\NodeBlack}{circle, minimum size=2cm, fill=black}
\begin{document}
\begin{tikzpicture}
\node[\NodeClassic] (P0) at (0,0) {$1$};
\node[\NodeRed] (P1) at (1,0) {$2$};
\node[\NodeBlack] (P2) at (2,0) {$3$};
\end{tikzpicture}
\end{document}
Overleaf 上的错误消息:
Package pgfkeys Error: I do not know the key '/tikz/circle, minimum size=2cm, fill=red' and I am going to ignore it. Perhaps you misspelled it.
See the pgfkeys package documentation for explanation.
Type H <return> for immediate help.
...
l.16 \node[\NodeRed]
(P1) at (1,0) {$2$};
我已经在 \newcommand 中尝试了 \def\command{params} 或 \tikz{params} 谢谢,
答案1
您应该使用样式:
\documentclass{article}
\usepackage{tikz}
\tikzset{
NodeClassic/.style={draw,circle, minimum size=2cm},
NodeRed/.style={circle, minimum size=2cm, fill=red},
NodeBlack/.style={circle, minimum size=2cm, fill=black!20},
}
\begin{document}
\begin{tikzpicture}
\node[NodeClassic] (P0) at (0,0) {$1$};
\node[NodeRed] (P1) at (2,0) {$2$};
\node[NodeBlack] (P2) at (4,0) {$3$};
\end{tikzpicture}
\end{document}
我改变了选项以绘制白色圆圈并减少黑色节点中的黑色,只是为了看到节点内容。
没有14pt
选项article
。
答案2
您要查找的变量称为“样式”。样式也可以有参数。例如,
mynode/.style={circle,minimum size=2cm,fill=#1},
mynode/.default={white}
定义一个mynode
带有一个参数(填充颜色)的样式。其默认值为white
。
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[
mynode/.style={circle,minimum size=2cm,fill=#1},
mynode/.default={white}
]
\node[mynode] (P0) at (0,0) {$1$};
\node[mynode=red] (P1) at (1,0) {$2$};
\node[mynode=black] (P2) at (2,0) {$3$};
\end{tikzpicture}
\end{document}