5
$\begingroup$

I'm trying to do some bar charts and pie charts in Mathematica, but I can't figure out how to make the legend colors correspond to the actual colors on the charts. I'm running

10.4.0 for Linux x86 (64-bit) (February 26, 2016)

The code that I've got is:

PieChart[
 {1, 2, 3, 4},
 ColorFunction -> Function[{angle}, ColorData["DarkRainbow"][angle]],
 ChartLegends -> {"This", "is", "the wrong", "color"}
 ]

What I get is the following:

enter image description here

This persists for BarChart as well, I haven't tried any others, but I'm guessing it has something to do with the legending options in general.

Any idea how to make the ChartLegends behave according to the ColorFunction? I've been trying to go through the documentation, but it's not exactly as detailed as I'd like it to be.

$\endgroup$
1
  • $\begingroup$ Function[{angle}, ColorData["DarkRainbow"][angle]] is in most cases the same as ColorData["DarkRainbow"]. $\endgroup$
    – Szabolcs
    Feb 18, 2017 at 23:22

1 Answer 1

5
$\begingroup$

Use ChartStyle -> "DarkRainbow" instead of ColorFunction.

ChartStyle determines the list of colours to be used.

ColorFunction determines how to compute the colour from each value. Two pie slices of the same size will have the same colour when you use ColorFunction. I think that in this situation, it makes no sense to have a separate legend entry for each slice.

However, if you still decide to use ColorFunction, you can use an explicit SwatchLegend specification in ChartLegends, with an explicit (manually computed) list of colours.

$\endgroup$
2
  • $\begingroup$ So basically, if I have some data in the form of {labels,values} that I want to plot using BarChart or PieChart, and use the legending according to the color on the plot, I should do something like: ColorFunction->Function[whatever],...,ChartLegends->SwatchLegend[Function[whatever]/@{scaledValues},labels]? $\endgroup$
    – blueshift
    Feb 18, 2017 at 22:41
  • $\begingroup$ @blueshift Not unless you want to colour the bars according to their height (in which case the use of a swatch legend is IMO misleading—a bar legend would fit better). $\endgroup$
    – Szabolcs
    Feb 18, 2017 at 23:21

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.