I tried to use tikz
and pgfplots
packages in order to fill different areas under a curve with different colors.
The issue is in the script below. When I define the area's draw pattern for two first areas, it seems ok, as it gives me red and cyan dashed lines. I specify green as pattern color for the third one but the fill color remains cyan. Can anyone give me a hint to solve this. I want to have multiple filled areas with different filling colors.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{patterns}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\usepgfplotslibrary{fillbetween}
\begin{document}
\begin{tikzpicture}
\tikzset{
hatch distance/.store in=\hatchdistance,
hatch distance=10pt,
hatch thickness/.store in=\hatchthickness,
hatch thickness=2pt
}
\makeatletter
\pgfdeclarepatternformonly[\hatchdistance,\hatchthickness]{flexible hatch}
{\pgfqpoint{0pt}{0pt}}
{\pgfqpoint{\hatchdistance}{\hatchdistance}}
{\pgfpoint{\hatchdistance-1pt}{\hatchdistance-1pt}}%
{
\pgfsetcolor{\tikz@pattern@color}
\pgfsetlinewidth{\hatchthickness}
\pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
\pgfpathlineto{\pgfqpoint{\hatchdistance}{\hatchdistance}}
\pgfusepath{stroke}
}
\begin{axis}[
xmin=0,xmax=4,
xlabel={k'},
ymin=0,ymax=1,
axis on top,
legend style={legend cell align=right,legend plot pos=right}]
\addplot[name path=A,color=red,domain=0:4,samples=100] {1/(x+1)};
\path[name path=B] (axis cs:\pgfkeysvalueof{/pgfplots/xmin},0) -- (axis cs:\pgfkeysvalueof{/pgfplots/xmax},0);
\addplot+[draw,pattern=flexible hatch,pattern color=red]
fill between[
of=A and B,
soft clip={domain=0:.25},
];
\addplot[pattern=flexible hatch,pattern color=cyan,draw=blue,hatch distance=5pt, hatch thickness=0.5pt]
fill between[
of=A and B,
soft clip={domain=0.25:0.5},
];
\addplot[pattern=flexible hatch,pattern color=green,draw=blue,hatch distance=5pt, hatch thickness=0.5pt]
fill between[
of=A and B,
soft clip={domain=0.5:0.9},
];
\end{axis}
\end{tikzpicture}
\end{document}
Best Answer
The problem lays in the definition of your custom pattern. With the link provided by Ross in the comments below this answer one can modify your definition which then works perfectly fine.
For more details please have a look at the comments in the code.