我正在尝试编写一些 tikz 代码,以便图表可以在文档中重复多次,并保持一致的格式。
一切进展顺利,直到我决定根据在“\myGraph”中输入的值来改变点的颜色。
所有大于 5 的值都应显示为红色,所有小于 5 的值都应显示为绿色。
我能想到的最好的办法如下,我认为我编写的代码有效地使中间点(最小/最大数据值)以上的所有值变为红色,中间点以下的所有值变为绿色。因此,在某些情况下这样做没问题,但在其他情况下则不行。
我需要换线
\ifdim\pgfplotspointmetatransformed pt<500pt
类似于
\ifdim\pgfplotspointmeta pt<5
但这不起作用。有人能帮忙吗?
非常感谢!
\documentclass{article}
\usepackage{tikz,pgfplots}
\newcommand{\myGraph}[3]
{
\begin{tikzpicture}[scale=0.5]
\begin{axis}[
scatter/@pre marker code/.code={%
\ifdim\pgfplotspointmetatransformed pt<500pt
\def\markopts{fill=green}%
\else
\def\markopts{fill=red}
\fi
\expandafter\scope\expandafter[\markopts]
},%
scatter/@post marker code/.code={%
\endscope
},enlargelimits=0.1,ymin=0,ymax=10,/pgf/number format/1000 sep={}]
\addplot[scatter, line width=3pt, black,dashed, mark=*, mark options= {scale=4,solid}] coordinates {%
(2017, #1)
(2019, #2)
(2021, #3)
};
\end{axis}
\end{tikzpicture}
}
\begin{document}
First points should be green (2017,2019), last point should be red (2021).
\myGraph{1}{2}{7}
First point and last should be red (2017,2021), middle point should be green (2019).
\myGraph{9}{4}{9}
But ...
\myGraph{7}{7}{8}
all points should be red.
\end{document}
答案1
您只需使用提供给键的数学函数并定义由所需颜色组成的point meta
自定义即可获得所需的结果。colormap
% used PGFPlots v1.14
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\newcommand{\myGraph}[3]{
\begin{tikzpicture}[scale=0.5]
\begin{axis}[
enlargelimits=0.1,
ymin=0,
ymax=10,
/pgf/number format/1000 sep={},
% create custom colorbar for the two colors you need
colormap={my colormap}{
color=(green)
color=(red)
},
]
\addplot [
scatter,
line width=3pt,
black,
dashed,
mark=*,
mark options={scale=4,solid},
% ---
% apply here the function you need for the meta data
point meta={ifthenelse(y>5,1,0)},
% ... and set the limits of the `point meta' data (by hand)
% (the automatic approach doesn't work if only 1 value is
% present which is the case for the third example)
point meta min=0,
point meta max=1,
] coordinates {
(2017, #1)
(2019, #2)
(2021, #3)
};
\end{axis}
\end{tikzpicture}
}
\begin{document}
\myGraph{1}{2}{7}
\myGraph{9}{4}{9}
\myGraph{7}{7}{8}
\end{document}