Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I'm using PGF plots and would like to fill two colours to my plot. One colour indicates a positive value, while the other colour for negative values. What I have so far is one colour for the entire plot.

\begin{tikzpicture}[scale=1.4]
\begin{axis}[no markers, scale only axis,ylabel={SOI}, axis on top=true, axis x line=below,axis y line=middle]
\addplot {sin(x)} \closedcycle;
%\addplot [red, fill] table[x=Year,y=INDEX,col sep=comma] {data/SOIvRainfall.csv} \closedcycle;
\end{axis}
\end{tikzpicture}
share|improve this question
1  
I think with only one \addplot is not possible to change the plot color except with colormaps but you can use restrict y to domain ... and make two plots one for positive values and the other for negative with different colors. –  Ignasi Aug 2 '12 at 10:54
add comment

1 Answer

You could use the min(a,b) and max(a,b) functions with the plot as one and zero as the other parameter to get the positive and negative parts of a function. For plots from tables / files you'll have to use y expr and \thisrow{}:

Code

\documentclass[parskip]{scrartcl}
\usepackage[margin=15mm]{geometry}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}
[   xlabel=degree,
    ylabel=sin,
    no markers,
]
\addplot[fill=cyan,draw=blue!50!black,thick] table[x=deg,y expr={max(\thisrow{val},0)}] {
deg val
-400    -0.64
-380    -0.34
-360    0.00
-340    0.34
-320    0.64
-300    0.87
-280    0.98
-260    0.98
-240    0.87
-220    0.64
-200    0.34
-180    0.00
-160    -0.34
-140    -0.64
-120    -0.87
-100    -0.98
-80 -0.98
-60 -0.87
-40 -0.64
-20 -0.34
0   0.00
20  0.34
40  0.64
60  0.87
80  0.98
100 0.98
120 0.87
140 0.64
160 0.34
180 0.00
200 -0.34
220 -0.64
240 -0.87
260 -0.98
280 -0.98
300 -0.87
320 -0.64
340 -0.34
360 0.00
380 0.34
400 0.64
} \closedcycle;

\addplot[fill=orange,draw=orange!50!black,thick] table[x=deg,y expr={min(\thisrow{val},0)}] {
deg val
-400    -0.64
-380    -0.34
-360    0.00
-340    0.34
-320    0.64
-300    0.87
-280    0.98
-260    0.98
-240    0.87
-220    0.64
-200    0.34
-180    0.00
-160    -0.34
-140    -0.64
-120    -0.87
-100    -0.98
-80 -0.98
-60 -0.87
-40 -0.64
-20 -0.34
0   0.00
20  0.34
40  0.64
60  0.87
80  0.98
100 0.98
120 0.87
140 0.64
160 0.34
180 0.00
200 -0.34
220 -0.64
240 -0.87
260 -0.98
280 -0.98
300 -0.87
320 -0.64
340 -0.34
360 0.00
380 0.34
400 0.64
} \closedcycle;
\end{axis}
\end{tikzpicture}

\end{document}

Result

enter image description here

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.