# Legends with Graphics object

I have a 3 column data, x-coordinate, y-coordinate and a weight to color that particular point. As far as I know, there is no inbuilt Mathematica function that allows me to do so. So I am trying this with Grphics objects in the following way,

• This is what my typical data looks for this particular plot

data = Table[{x, Sin[x], Sin[4*x]}, {x, -Pi, Pi, 0.001}];

• I am using this data as my x,y coordinates and color in the following way

plot = Graphics[
Table[{Blend[{Red, Blue}, v[]], Point[{v[], v[]}]}, {v,
data}], Axes -> True] • I making the bar legend like this

legend = BarLegend[{Blend[{Red, Blue}, #] &, {-1, 1}}] • Legended function does the job

Legended[plot, legend] Although this does the job, the legend is out of proportion to the plot. Is there a better (natural) way of doing this?

• Show[Legended[plot, legend], AspectRatio -> 1/GoldenRatio] Dec 7, 2022 at 16:39

If you prefer to keep the actual aspect ratio of the points, you can make the legend smaller with the LegendMarkerSize option.

Also, the VertexColors option of Point will simplify the code:

points = Most /@ data;
colors = Blend[{Red, Blue}, Last[#]] & /@ data;
legend = BarLegend[{Blend[{Red, Blue}, #] &, {-1, 1}}, LegendMarkerSize -> 150];

Legended[Graphics[Point[points, VertexColors -> colors],Axes -> True], legend]


With a large number of points, you may prefer to plot a line instead of individual points. For that, replace Point by Line in the Graphics.

Another option is ListLinePlot with a ColorFunction to get the color:

Legended[
ListLinePlot[points, ColorFunction -> (Blend[{Red, Blue}, Sin[4 #1]] &)],
legend ]