我有一个世界的底图,它使用pcolormesh填充数据(lintrends_mean).因为数据有相对较大的网格框,我想平滑情节.但是,我无法弄清楚如何做到这一点.在绘图功能中设置着色='gouraud'会模糊网格框的边缘,但我想要一些比这更好看的东西,因为数据仍然显得斑点.
这里有一个类似的问题给出了答案,但我不明白答案,特别是"newdepth"的来源.由于我的声誉不足,我无法对其进行澄清澄清. 使用matplotlib pcolor进行插值
#Set cmap properties
bounds = np.array([0.1,0.2,0.5,1,2,3,4,6,9,13,20,35,50])
norm = colors.LogNorm(vmin=0.01,vmax=55) #creates logarithmic scale
#cmap.set_under('#000099') # I want to use this- edit in Paint
cmap.set_over('#660000') # everything above range of colormap
fig = plt.figure(figsize=(15.,10.)) #create figure & size
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=0,urcrnrlon=360.,lon_0=180.,resolution='c') #create basemap & specify data area & res
m.drawcoastlines(linewidth=1)
m.drawcountries(linewidth=1)
m.drawparallels(np.arange(-90,90,30.),linewidth=0.3)
m.drawmeridians(np.arange(-180.,180.,90.),linewidth=0.3)
meshlon,meshlat = np.meshgrid(lon,lat) #meshgrid turns lats & lons into 2D arrays
x,y = m(meshlon,meshlat) #assign 2D arrays to new variables
trend = m.pcolormesh(x,y,lintrends_mean,cmap=plt.get_cmap('jet'),norm=norm) #plot the …Run Code Online (Sandbox Code Playgroud) 我有一个形状矩阵(64,17)对应时间和纬度.我想采用加权纬度平均值,我知道np.average可以做,因为,与我用来平均经度的np.nanmean不同,权重可以在参数中使用.但是,np.average不会像np.nanmean那样忽略NaN,所以我每行的前5个条目都包含在纬度平均值中,并使整个时间序列充满NaN.
有没有一种方法可以在没有将NaN包含在计算中的情况下采用加权平均值?
file = Dataset("sst_aso_1951-2014latlon_seasavgs.nc")
sst = file.variables['sst']
lat = file.variables['lat']
sst_filt = np.asarray(sst)
missing_values_indices = sst_filt < -8000000 #missing values have value -infinity
sst_filt[missing_values_indices] = np.nan #all missing values set to NaN
weights = np.cos(np.deg2rad(lat))
sst_zonalavg = np.nanmean(sst_filt, axis=2)
print sst_zonalavg[0,:]
sst_ts = np.average(sst_zonalavg, axis=1, weights=weights)
print sst_ts[:]
Run Code Online (Sandbox Code Playgroud)
输出:
[ nan nan nan nan nan
27.08499908 27.33333397 28.1457119 28.32899857 28.34454346
28.27285767 28.18571472 28.10199928 28.10812378 28.03411865
28.06411552 28.16529465]
[ nan nan nan nan nan nan nan nan nan nan nan …Run Code Online (Sandbox Code Playgroud) 问题
因此,我有50个netCDF4数据文件,其中包含全球网格上数十年的月度温度预测.我正在使用np.mean()将所有50个数据文件的整体平均值放在一起,同时保留时间长度和空间比例,但是np.mean()给出了两个不同的答案.我第一次运行它的代码块时,它给出了一个数字,当经纬度和经度平均并针对单个运行绘制时,它略低于整体平均值.如果我重新运行该块,它会给我一个看起来正确的不同均值.
代码
我不能复制每一行,因为它很长,但这是我为每次运行所做的.
#Historical (1950-2020) data
ncin_1 = Dataset("/project/wca/AR5/CanESM2/monthly/histr1/tas_Amon_CanESM2_historical-r1_r1i1p1_195001-202012.nc") #Import data file
tash1 = ncin_1.variables['tas'][:] #extract tas (temperature) variable
ncin_1.close() #close to save memory
#Repeat for future (2021-2100) data
ncin_1 = Dataset("/project/wca/AR5/CanESM2/monthly/histr1/tas_Amon_CanESM2_historical-r1_r1i1p1_202101-210012.nc")
tasr1 = ncin_1.variables['tas'][:]
ncin_1.close()
#Concatenate historical & future files together to make one time series array
tas11 = np.concatenate((tash1,tasr1),axis=0)
#Subtract the 1950-1979 mean to obtain anomalies
tas11 = tas11 - np.mean(tas11[0:359],axis=0,dtype=np.float64)
Run Code Online (Sandbox Code Playgroud)
我重复其他数据集的49倍.每个tas11,tas12等文件具有对应于月,纬度和经度的时间长度的形状(1812,64,128).
为了得到合奏的意思,我做了以下几点.
#Move all tas data to one array
alltas = np.zeros((1812,64,128,51)) #years, lat, lon, members …Run Code Online (Sandbox Code Playgroud) 问题
因此,我有一个包含6层(array.size = (192,288,6))的lat-lon数组,其中包含一堆数据,其值范围从近0到到0.65。当我从每个6图层([:,:,0],[:,:,1]等)绘制数据时,除了,我都没有问题并得到一张漂亮的地图[:,:,4]。出于某种原因,当我尝试绘制此2D数组时,收到一条我不理解的错误消息,并且仅当我尝试包含色条时才会出现。如果我不使用颜色条,就没有错误,但是我需要颜色条...
代码
这是我用于数组其他部分的代码以及生成的图。我们一起去吧[:,:,5]。
#Set labels
lonlabels = ['0','45E','90E','135E','180','135W','90W','45W','0']
latlabels = ['90S','60S','30S','Eq.','30N','60N','90N']
#Set cmap properties
bounds = np.array([0,0.001,0.01,0.05,0.1,0.2,0.3,0.4,0.5,0.6])
boundlabels = ['0','0.001','0.01','0.05','0.1','0.2','0.3','0.4','0.5','0.6']
cmap = plt.get_cmap('jet')
norm = colors.PowerNorm(0.35,vmax=0.65) #creates logarithmic scale
#Create basemap
fig,ax = plt.subplots(figsize=(15.,10.))
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=0,urcrnrlon=360.,lon_0=180.,resolution='c')
m.drawcoastlines(linewidth=2,color='w')
m.drawcountries(linewidth=2,color='w')
m.drawparallels(np.arange(-90,90,30.),linewidth=0.3)
m.drawmeridians(np.arange(-180.,180.,45.),linewidth=0.3)
meshlon,meshlat = np.meshgrid(lon,lat)
x,y = m(meshlon,meshlat)
#Plot variables
trend = m.pcolormesh(x,y,array[:,:,5],cmap='jet',norm=norm,shading='gouraud')
#Set plot properties
#Colorbar
cbar=m.colorbar(trend, size='5%',ticks=bounds,location='bottom',pad=0.8)
cbar.set_label(label='Here …Run Code Online (Sandbox Code Playgroud) 问题
我有一个情节,我试图使用网格化数据为世界各地的降水率趋势.我可以让情节本身很好,但颜色范围给我带来了问题.我无法弄清楚如何使色彩图更适合我的数据,这似乎是指数级的.我尝试了一个对数范围,但它并不完全适合数据.
代码和数据范围
这是我在简单的xy线图上按顺序绘制时的8,192个数据值.数据点位于x轴上,值位于y轴上.

这是我的数据看起来像使用LogNormal颜色范围绘制的.这对我来说太薄荷绿和橘红色了.
#Set labels
lonlabels = ['0','45E','90E','135E','180','135W','90W','45W','0']
latlabels = ['90S','60S','30S','Eq.','30N','60N','90N']
#Set cmap properties
norm = colors.LogNorm() #creates logarithmic scale
#Create basemap
fig,ax = plt.subplots(figsize=(15.,10.))
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=0,urcrnrlon=360.,lon_0=180.,resolution='c')
m.drawcoastlines(linewidth=1)
m.drawcountries(linewidth=1)
m.drawparallels(np.arange(-90,90,30.),linewidth=0.3)
m.drawmeridians(np.arange(-180.,180.,45.),linewidth=0.3)
meshlon,meshlat = np.meshgrid(lon,lat)
x,y = m(meshlon,meshlat)
#Plot variables
trend = m.pcolormesh(x,y,lintrends[:,:,0],cmap='jet', norm=norm, shading='gouraud')
#Set plot properties
#Colorbar
cbar=m.colorbar(trend, size='8%',location='bottom',pad=0.8) #Set colorbar
cbar.set_label(label='Linear Trend (mm/day/decade)',size=25) #Set label
for t in cbar.ax.get_xticklabels():
t.set_fontsize(25) #Set tick label sizes
#Titles & labels
fig.suptitle('Linear Trends of Precipitation (CanESM2)',fontsize=40,x=0.51,y=0.965)
ax.set_title('a) 1979-2014 …Run Code Online (Sandbox Code Playgroud) 我有一个我在ipython笔记本中使用两个导入的数据集和我为x轴制作的数组制作的情节,但颜色条有点厚,我喜欢.有没有办法让它更苗条?
#import packages
import numpy as np #for importing u array
import matplotlib.pyplot as plt #for plotting
%matplotlib inline
th = np.loadtxt("MT3_th.dat") #imports data file- theta pert.
pi = np.loadtxt("MT3_pi.dat") #imports data file- pressure pert.
k = np.loadtxt("MT3_z.dat") #imports data file- height
i = np.linspace(-16.,16.,81) #x-axis array
x, z = np.meshgrid(i, k)
th[th == 0.0] = np.nan #makes zero values for th white
clevels = [0.5, 1, 1.5, 2, 2.5, 3.]
fig = plt.figure(figsize=(12,12))
thplot = plt.contourf(x, z, th, clevels, …Run Code Online (Sandbox Code Playgroud) 所以我有一个底图,顶部有一个colormesh,另一个设置为cbar的颜色条.我希望colorbar方向是水平而不是垂直,但是当我在extend ='max'之后的cbar = m.colorbar行中设置orientation ='horizontal'时,我得到以下错误:"colorbar()获得了多个值关键字参数'orientation'"
有人在另一个问题上解释了为什么会发生这种情况,但老实说,我无法理解答案或看到如何解决问题的解释.有人可以帮忙吗?我尝试使用plt.colorbar,但由于某些原因不接受我的刻度设置.
这是我之前的情节......
#Set cmap properties
bounds = np.array([0.1,0.2,0.5,1,2,3,4,6,9,13,20,30])
norm = colors.LogNorm(vmin=0.1,vmax=30) #creates logarithmic scale
#Create basemap
fig = plt.figure(figsize=(15.,10.))
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=0,urcrnrlon=360.,lon_0=180.,resolution='c')
m.drawcoastlines(linewidth=1)
m.drawcountries(linewidth=1)
m.drawparallels(np.arange(-90,90,30.),linewidth=0.3)
m.drawmeridians(np.arange(-180.,180.,90.),linewidth=0.3)
meshlon,meshlat = np.meshgrid(lon,lat)
x,y = m(meshlon,meshlat)
#Plot variables
trend = m.pcolormesh(x,y,lintrends_36,cmap='jet', norm=norm, shading='gouraud')
#Set plot properties
plt.tight_layout()
#Colorbar
cbar=m.colorbar(trend, size='3%',ticks=bounds,extend="max") #THIS LINE
cbar.set_label(label='Linear Trend (mm/day/decade)',size=30)
cbar.set_ticklabels(bounds)
#Titles & labels
plt.suptitle('Linear Trends of Precipitation (CanESM2)',fontsize=40,y=0.962)
plt.title('a) 1979-2014',fontsize=40)
plt.ylabel('Latitude',fontsize=30)
plt.show()
Run Code Online (Sandbox Code Playgroud)
地图看起来像这样.
我有一个 Jupyter 笔记本,里面有很多大变量,有一次我想扔掉所有我已经用完的变量。我使用 %reset_selective 变量名来清除每个变量,但是这些变量有 60 个,当我运行包含所有 60 个提示的块时,它会要求我为每个清除输入 y/n。
“一旦删除,变量将无法恢复。继续 (y/[n])?”
有没有办法让我一次回答所有问题“y”,或者完全跳过提示?
问题
所以我有一个2D数组(151行,52列)我想使用np.savetxt保存为文本文件.但是,我希望第一列的数字保存为整数(1950,1951等),而其余数据保存为精度5(如果舍入为4)浮点数(2.7419,2.736等).我无法弄清楚如何做到这一点.
代码
当我打印数组输出的前4行和3列时,它看起来像这样.
[[1950. 2.7407 2.7396]
[1951. 2.7419 2.736]
[1952. 2.741 2.7374]
[1953. 2.7417 2.7325]]
当我使用以下...
np.savetxt('array.txt',data,fmt="%1.4f")
Run Code Online (Sandbox Code Playgroud)
该数组将第一列保存为精度为5的浮点数,如其余数据(1950.0000,1951.0000等).当我尝试指定不同的格式时......
np.savetxt('array.txt',data,fmt="%i %1.4f")
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:"ValueError:fmt%格式错误:%i%1.4f"
问题
有没有办法我把第一列保存为整数,其余列保存为浮点数?
问题
我有一个带有 2 个 y 轴的图,每个 y 轴对应一组线。实线对应左侧 y 轴,虚线对应右侧 y 轴。我还有一个图例,我希望它只使用实线作为键,因为虚线具有相同的标签,具体取决于它们的颜色。
问题是当我为实线绘制图例,然后为虚线绘制代码时,网格线通过图例显示。我需要为两个轴指定网格线,因为它们不会以其他方式显示,如果我将图例移动到虚线,它会使用虚线作为键。我也不想改变我的绘图顺序。
代码和情节
#Plot
x= np.arange(0,3)
fig,ax = plt.subplots(figsize=(6,6))
#DOD
dod1 = ax.plot(x, ctrl_dod, color='r', label='CTRL' )
dod2 = ax.plot(x, mfkc_dod, color='#e68a00', label='MFKC' )
dod3 = ax.plot(x, gses_dod, color='green', label='GSES' )
dod4 = ax.plot(x, gses3_dod, color='blue', label='GSES-3')
dod5 = ax.plot(x, gses4_dod, color='purple', label='GSES-4')
dod6 = ax.plot(x, mera_dod, color='brown', label='MERRA2')
ax.xaxis.grid(True)
ax.set_ylim([0.02,0.044])
ax.set_yticks(np.arange(0.02,0.045,0.004))
ax.set_xlabel('Month')
ax.set_ylabel('Dust Optical Depth (550 nm)')
ax.set_title('Global Mean DOD and DCM')
legend = ax.legend()
legend.get_frame().set_facecolor('white') …Run Code Online (Sandbox Code Playgroud) 问题
所以我导入的数组包含从~0.0到~0.76的值.当我开始尝试使用Numpy找到最小值和最大值时,我遇到了一些奇怪的不一致,如果他们是我的错,我想知道如何解决,或者避免如果他们在Numpy开发人员端编程错误.
代码
让我们从使用np.max&找到最大值的位置开始np.where.
print array.shape
print np.max(array)
print np.where(array == 0.763728955743)
print np.where(array == np.max(array))
print array[35,57]
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
(74, 145)
0.763728955743
(array([], dtype=int64), array([], dtype=int64))
(array([35]), array([57]))
0.763728955743
Run Code Online (Sandbox Code Playgroud)
当我查找数组恰好等于最大条目值的位置时,Numpy找不到它.但是,当我只是搜索最大值的位置而不指定该值是什么时,它就可以工作.请注意,这不会发生在np.min.
现在我对minima有一个不同的问题.
print array.shape
print np.min(array)
print np.where(array == 0.0)
print np.where(array == np.min(array))
print array[10,25], array[31,131]
Run Code Online (Sandbox Code Playgroud)
看看回报.
(74, 145)
0.0
(array([10, 25]), array([ 31, 131]))
(array([10, 25]), array([ 31, 131]))
0.0769331747301 1.54220192172e-09
Run Code Online (Sandbox Code Playgroud)
1.54 ^ -9足够接近0.0,看起来它似乎是最小值.但为什么值为0.077的位置也列出np.where?与其他值相比,这甚至不接近0.0.
问题
为什么np.where在输入数组的最大值时似乎不起作用,但在搜索时却是这样np.max(array)?为什么np.where() …
python ×11
matplotlib ×6
numpy ×4
arrays ×3
colorbar ×2
colormap ×1
exponential ×1
fill ×1
ipython ×1
legend ×1
mean ×1
minimum ×1
orientation ×1
text-files ×1
where ×1