0

I have the following list of data:

{{1, 3}, {1, 4}, {1, 2}, {1, 1}, {2, 1}, {2, 2}, {2, 3}, {2, 3},{2,3}, {2, 3}, {3, 4}, {3, 4}, {3, 4}, {3, 5}, {3, 6}, {4,1}, {4, 2}, {4, 3}, {4,2}, {4, 2}};

data visualisation

How can I generate an ErrorListPlot from these set of points? The points used in the ErrorListPlot should be the mean value of the y-values of each x-coordinate. The positive error should go to the maximum value for an x-coordinate and the negative error to the minimum value of an x-coordinate.

corey979
  • 23,947
  • 7
  • 58
  • 101

3 Answers3

1

Step-by-step for easier comprehension:

Needs["ErrorBarPlots`"]
data = {{1, 3}, {1, 4}, {1, 2}, {1, 1}, {2, 1}, {2, 2}, {2, 3}, {2, 
    3}, {2, 3}, {2, 3}, {3, 4}, {3, 4}, {3, 4}, {3, 5}, {3, 6}, {4, 
    1}, {4, 2}, {4, 3}, {4, 2}, {4, 2}};
data2 = {{Mean@#[[1]], Mean@#[[2]]}, 
    Abs@(Mean@#[[2]] - MinMax@#[[2]])} & /@ 
  Transpose /@ GatherBy[data, First]

{{{1, 5/2}, {3/2, 3/2}}, {{2, 5/2}, {3/2, 1/2}}, {{3, 23/5}, {3/5, 7/ 5}}, {{4, 2}, {1, 1}}}

data3 = {#[[1]], ErrorBar[0, {-1, 1} #[[2]]]} & /@ data2

{{{1, 5/2}, ErrorBar[0, {-(3/2), 3/2}]}, {{2, 5/2}, ErrorBar[0, {-(3/2), 1/2}]}, {{3, 23/5}, ErrorBar[0, {-(3/5), 7/5}]}, {{4, 2}, ErrorBar[0, {-1, 1}]}}

ErrorListPlot[data3, PlotRange -> {All, {0, 6}}]

enter image description here

corey979
  • 23,947
  • 7
  • 58
  • 101
1

Here is a function to preprocess the data as requested, to make it suitable for ErrorListPlot to process:

data = {{1, 4}, {1, 2}, {1, 1}, {2, 1}, {2, 2}, {2, 3}, {2, 
     3}, {2, 3}, {2, 3}, {3, 4}, {3, 4}, {3, 4}, {3, 5}, {3, 6}, {4, 
     1}, {4, 2}, {4, 3}};
Needs["ErrorBarPlots`"];

formatForErrorListPlot[data_] := 
  Block[{gatheredData, sortedYData, meanY},
   gatheredData = GatherBy[data, First];
   Table[
    sortedYData = MinMax@dataForX[[All, 2]];
    meanY = Mean@dataForX[[All, 2]];
    {
     {dataForX[[1, 1]], meanY},
     ErrorBar[{sortedYData[[1]], sortedYData[[2]]} - meanY]
     },
    {dataForX, gatheredData}
    ]
   ];

ErrorListPlot[formatForErrorListPlot@data, 
 PlotRange -> {{0, 5}, {0, 6}}]

enter image description here

glS
  • 7,623
  • 1
  • 21
  • 61
1

With so little data and integer data with so many ties, error bars are unlikely to give a good summary of your data. (Someone - like a supervisor - might be telling you to do this and while I can't help that, I feel your pain.)

You might consider a small amount of jittering to display the data:

data = {{1, 3}, {1, 4}, {1, 2}, {1, 1}, {2, 1}, {2, 2}, {2, 3}, {2, 3}, {2, 3}, {2, 3},
   {3, 4}, {3, 4}, {3, 4}, {3, 5}, {3, 6}, {4, 1}, {4, 2}, {4, 3}, {4, 2}, {4, 2}};
n = Length[data];
jitter = Transpose[{RandomReal[{-0.05, 0.05}, n], RandomReal[{-0.1, 0.1}, n]}];
ListPlot[data + jitter]

data with jitter

JimB
  • 41,653
  • 3
  • 48
  • 106