# Filter data within a polygon

**URL:** <https://forum.generic-mapping-tools.org/t/filter-data-within-a-polygon/3784>\
**Category:** PyGMT Q&A\
**Created:** [March 26, 2023, 3:00am UTC](https://forum.generic-mapping-tools.org/t/filter-data-within-a-polygon/3784 "2023-03-26T03:00:33Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![tonino13](https://yyz1.discourse-cdn.com/flex047/user_avatar/forum.generic-mapping-tools.org/tonino13/32/1440_2.png) [@tonino13](https://forum.generic-mapping-tools.org/u/tonino13)\
**Post date:** [March 26, 2023, 3:00am UTC](https://forum.generic-mapping-tools.org/t/filter-data-within-a-polygon/3784/1 "2023-03-26T03:00:33Z")

</div>

Dear all,

If I would like to plot the data within a polygon in PyGMT v0.7 under ubuntu, will be it possible?

I worked around with this code:

```
df = pd.read_csv('example_cat.dat', sep=',')

    polygon = '/home/asus/Documents/PyTools/Points/Sipesipe_poly_2.txt'

    # Read in polygon coordinates
    with open(polygon) as f:
        lines = f.readlines()
        coords = [[float(x) for x in line.strip().split()] for line in lines]

    # Filter data within the polygon using pandas
    mask = (df['Lon'] >= coords[0][0]) & (df['Lon'] <= coords[1][0]) & \
           (df['Lat'] >= coords[0][1]) & (df['Lat'] <= coords[2][1])
    df_within_polygon = df[mask]

```

I attach the polygon (Sipesipe\_polyu\_2.txt) and the catalog ([example\_cat.dat](https://forum.generic-mapping-tools.org/uploads/short-url/j9cT7VZvSvevvhEUq1kSalnLBgv.dat) (2.9 KB) )  
[Sipesipe\_poly\_2.txt](https://forum.generic-mapping-tools.org/uploads/short-url/l55UWbMiLXWW2FsEJNV6GDcFztv.txt) (145 Bytes)

Is there any geopandas within Pygmt to enhance the code I showed?

Thank you.  
Tonino

---

<div class="post-metadata">

**Author:** ![yvonnefroehlich](https://yyz1.discourse-cdn.com/flex047/user_avatar/forum.generic-mapping-tools.org/yvonnefroehlich/32/5064_2.png) [@yvonnefroehlich](https://forum.generic-mapping-tools.org/u/yvonnefroehlich)\
**Post date:** [March 27, 2023, 7:18pm UTC](https://forum.generic-mapping-tools.org/t/filter-data-within-a-polygon/3784/2 "2023-03-27T19:18:35Z")

</div>

Hello @tonino13,

probably `pygmt.select` (please find the documentation at [pygmt.select — PyGMT](https://www.pygmt.org/latest/api/generated/pygmt.select.html)) is helpful for you, whereby point 4 (“inside one of the polygons in the polygonfile”) is relevant. So far, the **-F** flag (please see the upstream GMT documentation at [select — GMT 6.6.0 documentation](https://docs.generic-mapping-tools.org/latest/gmtselect.html#f)) has unfortunately no alias in PyGMT. Below you find a code example based on your code and data provided above.

_Code example:_

```python
import numpy as np
import pandas as pd
import pygmt

# Load data
df = pd.read_csv('example_cat.dat', sep=',')
df_resort = df[["Lon", "Lat", "id", "year", "month", "day", "hour", "minute",
                "second", "Dep", "ML", "ErrOr", "ErrLat", "ErrLon", "ErrDep",
                "Gap", "Np", "Ns", "Nphases"]]

# File with polygon coordinates
polygon = 'Sipesipe_poly_2.txt'

# Filter data based on polygon
# https://www.pygmt.org/dev/api/generated/pygmt.select.html
# https://docs.generic-mapping-tools.org/dev/gmtselect.html
# https://docs.generic-mapping-tools.org/dev/gmtselect.html#f
df_within_polygon = pygmt.select(
    # [currently] the dataframe must contain longitude and
    # latitude in the first and second column respectively
    data=df_resort,
    # currently there is no alias available in PyGMT for F
    F=polygon,
)

# Create figure object
fig = pygmt.Figure()

# Create basic map
fig.basemap(
    region=[
        np.min(df['Lon'])-0.1,
        np.max(df['Lon'])+0.1,
        np.min(df['Lat'])-0.1,
        np.max(df['Lat'])+0.1,
    ],
    projection="M10c",
    frame="afg",
)

# Plot polygon
fig.plot(
    data=polygon,
    pen="1p,red",
)

# Plot ALL data points
fig.plot(
    x=df['Lon'],
    y=df['Lat'],
    style="c0.15c",
    fill="lightblue",
    pen="1p,black",
)
# Plot data points WITHIN polygon
fig.plot(
    x=df_within_polygon['Lon'],
    y=df_within_polygon['Lat'],
    style="c0.15c",
    fill="orange",
    pen="1p,black",
)

fig.show()
# fig.savefig(fname="filter_by_polygon.png")

```

_Output figure:_

 ![filter_by_polygon](https://canada1.discourse-cdn.com/flex047/uploads/gmt/original/2X/2/23cd5c3f977b4f7b38661f07fee57bd421ba916b.png)

---

<div class="post-metadata">

**Author:** ![tonino13](https://yyz1.discourse-cdn.com/flex047/user_avatar/forum.generic-mapping-tools.org/tonino13/32/1440_2.png) [@tonino13](https://forum.generic-mapping-tools.org/u/tonino13)\
**Post date:** [March 28, 2023, 3:02am UTC](https://forum.generic-mapping-tools.org/t/filter-data-within-a-polygon/3784/3 "2023-03-28T03:02:04Z")

</div>

@yvonnefroehlich, thank you for the references and code.

---

<div class="post-metadata">

**Author:** ![simonst7](https://yyz1.discourse-cdn.com/flex047/user_avatar/forum.generic-mapping-tools.org/simonst7/32/1321_2.png) [@simonst7](https://forum.generic-mapping-tools.org/u/simonst7)\
**Post date:** [October 9, 2025, 1:41pm UTC](https://forum.generic-mapping-tools.org/t/filter-data-within-a-polygon/3784/4 "2025-10-09T13:41:56Z")

</div>

Hello,

I’ve just come across this thread and was wondering if there is a way to perform a similar selection with raster files. Specifically, I would like to use a polygon defined within the raster extent to crop the raster, keeping only the pixels either inside or outside the polygon.

Thank you!!

---

<div class="post-metadata">

**Author:** ![weiji14](https://yyz1.discourse-cdn.com/flex047/user_avatar/forum.generic-mapping-tools.org/weiji14/32/33_2.png) [@weiji14](https://forum.generic-mapping-tools.org/u/weiji14)\
**Post date:** [October 9, 2025, 9:48pm UTC](https://forum.generic-mapping-tools.org/t/filter-data-within-a-polygon/3784/5 "2025-10-09T21:48:31Z")

</div>

> [@simonst7](#):
>
> Specifically, I would like to use a polygon defined within the raster extent to crop the raster, keeping only the pixels either inside or outside the polygon.

What you’ll want is [`gmt grdcut -F`](https://docs.generic-mapping-tools.org/6.5/grdcut#f), which is currently being implemented in PyGMT at [Support polygon-based subsetting in grdcut -F with GeoDataFrame by kshitijaucharmal · Pull Request #4135 · GenericMappingTools/pygmt · GitHub](https://github.com/GenericMappingTools/pygmt/pull/4135).
