我想创建一个图,其中正值和负值具有不同的颜色。MWE:
\documentclass[tikz]{standalone}
\usepackage{filecontents}
\usepackage{xstring}
\begin{filecontents}{data.txt}
-3.5 nan
-3.375 nan
-3.25 nan
-3.125 0.000121769833828
-3.0 0.000901599938148
-2.875 0.0014834598325
-2.625 0.00588102803508
-2.25 0.0720113632674
-2.125 0.0314393757219
-1.875 0.0306933267171
-1.75 0.07029144932
-1.375 -0.0342012822215
-1.125 -0.0171975784671
-0.75 -0.0405296273749
-0.625 -0.0330713662613
-0.375 -0.00156002201142
0.0 0.044002036309
0.125 0.0634327667271
0.375 0.0153149732892
0.75 -0.00313272843988
0.875 0.0229547104663
1.125 0.0219197613133
1.625 0.0112441717079
1.875 -0.000229179659447
2.0 nan
2.625 nan
\end{filecontents}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\pgfplotsset{onlyPositive/.style={y filter/.code={
\pgfmathparse{##1<0 ? nan : ##1}}, unbounded coords=jump}}
\pgfplotsset{onlyNegative/.style={y filter/.code={
\pgfmathparse{##1>=0 ? nan : ##1}}, unbounded coords=jump}}
\begin{axis}[grid]
\addplot [] file {data.txt};
\addplot [onlyPositive,blue,xshift=2mm,very thick] file {data.txt};
\addplot [onlyNegative,red,xshift=2mm,very thick] file {data.txt};
\end{axis}
\end{tikzpicture}
\end{document}
现在,例如,我希望图表的正部分为蓝色,负部分为红色。我尝试使用数学表达式添加 2 个图,一个用于负值,一个用于正值。但是,由于我现在有两个图(如图所示),因此符号变化之间的图表中存在漏洞。我真正想要的是颜色在线条上自动变化。
谢谢你帮助我!Max
答案1
您需要将路径分解为与 X 轴相交的段。
有一个fillbetween
库pgfplots
允许计算(通常还包括填充)路径段的交叉段。它还可用于绘制单个交叉段:
\documentclass[tikz]{standalone}
\usepackage{filecontents}
\begin{filecontents}{data.txt}
-3.5 nan
-3.375 nan
-3.25 nan
-3.125 0.000121769833828
-3.0 0.000901599938148
-2.875 0.0014834598325
-2.625 0.00588102803508
-2.25 0.0720113632674
-2.125 0.0314393757219
-1.875 0.0306933267171
-1.75 0.07029144932
-1.375 -0.0342012822215
-1.125 -0.0171975784671
-0.75 -0.0405296273749
-0.625 -0.0330713662613
-0.375 -0.00156002201142
0.0 0.044002036309
0.125 0.0634327667271
0.375 0.0153149732892
0.75 -0.00313272843988
0.875 0.0229547104663
1.125 0.0219197613133
1.625 0.0112441717079
1.875 -0.000229179659447
2.0 nan
2.625 nan
\end{filecontents}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=1.11}
\begin{document}
\begin{tikzpicture}
\begin{axis}[grid]
\addplot [draw=none,name path=PATH] file {data.txt};
\path[name path=0 line] (-10,0) -- (10,0);
\draw[
intersection segments={
of=0 line and PATH,
sequence=R2 R4 R6},
blue, very thick];
\draw[
intersection segments={
of=0 line and PATH,
sequence=R3 R5},
red, very thick];
\end{axis}
\end{tikzpicture}
\end{document}
如您所见,该方法不像数学表达式那样自动化。但是,它更精确:交点是明确计算的,每个段都可以明确处理和绘制。 内部的语法是sequence
它是eft 输入段(此处称为)L1
的第一个段,是右输入段(此处称为)的第一个段。我每隔一个段绘制一次;起始偏移和结束段是手动工作。L
0 line
R1
R
PATH