2
$\begingroup$

I want to ask you a problem that I have. I make a non linear fit with some data, and I want to know how can I put the error bars in the plot together with the confidence level of the fit that I perform. I have tried this but doesn't work:

data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}, {6, 4}, {7, 5}};
errors = {0.1, 0.1, 0.2, 0.05, 0.2, 0.15};
nlm = NonlinearModelFit[data, Log[a + b x^2], {a, b}, x, 
   Weights -> 1/errors^2, VarianceEstimatorFunction -> (1 &)];


{bands80[x_], bands90[x_], bands95[x_], bands99[x_]} = 
  Table[nlm["SinglePredictionBands", 
    ConfidenceLevel -> cl], {cl, {0.6, .9, .95, 0.99}}];
Show[Plot[{nlm[x], bands80[x], bands90[x], bands95[x], 
   bands99[x]}, {x, 0, 7}, 
  Filling -> {2 -> {1}, 3 -> {2}, 4 -> {3}, 5 -> {4}}], 
 Graphics[{PointSize[Large], Blue, Point[data]}]]

I have though that maybe using ErrorListPlot[withError, PlotStyle -> Red], could work, but it doesn't...Do you know how to do it? Thanks

$\endgroup$

1 Answer 1

3
$\begingroup$

Your code works:

enter image description here

You can add error bars showing, for example, the range of the 90% confidence level of the fit. (It's up to you to decide if it makes sense to do that...)

bars90 = Table[bands90[d[[1]]] + -d[[2]], {d, data}]
(* {{-2.69685,1.58472},{-0.928799,3.33932},{-1.26757,2.99974},{-2.30463,1.96317},{-1.95044,2.31746},{-2.6485,1.61947}} *)

Needs["ErrorBarPlots`"]
Show[Plot[{nlm[x], bands80[x], bands90[x], bands95[x], bands99[x]}, {x, 0, 7}, 
  Filling -> {2 -> {1}, 3 -> {2}, 4 -> {3}, 5 -> {4}}, AxesOrigin -> {-.1, 0}], 
 ErrorListPlot[
  Table[{data[[n]], ErrorBar[bars90[[n]]]}, {n, Length[data]}], PlotMarkers -> {Automatic, Medium}, PlotStyle -> Blue]]

enter image description here

Or, per JimB's suggestion, add error bars corresponding to the values in the list errors (this makes more sense to me):

Show[Plot[{nlm[x], bands80[x]}, {x, 0, 7}, Filling -> {2 -> {1}}, AxesOrigin -> {-.1, 0}], 
 ErrorListPlot[
  Table[{data[[n]], ErrorBar[errors[[n]] {-1, 1}]}, {n, Length[data]}], PlotMarkers -> {Automatic, Tiny}, PlotStyle -> Blue]]

enter image description here

(The implementation of error bars has changed in v.12 - this is for earlier versions.)

$\endgroup$
3
  • $\begingroup$ I think the OP means error bars based on the list errors. I'm assuming those are standard errors for the y-values. (But I've been wrong many times before.) $\endgroup$
    – JimB
    Jul 6, 2019 at 4:29
  • $\begingroup$ Thanks, problem solved! $\endgroup$
    – Joe
    Jul 6, 2019 at 14:10
  • $\begingroup$ @JimB That sounds right, thanks. I added it to the answer. $\endgroup$
    – MelaGo
    Jul 6, 2019 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.