Pygmt.plot errorbars

When using pygmt.plot with errorbars, is there a way to pass the x, y errors as arrays or does this only work with files? The function definition seems to allow only for x/y arrays or a data file with errors in columns. I’d like to avoid having to write a file when I already got everything in a pandas dataframe. If pyGMT ends up writing the file itself to pass to GMT, I may as well do that.

Hi @rgrapenthin. Just to confirm, do you have your data in a pandas.DataFrame with ‘x’, ‘y’ and ‘error’ columns? Have you tried doing fig.plot(data=df, error_bar=True, ...), where df is your dataframe?

We have an open issue on GitHub at https://github.com/GenericMappingTools/pygmt/issues/735 which would allow passing in an array to the error_bar parameter, but that might take a while to get in (unless you or someone wants to submit a Pull Request).

Thanks - I couldn’t get the data=df solution to work. Writing a txt file with 4 columns for x,y,xerr,yerr does the job for now. Thanks.

Ah ok, so you have 4 columns. Could you post the output of df.head() (i.e. the first 5 rows) of your dataframe, and the fig.plot command you used? I feel like there should be a way to get data=df to work, but just need to check first.

Here’s an example:

                   x    y  x-error  y-error
0  181.89470 -4.0      0.0      1.0
1  181.89470 -4.0      0.0      1.0
2  195.63454 -4.0      0.0      1.5
3  195.63454 -4.0      0.0      1.5
4  195.63454 -4.0      0.0      1.5

Ah right, I just remembered that the data parameter in fig.plot currently accepts numpy.ndarray and not pandas.DataFrame objects. So you’ll need to do df.to_numpy() first like the example below (I’ve edited your sample data slightly):

import pandas as pd
import pygmt

df = pd.DataFrame(
    data={
        "x": [181.89470, 181.89470, 195.63454, 195.63454, 195.63454],
        "y": [-4.0, -4.0, -4.0, -4.0, -4.0],
        "x-error": [0.5, 0.0, 0.0, 0.5, 0.0],
        "y-error": [1.0, 1.0, 1.5, 1.5, 1.5],
    }
)

fig = pygmt.Figure()
fig.plot(data=df.to_numpy(), region=[180., 198., -6., -2.], error_bar=True, frame=True)
fig.show()

produces

As an aside, you can automatically get the bounding box region using pygmt.info, something like so:

region = pygmt.info(table=df[["x", "y"]], per_column=True, spacing="1/3+r5")
print(region)
# [181. 196.  -6.  -3.]

May need to adjust the spacing (I) setting a bit to include the length of your error-bars, see gmtinfo — GMT 6.1.1 documentation.

Let me know if you need any other help with your plot :smiley:

1 Like