3
$\begingroup$

How can I label a table of histograms with the names of the data symbols, not the data themselves?

If I want to make a table of plots with each plot labeled with the name of the function it plots, this is simple:

f[x_] := x; g[x_] := x^2;
Table[Plot[p[x], {x, -1, 1}, PlotLabel -> p], {p, {f, g}}]

However, if I want to do the same for Histogram, I have not figured out how. I have tried various combinations using ToString, Hold, HoldForm, and Unevaluated, as well as ChartLabels. For example,

l = RandomReal[{0, 1}, 20]; m = RandomReal[{0, 1}, 20];
Table[Histogram[p, PlotLabel -> p], {p, {l, m}}]

does not work, as the labels are the values of l and m, not the strings l and m.

The same question applies to the format analogous to

Plot[#[x], {x, -1, 1}, PlotLabel -> #] & /@ {f, g}

which works for Plot but not for Histogram.

$\endgroup$

1 Answer 1

3
$\begingroup$

The difference is that in your first example, f doesn't evaluate to anything, only f[x] does. For your second example however, l is already evaluated to the list of values.

There are various ways to go about this, here are some:

l = RandomReal[{0, 1}, 20]; m = RandomReal[{0, 1}, 20];

Table[Histogram[ReleaseHold@p, PlotLabel -> p], {p, {HoldForm[l], HoldForm[m]}}]
Histogram[ReleaseHold@#, PlotLabel -> HoldForm@#] & /@ Unevaluated /@ Unevaluated@{l, m}
Function[, Histogram[ReleaseHold@#, PlotLabel -> HoldForm@#], HoldFirst] /@ Unevaluated@{l, m}
KeyValueMap[Histogram[#2, PlotLabel -> #] &, <|"l" -> l, "m" -> m|>]

l2[] = RandomReal[{0, 1}, 20]; m2[] = RandomReal[{0, 1}, 20];
Table[Histogram[p[], PlotLabel -> p], {p, {l2, m2}}]

enter image description here

The first three solutions show various ways of preventing premature evaluation of l and m. The fourth solution shows how you can use the keys of an Association as labels for the plots. Finally, the last solution shows how to imitate the behavior of your first example

$\endgroup$
2
  • $\begingroup$ Maybe obvious from context, but l2 and m2 in your fourth method are undefined. Also, a more verbose answer using #4 is exactly what I was typing up when you answered :). $\endgroup$ Jul 24, 2021 at 21:45
  • $\begingroup$ @NonDairyNeutrino Thanks! I completely forgot to copy that line... $\endgroup$
    – Lukas Lang
    Jul 24, 2021 at 21:47

Your Answer

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

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