# Producing a bar chart with height and color determined by two distinct lists

I am trying to visualize a list of positive integers using a bar chart. In general, integers in that list may appear more than once. For example, I may have

list=Sort@RandomInteger[{1,10},20]

{1, 2, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 9, 10, 10}


The bar chart I have in mind has the shape of

BarChart[DeleteDuplicates[list], BarSpacing -> 0, ChartBaseStyle -> EdgeForm[]]


It basically forgets about the multiplicity of each integer. I prefer to have the multiplicity reflected in the color of the bars, so

BarChart[Tally[list][[All, 2]], BarSpacing -> 0,
ChartBaseStyle -> EdgeForm[], ColorFunction -> "Rainbow"]


has the color scheme I want on my first bar chart.

Here is a slightly more general problem:

Given two lists containing the same number of positive integers, to produce a bar chart with heights and colors determined by the respective lists.

Here's one approach, where we compute the heights using the first part of the results from Tally, and the colors using the second part. Then it's just a simple use of ChartStyle.

list = Sort@RandomInteger[{1, 10}, 20]

(*
==> {1, 2, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 9, 10, 10}
*)

{height, color} = Transpose[Tally[list]]

(*
==> {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 3, 1, 1, 2, 1, 1, 7, 1, 2}}
*)

color = ColorData["Rainbow"] /@ Rescale[color];

BarChart[height, ChartStyle -> color, BarSpacing -> 0,
ChartBaseStyle -> EdgeForm[]]


• +1, beat me by a couple of minutes, too. Also, I didn't realize that Rescale could operate on an entire list at once. Commented Mar 10, 2012 at 4:04
• @rcollyer I love being able to use that feature of Rescale. Commented Mar 10, 2012 at 4:08
• It certainly makes life easier than having to determine min-max first, and then Rescale[#, {min,max}]& /@ list. A lot less code to get wrong. Commented Mar 10, 2012 at 4:26
• @rcollyer Even if you need to specify the min and max, you can still use Rescale[list, {min,max}]. Commented Mar 10, 2012 at 4:40
• I'm aware, now. But, old habits die hard. Commented Mar 10, 2012 at 4:45

In addition to using ChartStyle as Brett shows, you can also use Style directly.

Here using indexed colors:

list = {1, 2, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 9, 10, 10};

dat = # ~Style~ ColorData[3][#2] & @@@ Tally@list;

BarChart[dat, BarSpacing -> 0, ChartBaseStyle -> EdgeForm[]]


dat =