I am trying to plot a set of data points (scatter
points not linked to each other), where each point has a different color. The color definition is given by predefined rgb
values written in the same file that contains the data.
The following file serves as example:
\usepackage{filecontents}
\begin{filecontents}{test.dat}
x y RED GREEN BLUE
1 11 0.2 0.3 0.5
2 14 0.3 0.3 0.4
4 26 0.1 0.8 0.1
3 39 0.0 0.1 0.9
\end{filecontents}
The x
and y
columns represent the position of the points I want to plot. The next three columns RED
, GREEN
and BLUE
correspond to the associated color values in rgb
format.
What I was trying so far, was to do:
\begin{document}
\pgfplotstableread{test.dat}\test
%number of points to be plotted
\pgfplotstablegetrowsof{\test}
\pgfmathsetmacro{\N}{\pgfplotsretval-1}
\begin{tikzpicture}
\begin{axis}[%
xmin=0, xmax=5,
ymin=0, ymax=45,
width=8cm,
height=6cm,
grid=both,
xlabel=Xtest,
ylabel=Ytest,
]
\foreach \i in {0,...,\N}
{
\definecolor{testcolor}{rgb}{\thisrow{3}, \thisrow{4}, \thisrow{5}}
\addplot[scatter,
only marks,
scatter/use mapped color={draw=none,fill=testcolor},
]
table [x index = 0,y index = 1]{\test};
}
\end{axis}
\end{tikzpicture}
\end{document}
But I am unable to fetch a single row value for the color definition. How can I do this ? I also looked at meta
options, but the color is defined with a single value (linearly) and I need the three components in the color definition.
Best Answer
While it is possible to access table elements by means of
\pgfplotstablegetelem{0}{RED}\of{\test}
, I would recommend to move the code which defines colors into the\addplot
command: pgfplots supports advancedscatter
plots in which you can define how each scatter point it is to be drawn. This is more efficient in TeX.A solution could be
I used
\addplot table {<inline data>};
to reduce the amount of code (which is, however, equivalent to\addplot ... table {\test};
). The key points are:mark=*
sincescatter
does not necessarily assign a plot mark as default.pre marker code
andpost marker code
to define the colors. This is precisely the same way how the defaultscatter
implementation works. In our case, I used\definecolor{rgb}{\pgfplotspointmeta}
, assuming that\pgfplotspointmeta
contains something of sorts<R>,<G>,<B>
.point meta
expression defines\pgfplotspointmeta
in the expected way.\thisrow{RED},...
into\definecolor
here:\thisrow
is only valid whilepgfplots
iterates over the table's row - and it does that just once when it surveys the input coordinates.\edef
means "expanded definition":\edef\temp{...}
defines\temp
to contain the expanded argument.\noexpand
means to not expand the following macro in this context.point meta={TeX code symbolic={<code which defines \pgfplotspointmeta}}
allows us to inject some TeX code to define a symbol - in our case a color triplet.