我正在嘗試讀取 .nc 檔案并在地圖上顯示資料。我希望顏色條刻度不是 10 的冪,而是純數字,所以從 0.1 到 10。此外,如果我可以格式化它,所以它會在 7 個刻度中從 0.1 到 10,所以結果與附加圖片中的相同。
請注意,我沒有添加與資料下載相關的代碼片段,因此該腳本無法運行。如果您在不運行代碼的情況下無法發現錯誤,請告訴我,我會附上它,以便您可以下載 .nc 檔案。

這是我正在使用的代碼。對不起,多余的進口。
import xarray as xr
import cartopy
import matplotlib
from matplotlib.colors import LogNorm
from matplotlib.offsetbox import AnchoredText
from matplotlib.ticker import ScalarFormatter, FormatStrFormatter
import sys
import os
#First we open the dataset and read the varaible of interest
ds = xr.open_dataset(OUTPUT_FILENAME)
chl = ds.CHL.sel(time=min_date)
#Setting the figure size and projection
fig = plt.figure(figsize=(15,15))
ax = plt.axes(projection=ccrs.PlateCarree())
#Adding coastlines and land
ax.coastlines(resolution="10m") #Coastline resolution
ax.set_extent([-9,2,35,37.6]) #Map extent
ax.add_feature(cartopy.feature.LAND) #Adding land
#Formatting colorbar <---------------------------------------------------DOES NOT WORK
ax.ticklabel_format(style='plain',useMathText=None)
#Adding gridlines
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=0.5, color='black', alpha=0.7, linestyle='--')
gl.top_labels = False
gl.right_labels = False
#Adding lat/lon labels in the axes
ax.text(-0.07, 0.55, 'Latitude [deg]', va='bottom', ha='center',
rotation='vertical', rotation_mode='anchor',
transform=ax.transAxes)
ax.text(0.5, -0.2, 'Longitude [deg]', va='bottom', ha='center',
rotation='horizontal', rotation_mode='anchor',
transform=ax.transAxes)
#Adding (C) info to the figure
SOURCE = 'ICMAN CSIC'
text = AnchoredText('$\copyright$ {}'.format(SOURCE),
loc=1, prop={'size': 9}, frameon=True)
ax.add_artist(text)
#Drawing the plot
chl.plot(ax=ax, transform=ccrs.PlateCarree(),
vmin=0.1, vmax=10, extend='both', cbar_kwargs={'shrink': 0.2, 'pad':0.01},
cmap="jet", norm=LogNorm(vmax=10))
#Figure title
ax.set_title("Chlorophyll NN (mg/m$^{3}$) " min_date_h " - " max_date_h)
uj5u.com熱心網友回復:
顏色條應該是圖中的最后一個軸 ( fig.axes[-1])。您可以手動設定顏色條的刻度和刻度標簽:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
X, Y = np.mgrid[-3:3:100j, -2:2:100j]
Z = 10*np.exp(-X**2 - Y**2)
fig, ax = plt.subplots()
pcm = ax.pcolor(X, Y, Z, norm=colors.LogNorm(vmin=.1, vmax=10), cmap='jet')
fig.colorbar(pcm, ax=ax)
cb = fig.axes[-1]
ticks = [.1,.2,.5,1,2,5,10]
cb.yaxis.set_ticks(ticks, labels=[f"{t:g}" for t in ticks])
cb.minorticks_off()
(在 matplotlib 3.5.0 之前,您必須分別設定刻度和標簽)。

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367159.html
標籤:Python matplotlib 蟒蛇-xarray 颜色条 卡托皮
上一篇:將影像添加到matplotlib中的圖例回傳錯誤:AttributeError:'BarContainer'objecthasnoattribute'_transform
