0

I have a file named J.txt that has data in 3 columns, the third being the value for the error bar (symmetrical) like this:

2454501.81752 0.0018087812 9.69699358080375E-005
2454537.77104 0.0030887732 0.0001610068
2454603.70872 0.0022500182 0.0001230047
2454640.56455 0.0013261298 7.57575739971879E-005
2454662.63581 0.0017888998 9.91743434734387E-005

and I have the following code:

import numpy as np
import matplotlib.pyplot as plt

plt.plotfile('J.txt', delimiter=' ', cols=(0, 1),  
             names=('V', 'V-B'), marker='o', markersize=2, markeredgewidth=0.1, markeredgecolor='black', 
             color= 'green', label= "Cluster", linestyle='None', newfig=False)

plt.show()

I'm stuck trying to add the error bars to the plot because I don't know how to relate the columns in the file to plt.errorbar (if that's what I should be using).

Cheers.

4
  • This may not help if you want to use plt.plotfile(), but you could first load the data using numpy with np.loadtxt() and then just use plt.errorbar(), supplying the third column to the yerryerr (or xerr) keyword. Commented Mar 25, 2016 at 4:45
  • I agree with Will Barnes. Separate the loading of the data and the plotting. This way you can also test in between the two operations what your data actually look like after being read in. Commented Mar 25, 2016 at 6:43
  • how do you put the horizontal bars to the upper and lower limit of the error bars? Commented Apr 24, 2020 at 18:38
  • @CharlieParker adding a value to the kwarg capsize in the function plt.plotfile() will do the trick. Commented Jul 18, 2022 at 22:41

1 Answer 1

2

After Will and roadrunner66's suggestions I digged for a solution like that:

import numpy as np
import matplotlib.pyplot as plt

col0 = np.genfromtxt('J.txt', usecols=(0), delimiter=' ', dtype=None)
col1 = np.genfromtxt('J.txt', usecols=(1), delimiter=' ', dtype=None)
col2 = np.genfromtxt('J.txt', usecols=(2), delimiter=' ', dtype=None)

fig, ax1 = plt.subplots()

ax1.plot(col0, col1, c='b', marker='o', markeredgewidth=0, linewidth=0, markersize=3)
ax1.errorbar(col0, col1, yerr=col2, linestyle=' ', c= 'b')
plt.show()

Numpy's np.genfromtxt brings the data like I needed it to and matplotlib's ax1.errorbar lets me put the error bars using the yerr value for the Y axis.

Sign up to request clarification or add additional context in comments.

2 Comments

how do you put the horizontal bars to the upper and lower limit of the error bars?
You need to set a value for the capsize parameter in errorbar, otherwise it will default to 0 and the horizontal bars will not be shown. For my case I would have: ax1.errorbar(col0, col1, yerr=col2, linestyle=' ', c= 'b', capsize=1)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.