TransWikia.com

How can I add plot legends to my list plot?

Mathematica Asked on March 17, 2021

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]

2 Answers

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

Answered by m_goldberg on March 17, 2021

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

Answered by kglr on March 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP