PGFPlots: line opacity gradient?

Imagine a very simple PGFPlot, e.g.:

\begin{tikzpicture}
\begin{axis}
    \addplot+[no marks]{x^2};
\end{axis}
\end{tikzpicture}

How can I have the line "fade out" from the left to the right of the axis? I.e., how can I gradually vary the opacity of the line depending on the position on the x-axis?

I have managed to achieve this with the markers on a scatter plot with the following code:

\begin{tikzpicture}
\begin{axis}[
    scatter/@pre marker code/.code= {\expandafter\scope\expandafter[opacity=0.1+\pgfplotspointmetatransformed/1000]},
    scatter/@post marker code/.code={\endscope},
]
    \addplot+[scatter, only marks] {x^2};
\end{axis}
\end{tikzpicture}

But I cannot do it with a "no marks" line plot. Ideally, I would like the colour of the line to be defined by the cycle list (rather than having to use a custom made gradient).

Answers


You can use a mesh plot and apply the same approach as you did for markers: by scaling by pgfplotspointmetatransformed.

The key idea is that the mesh implementation reevaluates tikz drawing options for every mesh segment. This is typically done to update the stroke/fill colors - but it works also for opacity or line width.

There is just one error message about \pgfplotspointmetatransformed being undeclared. However, the output is correct! The problem arises because the drawing options are evaluated in different contexts. If you make sure that \pgfplotspointmetatransformed has some useful global value, you do not run into the error message:

\documentclass{standalone}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\def\pgfplotspointmetatransformed{1000}
\begin{axis}
    \addplot+[no marks] {x^2*1.1};
    \addplot+[mesh,line width=8pt,opacity=\pgfplotspointmetatransformed/1000,no marks]{x^2};
\end{axis}
\end{tikzpicture}

\end{document}

Note that the default way that point meta is assigned is using shader=flat mean, i.e. by means of the mean of adjacent point meta data points. Use shader=flat corner to avoid averaging.


You can use a 1D mesh plot and a custom colormap which contains the opacity gradient. The gradient is set along the x-axis by means of the point meta key.

\pgfplotsset{colormap={opaqueblue}{color(0cm)=(blue) ; color(1cm)=(blue!0)}}

\begin{tikzpicture}
\begin{axis}[colormap name=opaqueblue]
    \addplot[thick, mesh, point meta=x] {x^2};
\end{axis}
\end{tikzpicture}

Need Your Help

how do i restart a table's primary key from 0 after deleting rows?

sql sql-server sql-server-2008 primary-key

I have deleted 28 rows from a table. Now, the PK for the table starts at 29. but I want to start from 0 again.