Skip to content

GitLab

  • Menu
Projects Groups Snippets
    • Loading...
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • Python_ToolBox Python_ToolBox
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Issues 0
    • Issues 0
    • List
    • Boards
    • Service Desk
    • Milestones
  • Monitor
    • Monitor
    • Metrics
    • Incidents
  • Packages & Registries
    • Packages & Registries
    • Package Registry
    • Container Registry
    • Infrastructure Registry
  • Analytics
    • Analytics
    • Value stream
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Create a new issue
  • Issue Boards
Collapse sidebar
  • Marie Brunel
  • Python_ToolBoxPython_ToolBox
  • Wiki
  • Plot graph and map

Last edited by Marie Brunel Feb 10, 2022
Page history

Plot graph and map

Set up figure

fig = plt.figure(figsize=(30,30))
subplots = set_subplots(3,4,0.1,0.2,0.03,0.02)

Plot line

axe = fig.add_axes(subplot)
axe.plot (data,color ="#000000",linewidth=2)
axe.set_xlabel("years",size=fs_axistitle)
axe.set_ylabel(file_name,size=fs_axistitle)
axe.set_xticks(np.arange(0,nb_year,20))
axe.set_xticklabels(np.arange(years[0],years[-1],20))
axe.set_yticks(np.arange(0,ymax,1))
axe.tick_params(labelsize=fs_label,length=4, direction ="inout")
axe.set_title(year,fontsize=fs_title,weight="bold")

Morocco Map

All Morocco

axe = fig.add_axes(subplot,projection=ccrs.PlateCarree())
im = axe.imshow(data,extent=[-17.5,-1,21,36],cmap=yelgre,vmin=v_min,vmax=v_max)
axe.text(-17,35,file_name+" _ "+str(year),fontsize = fs_textongraph,weight="bold",rotation="horizontal")
axe.set_xticks(np.arange(-15,-1,4))
axe.set_yticks(np.arange(23,36,4))  
axe.tick_params(labelsize=fs_label,length=4, direction ="inout")

North Morocco

axe = fig.add_axes(subplot,projection=ccrs.PlateCarree())
im = axe.imshow(data,extent=[-17.5,-1,21,36],cmap=yelgre,vmin=v_min,vmax=v_max)
axe.text(-11,37,file_name+" _ "+str(year),fontsize = fs_textongraph,weight="bold",rotation="horizontal")
axe.axis([-12,-1,29,38])
axe.set_xticks(np.arange(-12,-1,2))
axe.set_yticks(np.arange(29,38,2))  
axe.tick_params(labelsize=fs_label,length=4, direction ="inout")

North Morocco resolution 5 minutes

im = axe.imshow(data[id_months],extent=[-10.71,-1.0471998,28.619999,35.8671],cmap=whiblu)#,vmin=v_min,vmax=v_max)
axe.text(-10.5,36.5,"months {}".format(i),fontsize = fs_textongraph,weight="bold",rotation="horizontal")
axe.set(xlim= (-11,-1), ylim=(27, 37))
axe.set_xticks(np.arange(-10,-1,2))
axe.set_yticks(np.arange(28,37,2))  
axe.tick_params(labelsize=fs_label,length=4, direction ="inout")

Morocco shapefile

def plot_region (axe):
    region_sf = shp.Reader("/home/marie/nextCloud/Documents/lpjml5_maroc/python_toolbox/Shapefiles_Maroc_Regions_Provinces/REGION.shp")
    for shaperecord in region_sf.shapeRecords():
        shape = shaperecord.shape
        points = np.array(shape.points)
        intervals = list(shape.parts) + [len(shape.points)]
        for (k, l) in zip(intervals[:-1], intervals[1:]):
            axe.plot(*zip(*points[k:l]),color ="#000000",linewidth=1)
    return ()

def plot_morocco (axe):
    morocco_sf = shp.Reader("/home/marie/nextCloud/Documents/lpjml5_maroc/python_toolbox/Shapefiles_Maroc_Regions_Provinces/maroc_adm0.shp")
    for shaperecord in morocco_sf.shapeRecords():
        shape = shaperecord.shape
        points = np.array(shape.points)
        intervals = list(shape.parts) + [len(shape.points)]
        for (k, l) in zip(intervals[:-1], intervals[1:]):
            axe.plot(*zip(*points[k:l]),color ="#000000",linewidth=1)
    return ()

def plot_province (axe):
    province_sf = shp.Reader("/home/marie/nextCloud/Documents/lpjml5_maroc/python_toolbox/Shapefiles_Maroc_Regions_Provinces/PROVINCE.shp")
    for shape in province_sf.shapes():
        points = np.array(shape.points)
        intervals = list(shape.parts) + [len(shape.points)]
        for (k, l) in zip(intervals[:-1], intervals[1:]):
            axe.plot(*zip(*points[k:l]),color ="#000000",linewidth=1)
    return ()

plot_morocco(axe)
plot_region(axe)
plot_province(axe)

Brazil Map

fig = plt.figure(figsize=(30,30))
axe = fig.add_axes([0,0,0.2,0.2],projection=ccrs.PlateCarree())
im = axe.imshow(biomes,extent=[-74,-35,-32.5,5.5])
states_provinces = cfeature.NaturalEarthFeature(
    category='cultural',
    name='admin_1_states_provinces_lines',
    scale='50m',
    facecolor='none')
axe.add_feature(states_provinces, edgecolor='black')
axe.coastlines('50m', linewidth=0.4,edgecolor='black')
axe.add_feature(cfeature.BORDERS,linewidth=0.4,edgecolor='black')
axe.add_feature(cfeature.RIVERS,linewidth=0.6,edgecolor="white")
axe.set_xticks(np.append(np.append(-77,np.arange(-75,-30,5)),-32))
axe.set_yticks(np.append(np.append(-34,np.arange(-30,10,5)),7))
axe.set_xticklabels(np.append("",np.arange(-75,-30,5)))
axe.set_yticklabels(np.append("",np.arange(-30,10,5)))
axe.tick_params(labelsize=fs_label,length=4, direction ="inout")

Colormap scaling

scale_map = []
suggest_scalemap = []
#scaling
    if scale_map == []:
        v_min = np.amin(data)
        v_max = np.amax(data)
        suggest_scalemap.append([file_name,v_min,v_max])
    else :
        v_min = scale_map[i][1]
        v_max = scale_map[i][2]
#add at the end
print("Suggested scaling : ",suggest_scalemap)

Legend

# lines
legends = [
    mtplines.Line2D([0], [0], color="#2c7fb8", linewidth=2, linestyle="solid", label='Pasture Mapbiomas'),
    mtplines.Line2D([0], [0], color="#2ca25f", linewidth=2, linestyle="solid", label='Grassland Mapbiomas'),
    mtplines.Line2D([0], [0], color="#000000", linewidth=2, linestyle="solid", label='Pasture+Grassland Map'),
    mtplines.Line2D([0], [0], color="#000000", linewidth=2, linestyle="dashed",label='Pasture LPJmL')
    ]
# rectangle 
mpatches.Patch(facecolor='#8dd3c7', label="1. Al Hoceima"),

axe = fig.add_axes(subplots[-1],frame_on=False, yticks=[],xticks=[])
axe.legend(handles = legends,fontsize=fs_legend,loc = 'lower left',ncol=1)

Colorbar

  • vertical on the right :
last_subplot = the subplot next to color bar
cbar_ax = fig.add_axes([last_subplot[0]+last_subplot[2]+0.02,last_subplot[1]+0.009,0.025,last_subplot[3]-0.02])
cbar=fig.colorbar(im, cax = cbar_ax,orientation="vertical")
cbar.ax.tick_params(labelsize=fs_legend,labelleft=False,labelright=True)
cbar.set_label(label=file_name,size=fs_legend,weight='bold')
  • horizontal below :
last_subplot = subplots[0]
cbar_ax = fig.add_axes([last_subplot[0],last_subplot[1]-0.03,last_subplot[2],0.02])
cbar=fig.colorbar(im, cax = cbar_ax,orientation="horizontal")
cbar.ax.tick_params(labelsize=fs_legend,labelleft=False,labelright=True)
cbar.set_label(label="difference (percentage)",size=fs_legend,weight='bold')

Interactive plot

import matplotlib
matplotlib.use('TkAgg')
#pts = ginput(10)
#print(pts)

Plot marker on map

axe.plot(pt[1],pt[0],"+",markersize=10,markeredgecolor="#000000")
axe.text(pt[1]+0.1,pt[0]+0.1,i,fontsize = fs_textongraph,weight="bold")

save a figure

fig.savefig("pasture_fraction_landuse_input_mapbiomas_1985_2020.pdf", bbox_inches='tight',orientation = 'landscape' ) 

# multiple pages :
pp = PdfPages('average_difference_maps.pdf')
pp.savefig(bbox_inches='tight',orientation = 'landscape')
pp.close()

text on graph

axe.text(i,j,fraction,fontsize = fs_textongraph,weight="bold",rotation="horizontal",transform=fig.transFigure,va="bottom",ha="center")

plot region number in morocco

#plot region number
points = [(-5.644308943089431, 35.463414634146346), (-2.3414634146341466, 33.53252032520326), (-4.932926829268293, 34.04065040650407), 
          (-6.254065040650406, 34.09146341463415), (-6.508130081300813, 32.71951219512195), (-7.676829268292682, 33.12601626016261), 
          (-8.540650406504064, 31.804878048780488), (-5.59349593495935, 30.991869918699187), (-8.286585365853657, 29.8739837398374), 
          (-9.96341463414634, 28.34959349593496), (-10.573170731707316, 27.38414634146342)]
for id_point,point in enumerate(points) :
    id_region = id_point +1
    axe.text(point[0],point[1],id_region,fontsize = fs_textongraph,weight="bold")
Clone repository
  • Binary file
  • Brazil
  • C balance abnormally high in LPJmL 5 running @LAM
  • Cluster
  • Color and ColorMap
  • Data treatment
  • Link shelf
  • Morocco
  • NetCDF format and file
  • Numpy array
  • Plot graph and map
  • Python script
  • Run CNRM and HADgem LPJmL5 (30 minutes)
  • Home