Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xarray plot.line with non-dimensional coordinate

I wish to plot a series of line plots using non-dimensional coordinates instead of dimensional coordinates.

It is possible in pcolormesh:

import xarray as xr
import numpy as np
import matplotlib.pyplot as plt

# Setup data array, from http://xarray.pydata.org/en/stable/plotting.html#multidimensional-coordinates
lon, lat = np.meshgrid(np.linspace(-20, 20, 5), 
                       np.linspace(0, 30, 4))
lon += lat/10
lat += lon/10
da = xr.DataArray(np.arange(20).reshape(4, 5), dims=['y','x'],
                     coords = {'lat': (('y', 'x'), lat),
                               'lon': (('y', 'x'), lon)})

# plot in terms of y,x, the dimensional coordinate
fig,ax = plt.subplots()
da.plot.pcolormesh('y','x') 

# plot in terms of lon, lat, the non-dimensional coordinate
fig, ax = plt.subplots()
da.plot.pcolormesh('lon', 'lat')

# plot lines in terms of x,y, the dimensional coordinate
fig, ax = plt.subplots()
da.plot.line(x='x')

# plot lines in terms of lon, lat?
da.plot.line(x='lon') #gives error

plot in terms of y,x, the dimensional coordinate

plot in terms of lon, lat, the non-dimensional coordinate

plot lines in terms of x,y, the dimensional coordinate

Basically, I want to plot line cuts through the 2D data.

I can do it with basic matplotlib (below), but I want a 1 liner in xarray.

 fig,ax = plt.subplots()
 for i in range(int(da.y.shape[0])):
     ax.plot(da.lon[i], da[i])

What I want

like image 752
user1944244 Avatar asked Sep 18 '26 10:09

user1944244


1 Answers

I'm not sure why DataArray.plot.line doesn't allow non-dimension coordinates. You should submit this as an issue.

As for a one-liner solution, you could omit the for loop with this:

ax.plot(da.lon.T, da.data.T)
like image 113
GeorgeG Avatar answered Sep 19 '26 23:09

GeorgeG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!