4
$\begingroup$

Let's say I have a list of color names (strings), like this:

samples = {{"blue, red, red"}, {"purple, blue, purple"}, {"blue, blue"}};

Then I can plot the frequency of the words (I remove spaces and split by commas in this case).

data = Flatten[
   StringDelete[#, " "] & /@ (StringSplit[#, ","] & /@ 
      Flatten[samples])];
chart = BarChart[Counts[data]/Length[data], ChartLabels -> Automatic, 
  Frame -> True]

enter image description here

How could I detect the 'categories' and make an appropiate color accordingly?

I look for something like ColorRules -> {"blue" -> Blue, "red" -> Red, "purple" -> Purple} to make the color of each bar corresponding to the color category I'm showing here (I use strings representing colors as an example, in a general application, it can be anything, like {"birds"->Blue, "horses"->Red}, etc)

Thanks!

$\endgroup$

2 Answers 2

4
$\begingroup$

Below is a copy of your input.

samples = {{"blue, red, red"}, {"purple, blue, purple"}, \
{"blue, blue"}}
(* {{"blue, red, red"}, {"purple, blue, purple"}, {"blue, blue"}} *)

data = 
 Flatten[StringDelete[#, " "] & /@ (StringSplit[#, ","] & /@ 
     Flatten[samples])]
(* {"blue", "red", "red", "purple", "blue", "purple", "blue", \
"blue"} *)

I will add an intermediary variable that is not required. Just added to make it easier to follow.

dataCount = Counts[data]/Length[data]
(* <|"blue" -> 1/2, "red" -> 1/4, "purple" -> 1/4|> *)

Use Keys to extract the keys from the association

keys = Keys[dataCount]
(* {"blue", "red", "purple"} *)

Now you can use regular replacement to convert this to a list of colors.

keys /. {"blue" -> Blue, "red" -> Red, "purple" -> Purple}
(* {RGBColor[0, 0, 1], RGBColor[1, 0, 0], RGBColor[0.5, 0, 0.5]} *)

Use this list as the ChartStyle for the BarChart.

BarChart[dataCount,
 ChartLabels -> Automatic,
 Frame -> True,
 ChartStyle -> Keys[dataCount] /. {"blue" -> Blue, "red" -> Red, 
   "purple" -> Purple}
 ]

Mathematica graphics

$\endgroup$
2
$\begingroup$
samples = {{"blue, red, red"}, {"purple, blue, purple"}, {"blue, blue"}};

tally = Tally[Flatten[TextWords /@ samples]];
{keys, counts} = Transpose @ tally;
counts = Normalize[counts, Total];
colors = {Blue, Red, Purple};
coloring = AssociationThread[keys, colors];

bcdata = Labeled[Style[#2, coloring @ #], #] & @@@ tally;
BarChart[bcdata]

enter image description here

Alternatively,

bcdata2 = Labeled[#2 -> coloring @ #, #] & @@@ tally;
BarChart[bcdata2]

same picture

Also

BarChart[counts, ChartStyle -> (coloring/@keys), ChartLabels -> keys]

same picture

$\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.