2017-09-18 4 views
0

x 축을 따라 연도 또는 월이있는 선 그래프를 작성 중입니다. enter image description here파이썬 아이리스 설정 X 축 한계 및 틱

어떻게 나에게 모든 월 이름을 표시하는 눈금을 변경할 수 있습니다 : 이것은 다음과 같습니다 플롯을 생산

import matplotlib.pyplot as plt 
import iris 
import iris.coord_categorisation as iriscc 
import iris.plot as iplt 
import iris.quickplot as qplt 
import iris.analysis.cartography 
import cf_units 

#this file is split into parts as follows: 
    #PART 1: load and format CORDEX models 
    #PART 2: load and format observed data 
    #PART 3: format data 
    #PART 4: plot data 

def main(): 
    #PART 1: CORDEX MODELS 
    #bring in all the models we need and give them a name 
    CCCma = '/exports/csce/datastore/geos/users/s0XXXX/Climate_Modelling/AFR_44_tas/ERAINT/1979-2012/tas_AFR-44_ECMWF-ERAINT_evaluation_r1i1p1_CCCma-CanRCM4_r2_mon_198901-200912.nc' 

    #Load exactly one cube from given file 
    CCCma = iris.load_cube(CCCma) 


    #remove flat latitude and longitude and only use grid latitude and grid longitude to make consistent with the observed data, also make sure all of the longitudes are monotonic 
    lats = iris.coords.DimCoord(CCCma.coord('latitude').points[:,0], \ 
           standard_name='latitude', units='degrees') 
    lons = CCCma.coord('longitude').points[0] 
    for i in range(len(lons)): 
     if lons[i]>100.: 
      lons[i] = lons[i]-360. 
    lons = iris.coords.DimCoord(lons, \ 
           standard_name='longitude', units='degrees') 

    CCCma.remove_coord('latitude') 
    CCCma.remove_coord('longitude') 
    CCCma.remove_coord('grid_latitude') 
    CCCma.remove_coord('grid_longitude') 
    CCCma.add_dim_coord(lats, 1) 
    CCCma.add_dim_coord(lons, 2) 

    #we are only interested in the latitude and longitude relevant to Malawi 

    Malawi = iris.Constraint(longitude=lambda v: 32.5 <= v <= 36., \ 
         latitude=lambda v: -17. <= v <= -9.) 

    CCCma = CCCma.extract(Malawi) 

    #time constraignt to make all series the same 
    iris.FUTURE.cell_datetime_objects = True 
    t_constraint = iris.Constraint(time=lambda cell: 1989 <= cell.point.year <= 2008) 
    CCCma = CCCma.extract(t_constraint) 



    #PART 2: OBSERVED DATA 
    #bring in all the files we need and give them a name 
    CRU= '/exports/csce/datastore/geos/users/s0XXXX/Climate_Modelling/Actual_Data/cru_ts4.00.1901.2015.tmp.dat.nc' 

    #Load exactly one cube from given file 
    CRU = iris.load_cube(CRU, 'near-surface temperature') 

    #define the latitude and longitude 
    lats = iris.coords.DimCoord(CRU.coord('latitude').points, \ 
           standard_name='latitude', units='degrees') 
    lons = CRU.coord('longitude').points 

    #we are only interested in the latitude and longitude relevant to Malawi 
    Malawi = iris.Constraint(longitude=lambda v: 32.5 <= v <= 36., \ 
         latitude=lambda v: -17. <= v <= -9.) 
    CRU = CRU.extract(Malawi) 

    #time constraignt to make all series the same 
    iris.FUTURE.cell_datetime_objects = True 
    t_constraint = iris.Constraint(time=lambda cell: 1989 <= cell.point.year <= 2008) 
    CRU = CRU.extract(t_constraint) 



    #PART 3: FORMAT DATA 
    #data is in Kelvin, but we would like to show it in Celcius 
    CCCma.convert_units('Celsius')              

    #bring time data into allignment 
    new_unit = cf_units.Unit('days since 1900-01-01', calendar = '365_day') 
    CCCma.coord('time').convert_units(new_unit)             

    #add years and months to data 
    iriscc.add_year(CCCma, 'time') 
    iriscc.add_year(CRU, 'time') 
    iriscc.add_month(CCCma, 'time') 
    iriscc.add_month(CRU, 'time') 

    #We are interested in plotting the data by month, so we need to take a mean of all the data by month 
    CCCmaYR = CCCma.aggregated_by('month', iris.analysis.MEAN) 
    CRUYR = CRU.aggregated_by('month', iris.analysis.MEAN) 

    #regridding scheme requires spatial areas, therefore the longitude and latitude coordinates must be bounded. If the longitude and latitude bounds are not defined in the cube we can guess the bounds based on the coordinates 
    CCCmaYR.coord('latitude').guess_bounds() 
    CCCmaYR.coord('longitude').guess_bounds() 
    CRUYR.coord('latitude').guess_bounds() 
    CRUYR.coord('longitude').guess_bounds() 

    #Returns an array of area weights, with the same dimensions as the cube 
    CCCmaYR_grid_areas = iris.analysis.cartography.area_weights(CCCmaYR) 
    CRUYR_grid_areas = iris.analysis.cartography.area_weights(CRUYR) 

    #We want to plot the mean for the whole region so we need a mean of all the lats and lons 
    CCCmaYR_mean = CCCmaYR.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=CCCmaYR_grid_areas) 
    CRUYR_mean = CRUYR.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=CRUYR_grid_areas) 


    #PART 4: PLOT LINE GRAPH                        
    #assign the line colours and set x axis to months 
    qplt.plot(CCCmaYR_mean.coord('month'),CCCmaYR_mean, label='CanRCM4_ERAINT', lw=1.5, color='blue') 
    qplt.plot(CRUYR_mean.coord('month'), CRUYR_mean, label='Observed', lw=2, color='black') 

    #create a legend and set its location to under the graph 
    plt.legend(loc="upper center", bbox_to_anchor=(0.5,-0.05), fancybox=True, shadow=True, ncol=2) 

    #create a title 
    plt.title('Mean Near Surface Temperature for Malawi by month 1989-2008', fontsize=11) 

    #add grid lines 
    plt.grid() 

    #save the image of the graph and include full legend 
    #plt.savefig('ERAINT_Temperature_LineGraph_Annual', bbox_inches='tight') 

    #show the graph in the console 
    iplt.show()            

if __name__ == '__main__': 
    main() 

:

여기에 매달 선 그래프에 대한 단순화 된 코드는? 12 월에 그래프를 끝내고 싶습니다. (공백 없음).

마찬가지로, 연간 선 그래프, 여기에 간단한 코드 :

import matplotlib.pyplot as plt 
import iris 
import iris.coord_categorisation as iriscc 
import iris.plot as iplt 
import iris.quickplot as qplt 
import iris.analysis.cartography 

#this file is split into parts as follows: 
    #PART 1: load and format CORDEX models 
    #PART 2: load and format observed data 
    #PART 3: format data 
    #PART 4: plot data 

def main(): 
    #PART 1: CORDEX MODELS 
    #bring in all the models we need and give them a name 
    CCCma = '/exports/csce/datastore/geos/users/s0XXXX/Climate_Modelling/AFR_44_tas/ERAINT/1979-2012/tas_AFR-44_ECMWF-ERAINT_evaluation_r1i1p1_CCCma-CanRCM4_r2_mon_198901-200912.nc' 

    #Load exactly one cube from given file 
    CCCma = iris.load_cube(CCCma) 

    #remove flat latitude and longitude and only use grid latitude and grid longitude to make consistent with the observed data, also make sure all of the longitudes are monotonic 
    lats = iris.coords.DimCoord(CCCma.coord('latitude').points[:,0], \ 
           standard_name='latitude', units='degrees') 
    lons = CCCma.coord('longitude').points[0] 
    for i in range(len(lons)): 
     if lons[i]>100.: 
      lons[i] = lons[i]-360. 
    lons = iris.coords.DimCoord(lons, \ 
           standard_name='longitude', units='degrees') 

    CCCma.remove_coord('latitude') 
    CCCma.remove_coord('longitude') 
    CCCma.remove_coord('grid_latitude') 
    CCCma.remove_coord('grid_longitude') 
    CCCma.add_dim_coord(lats, 1) 
    CCCma.add_dim_coord(lons, 2) 

    #we are only interested in the latitude and longitude relevant to Malawi  
    Malawi = iris.Constraint(longitude=lambda v: 32.5 <= v <= 36., \ 
         latitude=lambda v: -17. <= v <= -9.) 

    CCCma = CCCma.extract(Malawi) 

    #time constraignt to make all series the same 
    iris.FUTURE.cell_datetime_objects = True 
    t_constraint = iris.Constraint(time=lambda cell: 1989 <= cell.point.year <= 2008) 

    CCCma = CCCma.extract(t_constraint)            


    #PART 2: OBSERVED DATA 

    #bring in all the files we need and give them a name 
    CRU= '/exports/csce/datastore/geos/users/s0XXXX/Climate_Modelling/Actual_Data/cru_ts4.00.1901.2015.tmp.dat.nc' 

    #Load exactly one cube from given file 
    CRU = iris.load_cube(CRU, 'near-surface temperature') 

    #define the latitude and longitude 
    lats = iris.coords.DimCoord(CRU.coord('latitude').points, \ 
           standard_name='latitude', units='degrees') 
    lons = CRU.coord('longitude').points 

    #we are only interested in the latitude and longitude relevant to Malawi 
    Malawi = iris.Constraint(longitude=lambda v: 32.5 <= v <= 36., \ 
         latitude=lambda v: -17. <= v <= -9.) 
    CRU = CRU.extract(Malawi) 

    #time constraignt to make all series the same 
    iris.FUTURE.cell_datetime_objects = True 
    t_constraint = iris.Constraint(time=lambda cell: 1989 <= cell.point.year <= 2008) 
    CRU = CRU.extract(t_constraint) 

    #PART 3: FORMAT DATA  
    #data is in Kelvin, but we would like to show it in Celcius 
    CCCma.convert_units('Celsius') 

    #add years to data 
    iriscc.add_year(CCCma, 'time') 
    iriscc.add_year(CRU, 'time') 

    #We are interested in plotting the data by month, so we need to take a mean of all the data by month 
    CCCma = CCCma.aggregated_by('year', iris.analysis.MEAN) 
    CRU = CRU.aggregated_by('year', iris.analysis.MEAN)  

    #regridding scheme requires spatial areas, therefore the longitude and latitude coordinates must be bounded. If the longitude and latitude bounds are not defined in the cube we can guess the bounds based on the coordinates 
    CCCma.coord('latitude').guess_bounds() 
    CCCma.coord('longitude').guess_bounds() 
    CRU.coord('latitude').guess_bounds() 
    CRU.coord('longitude').guess_bounds() 

    #Returns an array of area weights, with the same dimensions as the cube 
    CCCma_grid_areas = iris.analysis.cartography.area_weights(CCCma) 
    CRU_grid_areas = iris.analysis.cartography.area_weights(CRU) 

    #We want to plot the mean for the whole region so we need a mean of all the lats and lons 
    CCCma_mean = CCCma.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=CCCma_grid_areas) 
    CRU_mean = CRU.collapsed(['latitude', 'longitude'], iris.analysis.MEAN, weights=CRU_grid_areas)            



    #PART 4: PLOT LINE GRAPH 
    #assign the line colours 
    qplt.plot(CCCma_mean.coord('year'), CCCma_mean, label='CanRCM4_ERAINT', lw=1.5, color='blue') 
    qplt.plot(CRU_mean.coord('year'), CRU_mean, label='Observed', lw=2, color='black') 

    #create a legend and set its location to under the graph 
    plt.legend(loc="upper center", bbox_to_anchor=(0.5,-0.05), fancybox=True, shadow=True, ncol=2) 

    #create a title 
    plt.title('Mean Near Surface Temperature for Malawi 1989-2008', fontsize=11) 

    #add grid lines 
    plt.grid() 

    #save the image of the graph and include full legend 
    #plt.savefig('ERAINT_Temperature_LineGraph_Annual', bbox_inches='tight') 

    #show the graph in the console 
    iplt.show() 




if __name__ == '__main__': 
    main() 

는이이 그래프를 생성합니다 enter image description here

을 당신은 내가 1989 년부터 2008 년까지 내 데이터를 제한 볼 수 있듯이 , 축이 1985 년에서 2010 년으로 바뀌면 어떻게해야 더 빡빡할까요?

감사합니다.

+0

2008 년 당신의 "단순화 된 코드는"정말입니다 별로 간단하지 않습니다 - 우리가 실제로 재현 할 수있는 데이터로 최소한의 예를 사용하여 문제를 재현 할 수 있습니까? –

+0

죄송합니다. 여러 모델 및 관측 데이터 세트로 실행 중입니다. 그래서 간단하게 말했을 때, 나는 단지 하나만 남겨 두었다는 것을 의미했습니다. x 축이 표시하는 것을 제한하는 간단한 방법이 없습니까? – ErikaAWT

+0

적어도 모든 데이터로드 및 처리를 수행 할 수 있으며 플롯하려는 날짜와 값이있는 간단한 배열/데이터 프레임을 제공 할 수 있습니까? 현재 사용중인 데이터를 얻을 수 없기 때문에 아무도 현재 도움을 줄 수 없으며 솔직히 문제가 중요하지 않습니다. –

답변

1

월간 그래프의 경우 xticks를 설정하여 변경할 수 있습니다.이 숫자는 숫자 여야하지만 숫자 대신 사용할 레이블을 설정할 수도 있습니다. 작동 할 수

plt.xticks(range(12), calendar.month_abbr[1:13])

같은 뭔가 (데이터의 형식에 따라, 당신은 월 이름보다는 개월 수를 플롯해야 할 수도 있습니다). 위의 작업을하려면 import calendar이 필요합니다.

하여 연간 그래프를 들어 당신은이 xMin 아마 1989입니다

plt.xlim((xmin, xmax))

를 사용하여 x 축 제한을 설정할 수 있어야하고 XMAX는

관련 문제