Tushar Poddar
Tushar Poddar

Reputation: 23

How do I convert the Xarray plot xr.ufuncs.log(data_slice).plot(cmap='magma', vmin=0, vmax = max_value*.7) into the matplotlib plot?

So basically I have a Xarray and a NumPy array representing the same data of a spectrogram. The following code is used to plot the Xarrray with very good clarity(it cuts the spectrogram above the max value)

plt.figure(figsize=(3,5))
data_slice = data['__xarray_dataarray_variable__'].sel(slices=41625.0)
max_value = np.log(data.sel(slices=slice(67.5, 5.999625e+05)).max(xr.ALL_DIMS)['__xarray_dataarray_variable__'].values)
xr.ufuncs.log(data_slice).plot(cmap='magma', vmin=0, vmax = max_value*.7)

Here we have the Xarray -> data and we select a particular piece of it and then plot it using xf.plot. Similarly, I have a Numpy array that is in the shape of (256, 12333) where 12333 represents the number of time stamps and 256 represents the frequency bins. How do I tell my plot to shoe data until just the max value in the thing that I need to plot? I want to do this so that I get a magnified image of the spectrogram so that I can see the sounds clearly. As of now, I have been plotting my numpy array as this -

plt.imshow(data[:, 30:100])

Upvotes: 0

Views: 364

Answers (1)

paime
paime

Reputation: 3552

Why not merely converting it to a DataArray?

Then you'll take advantage of xarray's plotting utilities.

In particular, you'll be able to use the robust=True kwarg that will automatically remove potential outliers from the dynamic color range.

There is also automatic labeling, using "long_name" attribute.

freq_count, time_count = 256, 12333

data = np.random.randn(freq_count, time_count)

da = xr.DataArray(
    dims=("frequency", "time"),
    data=data,
    coords=dict( 
        frequency=np.arange(freq_count), 
        time=np.arange(time_count), 
    ), 
    attrs=dict(long_name="Spectral intensity over time") 
)

Plotting:

fig, axes = plt.subplots(ncols=2)
da.plot.imshow(robust=False, ax=axes[0])
da.plot.imshow(robust=True, ax=axes[1])
plt.show()

A comparison between the robust=False plot and the robust=True plot:

A comparison between the robust=False plot and the robust=True plot

Upvotes: 1

Related Questions