Benutzerspezifische Werkzeuge

##### Sektionen
Sie sind hier: NCL / DKRZ PyNGL example scatter plot with regression line
Info
Alle Inhalte des Nutzerportal sind nur auf Englisch verfügbar.

# DKRZ PyNGL example scatter plot with regression line

This example shows how to create a scatter plot and add the regression line to it.

Example:

`from __future__ import print_functionimport numpy as npimport Ngl,Nio#---------------------------------------------------------------# Function runave(data, xrange): compute the running mean##      Input:    data       data array#                xrange     time range##      Return:    running mean values#---------------------------------------------------------------def runave(data, xrange):    return np.convolve(data, np.ones((xrange,))/xrange, mode='valid')#---------------------------------------------------------------# Function regline(xin,yin):      compute the regression line##      Input:    xin       x array#                yin       data array##      Return:    x,y       x- and y-values of regression line#---------------------------------------------------------------def regline(xin,yin):    x    = np.vstack([xin, np.ones(len(xin))]).T    m, t = np.linalg.lstsq(x, yin, rcond=None)[0]       #-- returns gradient and y-intersection    y    = (m*x)+t                                      #-- regression line equation    return x, y    #---------------------------------------------------------------#                     MAIN#---------------------------------------------------------------#-- file namefname = 'tas_monmean_MPI-ESM-LR_rcp45_r1i1p1_20200101-20291231.nc'#-- open file and read variablesa    =  Nio.open_file(fname,"r")                        #-- open data filetas  =  a.variables["tas"][:,:,:]                       #-- read variable taslat  =  a.variables["lat"][:]                           #-- get whole "lat" variablelon  =  a.variables["lon"][:]                           #-- get whole "lon" variabletime =  a.variables["time"][:]                          #-- number of timestepsntime = time.size#-- set lat/lon pointlatval =  60                                            #-- extract lat 60Nlonval = 180                                            #-- extract lon 180W#-- retrieve the indices of lat/lon pointindlat = min(range(len(lat)), key=lambda i: abs(lat[i]-latval))indlon = min(range(len(lon)), key=lambda i: abs(lon[i]-lonval))#-- select the data of lat/lon point for all timestepsts = tas[:,indlat,indlon]#-----------------------------------------------------------# Smooth data so that seasonal cycle is less prominent. This # is for demo purposes only so that the regression line is # more sloped.#-----------------------------------------------------------rmean = runave(ts,40)#-----------------------------------------------------------# Create x and calculate the regression coefficient.#-----------------------------------------------------------x, y = regline(time,ts)#-----------------------------------------------------------# Graphics#-----------------------------------------------------------wks = Ngl.open_wks("png","plot_scatter_regline")#-- plot resourcesres                 =  Ngl.Resources()res.nglDraw         =  False                    #-- don't draw plotres.nglFrame        =  False                    #-- don't advance the frameres.nglMaximize     =  True                     #-- maximize plot res.tiMainString    = "Output from np.linalg.lstsq (regline)" #-- add titleres.tiXAxisString   = "simulation time" res.tiYAxisString   = "Surface temperature" res.xyMarkLineModes = "Markers"                 #-- use markersres.xyMarker        =  16                       #-- filled circleres.xyMarkerSizeF   =  0.005                    #-- default: 0.01res.xyMarkerColor   = "red"                     #-- marker colorres.trYMinF         =  240res.trYMaxF         =  300#-- create xy-plot of tsplot0 = Ngl.xy(wks,time,ts,res)                 #-- create the xy plot#-- change resource settings for regression lineres.xyMarkLineModes = "Lines"                   #-- use linesres.xyMarker        =  1                        #-- solid lineres.xyMarkerColor   = "black"                   #-- marker color#-- create plot of regression lineplot1 = Ngl.xy(wks,x,y,res)#-- overlay regression line plot on xy plotNgl.overlay(plot0,plot1)#-- draw plot and advance the frameNgl.draw(plot0)Ngl.frame(wks)Ngl.end()`

Result:

Artikelaktionen