comparison zonal_statistics.py @ 0:4f14b5b97262 draft

planemo upload for repository https://github.com/NordicESMhub/galaxy-tools/tree/master/tools/mean-per-zone commit 24f20e7459e275c14376680f9bb91cd8ac26d9a5
author climate
date Thu, 25 Apr 2019 14:32:23 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f14b5b97262
1 #!/usr/bin/env python3
2
3 import argparse
4 import warnings
5
6 import geopandas
7
8 import matplotlib as mpl
9 mpl.use('Agg')
10 from matplotlib import pyplot # noqa: I202,E402
11
12 import pandas as pd # noqa: I202,E402
13
14 from rasterstats import zonal_stats # noqa: I202,E402
15
16 import xarray as xr # noqa: I202,E402
17
18
19 if __name__ == '__main__':
20 warnings.filterwarnings("ignore")
21 parser = argparse.ArgumentParser()
22 parser.add_argument(
23 'raster',
24 help='input raster file with geographical coordinates (netCDF format)'
25 )
26
27 parser.add_argument(
28 'shapefile', help='input shapefile name with polygons '
29 )
30
31 parser.add_argument(
32 'variable', help='name of the variable in raster file'
33 )
34 parser.add_argument(
35 'output', help='output filename to store resulting image (png format)'
36 )
37 parser.add_argument(
38 '-s', '--stat', help='type of statistics [min, max, mean, count]'
39 )
40 parser.add_argument(
41 '-t', '--title', help='title for the generated plot'
42 )
43 parser.add_argument("-v", "--verbose", help="switch on verbose mode",
44 action="store_true")
45
46 args = parser.parse_args()
47 if args.stat is None:
48 stat_type = 'mean'
49 else:
50 stat_type = args.stat
51
52 dset = xr.open_dataset(args.raster)
53 dset[args.variable].to_netcdf(".tmp.nc")
54 zs = zonal_stats(args.shapefile, ".tmp.nc", stats=stat_type)
55 df_zonal_stats = pd.DataFrame(zs)
56 world = geopandas.read_file(args.shapefile)
57 df = pd.concat([world, df_zonal_stats], axis=1)
58 ddf = df.dropna()
59 f, ax = pyplot.subplots(1, figsize=(20, 10))
60
61 visu = ddf.plot(column=stat_type, scheme='Quantiles', k=15, cmap='jet',
62 legend=True, ax=ax,
63 legend_kwds={'loc': 'lower left',
64 'frameon': True,
65 'title': args.variable,
66 'bbox_to_anchor': (1, 0.05)
67 }
68 ) # plot done
69 ax.set_xlabel("Longitude")
70 ax.set_ylabel("Latitude")
71
72 if args.title is None:
73 f.suptitle(stat_type + " computed over areas")
74 else:
75 f.suptitle(args.title)
76 if args.verbose:
77 print("plot generated")
78
79 pyplot.savefig(args.output, format='png')