-2

I am having a NetCDF data with one dimension that varies with time for 1000 years (1 year interval from 850 to 1849). I am plotting a time series and I want to show only years in the X-axis (850 to 1849). I have used the following script but it doesn't work.

import netCDF4 as netcdf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

nc = netcdf.Dataset('tas_850-1849.nc')
time = nc.variables['time']
lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
var = nc.variables['pdo'][:]

start = datetime.date(850,01,01)
dates = [start + datetime.timedelta(n) for n in range(len(var))]

plt.plot(dates, var[:,0,0], color='red', linewidth=2, label='Data1')

plt.show()

I get the following image which is not the way I want.

enter image description here

Time series line plot with time in X-axis.

Gabriel
  • 40,504
  • 73
  • 230
  • 404
S.Br
  • 1
  • 4
  • One thing that's wrong in your code: `dates` is increasing at daily timesteps. You could use something like `dates = [datetime.date(850+n,1,1) for n in range(len(var))]`. – Robert Davy Mar 25 '18 at 22:54
  • Now it is working with the script you have suggested. However, how to deal with the tick marks here. The tick marks shows from 801 to 1801 with 200 intervals and values correctly positioning from 850 to 1850. The plot is correct but I need to have X-axis ticks from 850 to 1850 instead of 801-1801. – S.Br Mar 26 '18 at 16:20

1 Answers1

-1

As @Robert Davy mentioned in his comment, the dates were not well generated. Once that problem was fixed it works for me using your snippet.

enter image description here

If you need more information about tick locating and formatting take a look to this.

EDITED

According with this, I'd try:

import matplotlib.dates as mdates

plt.plot(dates, var[:,0,0], color='red', linewidth=2, label='Data1')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
Gonzalo Donoso
  • 657
  • 1
  • 6
  • 17
  • Unfortunately it didn't work. Following the above script, it draws the same plot without any X-axis value. – S.Br Mar 24 '18 at 21:46
  • I do not have access to that data, but this solution works for me using an artificial time series. – Gonzalo Donoso Mar 25 '18 at 23:45
  • Please find here the data. [https://www.dropbox.com/s/45zc8sk7vhv6um4/tas_850-1849.nc?dl=0] – S.Br Mar 26 '18 at 13:15