Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python program using netCDF help!

  1. Mar 11, 2012 #1
    Hello, I need to write a program that will plot any set of .nc data with dimensions stored in t-z-y-x order but i'm having some problems thats driving me crazy.

    first problem: how do I find the names of the variables for each dimension for example how would I find the name 'lat' for the latitude (I know in the .nc file but i'm not allowed to hard code it)

    second problem: The graphs that I plot have white bits on the outside because the x and y axis are bigger than the data set, is there a way to eliminate this part?

    my program is below notice that I have to hardcode the words 'lon' and 'lat when I need to get them from the file instead somehow!)

    # Assignment2 module1
    # FILENAME: A2P1

    def plotMap(locStr, varStr, tI, zI):
    '''reads a file location (string), variable (string), a time index and then a z index'''
    print "importing..."
    import numpy as np
    import matplotlib
    import netCDF4
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    from netCDF4 import Dataset
    import string

    print "reading data..."
    nc = Dataset(locStr)
    var = nc.variables[varStr]

    print "Converting the coordinates..."
    lonvar = nc.variables['lon']
    lonvals = lonvar[:]
    latvar = nc.variables['lat']
    latvals = latvar[:]

    print "Creating plot attributes..."
    pc=plt.pcolor(lonvals, latvals, data)
    plt.colorbar(pc, orientation='horizontal')
    plt.xlabel('longitude (' + lonvar.units +')')
    plt.ylabel('latitude (' + latvar.units + ')')
    plt.title('plot of ' + varStr + ' at level z=' + str(zI) + ' (' + var.units + ')')

    print "Plotting graph..."
    plt.savefig(varStr + '.png')

    import A2P1
    A2P1.plotMap('/home/edev/classes/class7/FOAM_20110209.0.nc', 'TMP', 1, 12)
    #A2P1.plotMap('/home/edev/classes/class6/GlobModel_temp.nc', 'Pressure', 1, 1)

    here are links to two .nc file this program should work for but doesn't quite yet


    I have used a lot of time looking for the command that will fix everything, your help will be very appretiated. If can't help and have a good idea of where to look that would be usedful too,

    thank you

  2. jcsd
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted