4
$\begingroup$

Is there a way to add a legend to a SmoothDensityHistogram?

DensityHistogram accepts the ChartLegends option. Other plots accept the PlotLegends. However, the SmoothDensityHistogram does not accept any of them. Is there another solution?

$\endgroup$
1
  • 2
    $\begingroup$ a workaround: use DensityPlot[ PDF[SmoothKernelDistribution[data], {x, y}], {x, -3, 3}, {y, -3, 3}, PlotLegends -> Automatic]? $\endgroup$
    – kglr
    Commented Dec 22, 2019 at 0:05

2 Answers 2

6
$\begingroup$

Update: A slightly more direct approach to construct the bar legend using "PDFValues" property of data distribution object returned by SmoothKernelDistribution:

Legended[SmoothDensityHistogram[data, Automatic, "PDF"], 
 BarLegend[{"M10DefaultDensityGradient", {0, Max @ skd["PDFValues"]}}]]

enter image description here

Original answer:

A workaround: (1) Use the pdf of the SmoothKernelDistribution of data (using the same bandwidth and kernel specs as in your SmoothDensityHistogram) in a DensityPlot with the option PlotLegends and (2) extract the legend (the second part) from the output and add it to your SmoothDensityHistogram it using Legended.

SeedRandom[1]
data = RandomVariate[BinormalDistribution[.5], 100];
skd = SmoothKernelDistribution[data];

legend = DensityPlot[Evaluate@PDF[skd, {x, y}], {x, -3, 3}, {y, -3, 3}, 
    PlotLegends -> Automatic][[2]];

Legended[SmoothDensityHistogram[data, Automatic, "PDF"], legend]

enter image description here

$\endgroup$
3
  • 1
    $\begingroup$ At that point why not just use NMaximize on the SmoothKernelDistribution and create the BarLegend explicitly? $\endgroup$
    – b3m2a1
    Commented Dec 22, 2019 at 0:48
  • $\begingroup$ @b3m2a1, I updated with a more direct way to get the peak value of pdf. $\endgroup$
    – kglr
    Commented Dec 22, 2019 at 1:16
  • 1
    $\begingroup$ Nice! I didn't know about that property but I expect I will find myself using it $\endgroup$
    – b3m2a1
    Commented Dec 22, 2019 at 1:16
4
$\begingroup$
Clear["Global`*"]

SeedRandom[1234]

data = RandomVariate[BinormalDistribution[.5], 100];

peak = MaxValue[PDF[SmoothKernelDistribution[data], {x, y}], {x, y}];

Legended[
 SmoothDensityHistogram[data, Automatic, "PDF", 
  ColorFunction -> "DarkRainbow"],
 BarLegend[{"DarkRainbow", {0, peak}}]]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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