def test_pretty_plot(): image = os.path.join(root_path.test_root, '00_testdata', 'plot', 'ESACCI-SOILMOISTURE-L3S-SSMV-COMBINED-20100701000000-fv04.5.nc') ds = Dataset(image) dat = ds.variables['sm'][:] dat = dat.filled(np.nan).flatten() _, resampled_lons, resampled_lats, _ = SMECV_Grid_v052(None).get_grid_points() index =pd.MultiIndex.from_arrays(np.array([resampled_lats, resampled_lons]), names=['lats', 'lons']) df = pd.DataFrame(index=index, data={'sm': dat}).dropna() f, imax, im = cp_map(df, 'sm', resxy=(0.25,0.25), cbrange=(0,50.), veg_mask=True, cmap=cm_sm, projection=ccrs.Sinusoidal(), title='Overloaded Plot with too much Information', ocean=True, land='grey', gridspace=(60,20), states=True, borders=True, llc=(-179.9999, -90.), urc=(179.9999, 90), cb_label='ESA CCI SM [$m^3/m^3$]', cb_labelsize=7, scale_factor=100, grid_label_loc='0111', coastline_size='110m', cb_extend='both', cb_ext_label_min='DRY', cb_ext_label_max='WET', cb_loc='right') out_dir = tempfile.mkdtemp() try: filename = 'pretty_plot.png' f.savefig(os.path.join(out_dir, 'pretty_plot.png'), dpi=200) assert os.path.isfile(os.path.join(out_dir, filename)) finally: shutil.rmtree(out_dir)
def test_area_gpi(): with TemporaryDirectory() as out_dir: gpis = np.arange(346859, 374200) df = pd.DataFrame(index=gpis) df['data'] = np.random.rand(df.index.size) f, imax, im = cp_map(df, 'data', resxy=(0.25,0.25)) filename = 'plot_area_gpi.png' f.savefig(os.path.join(out_dir, filename)) assert os.path.isfile(os.path.join(out_dir, filename))
def plot_variable(self, variable, time=None, interface=True, transparent=False, plotfile_name=None, file_format='png', **plot_kwargs): """Plot a single variable from a certain time""" self.read(time) df = self.df.copy() if not interface: plot_kwargs['show_cbar'] = False plot_kwargs['title'] = None if self.irregular: lons = df[self.index_name[1]].values if self.index_name[1] in df.columns \ else df.index.get_level_values(self.index_name[1]) lats = df[self.index_name[0]].values if self.index_name[0] in df.columns \ else df.index.get_level_values(self.index_name[0]) f, imax, im = cp_scatter_map(lons, lats, df[variable].values, **plot_kwargs) else: f, imax, im = cp_map(df, variable, resxy=self.resxy, **plot_kwargs) if not plotfile_name: if self.time not in [None, datetime(1900, 1, 1)]: plotfile_name = '{var}_at_{time}_from_{file}'.format( var=variable, time=str(self.time.date()) if not isinstance(self.time, str) else self.time, file=self.filename) else: plotfile_name = '{var}_from_{file}'.format(var=variable, file=self.filename) if not interface: plt.tight_layout(pad=3) if not os.path.exists(self.out_dir): os.makedirs(self.out_dir) plt.savefig(os.path.join(self.out_dir, plotfile_name + '.{}'.format(file_format)), dpi=self.dpi, transparent=transparent, bbox_inches='tight') plt.close('all')
def test_area_multiindex(): with TemporaryDirectory() as out_dir: lons = np.linspace(-20, 20, 41) lats = np.linspace(20, -20, 41).transpose() lons, lats = np.meshgrid(lons, lats) # multiindex: lats, lons index =pd.MultiIndex.from_arrays(np.array([lats.flatten(), lons.flatten()]), names=['lats', 'lons']) df = pd.DataFrame(index=index) df['data'] = np.random.rand(df.index.size) f, imax, im = cp_map(df, 'data', resxy=(1,1), offset=(0,0)) filename = 'plot_area_multiindex.png' f.savefig(os.path.join(out_dir, filename)) print('Stored plot in {}') assert os.path.isfile(os.path.join(out_dir, filename))
def plot_comb_variable(self, vards1, vards2, time1=None, time2=None, metric='-', interface=True, transparent=False, plotfile_name=None, file_format='png', **plot_kwargs): """ Plot a single variable from a certain time Parameters --------- vards1 : str Name of the variable to use in the first file vards2 : str Name of the variable to use in the second file time1 : datetime or str, optional (default: None) Date of the variable in the first file to use. If there are no dates, pass None. time2 : datetime or str, optional (default: None) Date of the variable in the second file to use. If there are no dates, pass None metric : str, optional (default: -) Metric to combine the 2 variables Difference, AbsDiff, Ratio, Product, Sum, or Mask1 interface: bool, optional (default: True) Plot elements such as colorbar and title transparent: bool, optional (default: True) Make the background of the plot transparent. plotfile_name : str, optional (default: None) File name to store the plot, if this is None, we create a file name. file_format : str, optional (default: 'png') Format in which the plot is stored (e.g. pdf or svg for vector format) Returns --------- ds : pd.Series The created comb data frame, e.g. for calculating stats according to the plotted data. f : plt.figure The Figure that is created. imax : plt.Axes The axes of the map plot. """ plt.close('all') self.times = self._load_times(time1, time2, vards1, vards2) # calc variable1 *metric* variable2 s1 = self.ds1.df[vards1] s2 = self.ds2.df[vards2] # make sure the two have the same index names if self.ds1.index_name != self.ds2.index_name: s2.rename_axis( index=dict(zip(self.ds2.index_name, self.ds1.index_name))) cds, smetric = self._usemetric(s1, s2, metric) name = '{}_between_{}_and_{}'.format(smetric, vards1, vards2) df = cds.to_frame(name) if not interface: plot_kwargs['show_cbar'] = False if not self.ds1.irregular and not self.ds2.irregular: f, imax, im = cp_map(df, name, resxy=self.resxy, **plot_kwargs) else: f, imax, im = cp_scatter_map( lats=df.index.get_level_values(self.ds1.index_name[0]), lons=df.index.get_level_values(self.ds1.index_name[1]), values=df[name].values, **plot_kwargs) if not plotfile_name: plotfile_name = name if self.times in [[None, None], [datetime(1900, 1, 1), datetime(1900, 1, 1)]]: pass else: plotfile_name += 'at_{t1}_and_{t2}'.format( t1=str(self.times[0]), t2=str(self.times[1])) if not os.path.exists(self.out_dir): os.makedirs(self.out_dir) plt.savefig(os.path.join(self.out_dir, plotfile_name + '.{}'.format(file_format)), dpi=self.dpi, transparent=transparent, bbox_inches='tight') return df[name], f, imax