2
$\begingroup$

I would like to add a legend to the ListPlot defined in the code shown below. Unfortunately, adding PlotLegends -> Automatic to the plot does not work. I was wondering if there are any other ways to add a legend to this plot.

points = 
  Join[
    RandomVariate[
      MultinormalDistribution[{-0.5, 0.25}, 0.07 IdentityMatrix[2]], 1000], 
    RandomVariate[
      MultinormalDistribution[{0.6, -0.1}, 0.03 IdentityMatrix[2]], 1000], 
    RandomReal[{-1.5, 1.5}, {1000, 2}]]; 
skd = SmoothKernelDistribution[points]; 
ListPlot[points, 
  ColorFunction -> Function[{x, y}, Hue[PDF[skd, {x, y}]]], 
  ColorFunctionScaling -> False, AspectRatio -> 1]
$\endgroup$
2
  • $\begingroup$ points = Join[ RandomVariate[ MultinormalDistribution[{-0.5, 0.25}, 0.07*IdentityMatrix[2]], 1000], RandomVariate[MultinormalDistribution[{0.6, -0.1}, 0.03*IdentityMatrix[2]], 1000], RandomReal[{-1.5, 1.5}, {1000, 2}]] skd = SmoothKernelDistribution[points] ListPlot[points, ColorFunction -> Function[{x, y}, Hue[PDF[skd, {x, y}]]], ColorFunctionScaling -> False, AspectRatio -> 1] $\endgroup$
    – Pjana
    Nov 16 '20 at 14:49
  • $\begingroup$ Perhaps you want PlotLegends -> BarLegend[{Hue[#] &, {0, 1}}]? $\endgroup$ Nov 16 '20 at 14:56
2
$\begingroup$

You can add a legend to any expression with Legended. Like so:

Legended[
  ListPlot[points,
    ColorFunction -> Function[{x, y}, Hue[PDF[skd, {x, y}]]],
    ColorFunctionScaling -> False,
    AspectRatio -> 1],
  BarLegend[{Hue, {0, 1}}]]

plot

$\endgroup$
2
$\begingroup$
SeedRandom[1]
points =  Join[
   RandomVariate[MultinormalDistribution[{-0.5, 0.25}, 0.07 IdentityMatrix[2]], 1000], 
   RandomVariate[MultinormalDistribution[{0.6, -0.1}, 0.03 IdentityMatrix[2]], 1000], 
   RandomReal[{-1.5, 1.5}, {1000, 2}]]; 

skd = SmoothKernelDistribution[points]; 

To get a bar legend that matches the pdf values of skd (1) use points with SmoothDensityHistogram with the options ColorFunction -> Hue and PlotLegends -> Automatic and (2) take the second part of the output:

legend = SmoothDensityHistogram[points, 
    ColorFunction -> Hue, PlotLegends -> Automatic][[2]] 

enter image description here

Then we use PlotLegends -> legend with ListPlot:

ListPlot[points, 
   ColorFunction -> Function[{x, y}, Hue[PDF[skd, {x, y}]]], 
   ColorFunctionScaling -> False, AspectRatio -> 1, 
   PlotLegends -> legend]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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