Home > Back-end >  Labeling xarray plot with month names
Labeling xarray plot with month names

Time:11-18

I have an xarray dataset with three dimensions include lat, lon and time. Time dimension is monthly value for 12 values from 1 to 12. I want to plot a variable of this dataset with name of months (e.g. 'Jan', 'Feb', 'Mar',...). How can I change number of months to name of months in plotting?

<xarray.Dataset>
Dimensions:              (month: 12, latitude: 501, longitude: 721)
Coordinates:
  * longitude            (longitude) float64 49.8 49.81 49.82 ... 56.99 57.0
  * latitude             (latitude) float64 27.0 27.01 27.02 ... 31.99 32.0
  * month                (month) int64 1 2 3 4 5 6 7 8 9 10 11 12
Data variables:
    Sum_monthly_Rain_mm  (month, latitude, longitude) float32 dask.array<chunksize=(1, 501, 721), meta=np.ndarray>
    Tair_C               (month, latitude, longitude) float32 dask.array<chunksize=(1, 501, 721), meta=np.ndarray>

Plots:

temp_rain_mean_months.Tair_C.plot(x='longitude', y='latitude', col='month', col_wrap=4,
                                      levels=[-10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]);

enter image description here

CodePudding user response:

two ways...

You can iterate through the axes on the plot object returned by da.plot and set the title manually:

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

p = da.groupby('time.month').mean(dim='time').plot(col='month', col_wrap=4)
for i, ax in enumerate(p.axes.flat):
    current_title = ax.get_title()
    assert current_title[:len('month = ')] == 'month = '
    month_ind = int(current_title[len('month = '):]) - 1
    ax.set_title(months[month_ind])

Or, you could modify the dim on the array prior to plotting:

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
da['month_name'] = ('month', months)
da.swap_dims({'month': 'month_name'}).Tair_C.plot(
    x='longitude',
    y='latitude',
    col='month_name',
    col_wrap=4,
    levels=[-10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40],
)
  • Related