4
$\begingroup$

This is my first time asking a question on the Mathematica StackExchange. As the title says I'm looking for a way to add a horizontal line across my bar graph. The code I currently have is as follows:

BarPi = BarChart[dataExperimentalPi, 
  ChartLabels -> {A, B, C, D, E, F}, PlotRange -> {3, 3.25}]

I have a screenshot of the desired output below (along with my code at present).

Example of what I would like it to look like

Thank you so much for the help in advance.

$\endgroup$

3 Answers 3

5
$\begingroup$

There might be better ways, but you can try Epilog

BarChart[{1, 2, 3}, ChartLabels -> {"A", "B", "C"}, 
 Epilog -> {Red, Thick, Line[{{-0.4, 0.5}, {3.45, 0.5}}]}]

Mathematica graphics

The problem is that I had to try different starting/ending values for the x coordinate to get the red line to match as needed, this is because the scales are different. For your case, you'd have to do the same. Try few values to make the red line starts and ends exactly where you want it.

Another option is to use Show

p1 = BarChart[{1, 2, 3}, ChartLabels -> {"A", "B", "C"}];
p2 = Graphics[{Red, Thick, Line[{{-0.4, 0.5}, {3.45, 0.5}}]}];
Show[p1, p2]

Mathematica graphics

$\endgroup$
5
$\begingroup$

You could use grid lines:

BarChart[
  {1, 2, 3}, ChartLabels -> {"A", "B", "C"},
  GridLines -> {None, {0.5}},
  GridLinesStyle -> Directive[Red, Thick],
  Method -> {"GridLinesInFront" -> True}
]

result with gridlines

$\endgroup$
2
$\begingroup$
  1. nItems can be used to change the number of data items.
  2. A Red line is drawn at the Mean value of the data items.
  3. I have used this answer by @kglr for the FixedBarSpacing option that appears in Red.
  4. My setup: v12.2.0 Win7-x64.
  5. I hope this gives you the necessary pointers.

nItems = 13;
data = 3 + RandomReal[{-0.7, 0.7}, nItems];
m = Mean@data;
BarChart[data
 , ChartLabels -> CharacterRange[
    "A", "Z"][[1 ;; Length@data]
   ]
 , "FixedBarSpacing" -> True
 , PlotRange -> {
   {0.4, Length[data] + 0.4 + 0.1}
   , {0, Ceiling[Max@data, 0.5]}
   }
 , AxesOrigin -> {0.4, 0}
 , AspectRatio -> 1/3
 , ImageSize -> Large
 , ImagePadding -> {{Scaled[0.04], Scaled[0.01]}
   , {Scaled[0.04], Scaled[0.01]}}
 , Epilog -> {
   Red, Thick
   , Line[{
     Scaled[{0, 0}, {0.4, m}]
     , Scaled[{1, 0}, {0.4, m}]
     }]
   }
 ]

enter image description here

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