I have the following for a dataset, but I do not have the underlying data:
- Mean
- Median
- Q1
- Q3
- range OR max(data) & min(data)
Is it possible for me to draw the BoxWhiskerChart?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityYou can use the option Method
with suboption "BoxRange"
:
ClearAll[boxRange]
boxRange = #[[{5, 3, 2, 4, 6}]] &;
Examples:
summary = {mean, median, q1, q2, min, max} = {5, 6, 3, 7, 1, 9};
summaries = {summary , 2 + summary , 1 + summary};
BoxWhiskerChart[summaries,
ChartStyle -> 97,
Method -> {"BoxRange" -> boxRange},
ChartElementFunction -> "GlassBoxWhisker"]
If you need to add the mean marker, you can pre-process input data to create new lists with the required means:
ClearAll[preProcess]
preProcess = Module[{d = Append[#, t]}, d /. Solve[Mean[d] == d[[1]], t][[1]]] &;
BoxWhiskerChart[preProcess /@ summaries, {{"MeanMarker", 1, Red}},
ChartStyle -> 97,
Method -> {"BoxRange" -> boxRange},
ChartElementFunction -> "GlassBoxWhisker"]
Update: An alternative way to add mean markers is to use a custom ChartElementFunction
:
ClearAll[ceF]
ceF[f_: "BoxWhisker"] := {ChartElementData[f][##], PointSize[Large],
If[#3 === {}, {}, Point@Thread[{Mean[#[[1]]], #3[[1]]}]], White,
Thick, Dashed, Line[Thread[{#[[1]], #2[[1]]}]]} &;
BoxWhiskerChart[summaries,
ChartStyle -> 98,
Method -> {"BoxRange" -> boxRange},
ChartElementFunction -> ceF["GlassBoxWhisker"]]
The function ceF
can also be used to show outliers by using them as metadata in the first argument of BoxWhiskerChart
:
outliers = {{12, 13, 14}, {1, 13, 15}, {12, 13}};
BoxWhiskerChart[Thread[summaries -> outliers],
ChartStyle -> 98,
Method -> {"BoxRange" -> boxRange},
ChartElementFunction -> ceF["GlassBoxWhisker"]]
Epilog
to add outliers.
$\endgroup$
Here is a quick and dirty way to do it..
val = {{1, 4, 9/2, 5, 9}, {4, 5, 11/2, 6, 8}};(*min,Q1,Median,Q3,max,*)
col = ColorData[97, #] & /@ Range@Length@val;
fence = 0.05;
boxWidth = 0.1;
Show[Table[Graphics[{Black,
(*wisker*)Line[{{i, val[[i, 1]]}, {i, val[[i, 5]]}}],
(*lower fence*)
Line[{{i - fence, val[[i, 1]]}, {i + fence, val[[i, 1]]}}],
(*upper fence*)
Line[{{i - fence, val[[i, 5]]}, {i + fence, val[[i, 5]]}}],
(*box*)col[[i]],
Rectangle[{i - boxWidth, val[[i, 2]]}, {i + boxWidth,
val[[i, 4]]}],
(*median*)Red,
Line[{{i - boxWidth, val[[i, 3]]}, {i + boxWidth, val[[i, 3]]}}]
}, Frame -> True, AspectRatio -> 1/1.2], {i, Length@val}]]