1. 程式人生 > 其它 >[視覺化學習筆記]——01——簡單圖

[視覺化學習筆記]——01——簡單圖

一、讀nc檔案畫出降水概率的分佈

  給了一個降水的nc檔案,讀取lon lat pre,建立畫布,選擇投影,設定colorbar,plot.savefig(),plt.show()出圖!

 1 import xarray as xr
 2 import matplotlib.pyplot as plt
 3 import cartopy.crs as ccrs
 4 
 5 
 6 
 7 ds=xr.open_dataset("/home/kwang/PY/keshihua/plot_exp1/relativeuncertainty.nc")
 8 
 9 lats = ds.variables['
lat'][:] 10 lons = ds.variables['lon'][:] 11 precipitation=ds.variables['precipitation'][0, :, :] 12 fig = plt.figure() #空白畫板 13 ax = plt.axes(projection=ccrs.Robinson()) #設定軸域,在fig中來一個軸,Robinson是偽圓柱投影, 14 plt.contourf(lons, lats, precipitation) 15 plt.colorbar(shrink = 0.8,orientation='horizontal
',label='Precipitation Uncertainty (%)') 16 plt.savefig('/home/kwang/PY/keshihua/plot_exp1/PrecipitationUncertainty2.png', format='png',dpi=400) 17 plt.show()

  

 

  ???不理解為什麼改了投影型別,圖還是沒有變...

  投影型別看的是園裡一個老哥的(d=====( ̄▽ ̄*)b):(一)Cartopy中的地圖投影 - 氣象學人 - 部落格園 (cnblogs.com)

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

二、讀EXCEL檔案做scatter的圖

  先定義了一個函式def plot_validation_metric ,然後在函式定義裡面寫語句,最後直接在函式外面用這個語句就ok。

  (目前裡面還是有些語句沒搞懂,例如那個迴圈,等老師講了後更新)

 1 import numpy as np
 2 #from pylab import rcParams
 3 import matplotlib.pyplot as plt
 4 from matplotlib import colors
 5 import pandas as pd
 6 import cartopy.crs as ccrs
 7 import cartopy
 8 
 9 #from mpl_toolkits.basemap import Basemap
10 
11 def plot_validation_metric(dir_fig, data):
12     fig = plt.figure(figsize=(10, 5))
13     plt.interactive(False)
14     ax = fig.add_subplot(1, 1, 1, projection=ccrs.Robinson())
15     #ax.set_extent([180, -180, -60, 60])
16     #ax.set_extent([ext_e, ext_w, ext_s, ext_n])
17     IGBPs = ['DBF','EBF','ENF','MF','SH','SAV','GRA','WET','CRO']
18     sybs  = ["v","^","<",">","o","s","*","d","D"]
19     cpools = ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4','#313695','#393695']
20     for IGBP,syb, cpool in zip(IGBPs, sybs,cpools):
21         ind = data[data['IGBP_veg_class'] == IGBP].index
22         data_select = data.loc[ind]
23         lon_select = data_select['lon'].values
24         lat_select = data_select['lat'].values
25         ax.scatter(lon_select, lat_select, marker=syb, linewidth=0,label=IGBP,s=150, alpha=0.7, zorder=2,
26                 transform=ccrs.PlateCarree())
27     ax.legend(fontsize=10, loc=3, bbox_to_anchor=(0.06, 0.20, 0.5, 0.5))
28     ax.add_feature(cartopy.feature.LAKES, edgecolor='None',zorder=1)
29 
30     # make the map global rather than have it zoom in to
31     # the extents of any plotted data
32     ax.set_global()
33     ax.stock_img()
34     ax.coastlines(resolution='110m')
35     #rivers_50m = cartopy.feature.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '50m')
36     #ax.plot(gauge_lon,gauge_lat, 'o',markersize=10,color="red",alpha=0.7,zorder=2,transform=ccrs.PlateCarree())
37 
38     plt.tight_layout()
39 
40     #ax.add_feature(rivers_50m, facecolor='None', edgecolor='b',zorder=4)
41     plt.savefig('/home/kwang/PY/keshihua/plot_exp2/test2.png' ,  format='png',dpi=600)
42     plt.show()
43     
44 if __name__=='__main__':
45     dir_Fig = './'
46     data_dir = './'
47     data = pd.read_excel('/home/kwang/PY/keshihua/plot_exp2/fluxnet_map.xlsx')
48     #ind = data[data['IGBP_veg_class'] == 'GRA'].index
49     #data_select = data.loc[ind]
50     #lon_select = data_select['lon'].values
51     #lat_select = data_select['lat'].values
52     #data_select0 = data.loc[ind]
53     #ind2 = data_select0[data_select0['Bset'] == 5].index
54     #data_select = data.loc[ind2]
55     #KGE_select = data_select['MAX'].values
56     #lon_select = data_select['lon'].values
57     #lat_select = data_select['lat'].values
58 
59     #cpool = ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']
60     #cmap = colors.ListedColormap(cpool)
61     #norm = colors.BoundaryNorm(bnd, cmap.N)
62     plot_validation_metric(dir_Fig, data)

三、讀取地表溫度的nc檔案,做出動圖

  這個在畫的時候需要裝兩個geocat的庫,一個是geocat-viz, geocat-comp。這兩個都是在wsl裡面裝好的,在自己定義的一個環境裡面安裝成功的!!!(只能在linux和macos裡面安裝)!!!,伺服器上不知道為什麼也裝不上,只裝好了viz。。。

  Geocat Comp :: Anaconda.org  這裡可以直接在conda官網上查到指定包的安裝指令。

  先是通過迴圈生成35張圖,每個間隔10°經度,然後最後通過os.system("convert -delay 0 ts??.png -loop 0 ts.gif") 指令,講這35張圖合併為一張GIF。

———————————————————————————————————————————————————————————

 1 import numpy as np
 2 import xarray as xr
 3 import cartopy.crs as ccrs
 4 import matplotlib.pyplot as plt
 5 from geocat.viz import util as gvutil
 6 import os
 7 import matplotlib
 8 from pylab import rcParams
 9 
10 ### Plot settings
11 font = {'family' : 'DejaVu Sans'}
12 #font = {'family' : 'Myriad Pro'}
13 matplotlib.rc('font', **font)
14 
15 params = {'backend': 'ps',
16           'axes.labelsize': 12,
17           'grid.linewidth': 0.2,
18           'font.size': 15,
19           'legend.fontsize': 12,
20           'legend.frameon': False,
21           'xtick.labelsize': 12,
22           'xtick.direction': 'out',
23           'ytick.labelsize': 12,
24           'ytick.direction': 'out',
25           'savefig.bbox': 'tight',
26           'axes.unicode_minus': False,
27           'text.usetex': False}      #提前設定好畫圖的引數,這樣後面就不用邊畫邊設定
28 rcParams.update(params)
29 
30 
31 
32 # Generate figure (set its size (width, height) in inches)
33 fig = plt.figure(figsize=(10, 10))
34 
35 ###############################################################################
36 # Read in data:
37 
38 # Open a netCDF data file using xarray default engine and load the data into xarrays
39 ds = xr.open_dataset("/home/kwang/PY/keshihua/plot_exp3/atmos.nc", decode_times=False)
40 for i in range (0,35):
41     t = ds.TS.isel(time=0)
42 
43 ###############################################################################
44 # Fix the artifact of not-shown-data around 0 and 360-degree longitudes
45     wrap_t = gvutil.xr_add_cyclic_longitudes(t, "lon")
46 
47 ###############################################################################
48 #Plot:
49 
50 
51 # Generate axes using Cartopy and draw coastlines with
52     ax = plt.axes(
53         projection=ccrs.Orthographic(central_longitude=-180+i*10, central_latitude=50))
54     ax.set_extent([0, -180, 0, 90], ccrs.PlateCarree())
55     ax.set_global()
56     ax.coastlines(linewidths=0.5)
57     temp = wrap_t.plot.contourf(
58         ax=ax,
59         transform=ccrs.PlateCarree(),
60         levels=11,
61         cmap='coolwarm',
62         add_colorbar=False)
63 
64     cbar_ticks = np.arange(210, 311, 10)
65     cbar = plt.colorbar(temp, 
66                     orientation='horizontal', 
67                     shrink=0.75, 
68                     pad=0.05, 
69                     extendrect=True,
70                     ticks=cbar_ticks)
71 
72     cbar.ax.tick_params(labelsize=10)
73     gvutil.set_titles_and_labels(ax,
74                              maintitle="Example of Orthogonal Projection",
75                              lefttitle="Surface Temperature",
76                              righttitle="K")
77 
78     plt.savefig("/home/kwang/PY/keshihua/plot_exp3/ts"+str(i).zfill(2)+".png")
79 # Show the plot
80 #plt.show()
81 
82 os.system("convert -delay 0 ts??.png -loop 0 ts.gif")