imsave:保存像素数组与格式
区分数组保存和整张Figure保存。
学完这一章,你能够
- 区分数组保存和整张Figure保存。
- 区分数组保存和整张Figure保存。
两条保存路线
imsave把数组编码为图片,不含坐标轴和标题;要保存完整图表使用fig.savefig。fname可为路径或适用文件对象,父目录要先存在,相对路径依工作目录变化。
把像素数组保存为PNG文件,不含Figure轴及标题。
扩展名通常参与格式推断;format显式指定时以相应编码为准,不能一律说未传format就必定PNG。示例明确输出.png与.jpg并重新打开核对实际格式。
灰度、RGB与有损编码
二维数组加cmap=gray会映射后保存,产物可能为RGBA并非单通道灰度。需要严格L模式时使用Pillow显式转换并核对,不能从cmap名字推断文件通道。
彩色float数组需有效范围;JPEG不保留alpha且有损,往返不能做逐字节数值相等断言。PNG无损示例也需考虑归一化与8位量化,原始科学数组另用适当数值格式保存。
本站实际运行图:实际编码后重新读取的灰度映射PNG、RGB PNG和JPEG。

imsave参数及文件核对
| 参数/条目 | 类型或默认 | 用途 | 条件/准确说明 |
|---|---|---|---|
| fname | 路径或适用二进制对象 | 输出位置 | 扩展名/format决定编码,父目录先创建 |
| arr | 二维或RGB(A)数组 | 像素内容 | 二维cmap映射产物不一定单通道 |
| cmap/vmin/vmax | 当前支持参数 | 标量映射 | imsave当前不接受norm;RGB与标量处理分开 |
| format | 明确格式或推断 | PNG/JPEG等 | 不称任何情况下缺省都是PNG |
| origin | upper/lower | 数组行方向 | 与实际显示方位一致 |
| dpi | 数值 | 像素文件元数据等 | 不等于插值扩大数组尺寸 |
| metadata/pil_kwargs | 格式相关字典 | 元信息与编码选择 | 支持项依格式/Pillow版本 |
| 返回 | None | 通过文件再读取核对 | JPEG有损不能逐像素完全相等 |
本章独立核心源码与验证步骤
from plot_lab import run
if __name__ == "__main__":
run('matplotlib-imsave')
所需环境:Matplotlib3.11.2/NumPy2.5.4/Pandas3.1.0/Seaborn0.13.2/Pillow13.0.0;Python3.12 Windows Agg
当前源码 SHA256:adbd9aa01364d98329b061b498521dff70fa4ba4069afd0f5ecb3330a5e7e6e3
- 当前章全部明确断言通过;实际值、环境及文件哈希写入observations.json
- PNG可实际打开且属于本章,原图缺失与本站结果分开
本章真实实现和分支
"""Independent, deterministic Matplotlib experiments for mbsky.com."""
from pathlib import Path
import argparse,json,sys,hashlib,warnings,inspect
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager as fm
from matplotlib.ft2font import FT2Font
import numpy as np
from PIL import Image
MARKERS=['.',',','o','v','^','<','>','1','2','3','4','8','s','p','P','*','h','H','+','x','X','D','d','|','_',*range(12),'None',' ','','$f$']
COLORS={'b':(0,0,1,1),'g':(0,.5,0,1),'r':(1,0,0,1),'c':(0,.75,.75,1),'m':(.75,0,.75,1),'y':(.75,.75,0,1),'k':(0,0,0,1),'w':(1,1,1,1)}
def chinese_font(path=None):
# A fallback font may advertise every codepoint but render generic boxes.
# Never select Last Resort by a simple character-map membership search.
if path:
p=Path(path).resolve();assert p.is_file()
else:
p=Path(fm.findfont(fm.FontProperties(family='Microsoft YaHei'),fallback_to_default=False))
face=FT2Font(str(p));assert 'last resort'not in face.family_name.lower()
assert all(ord(c)in face.get_charmap()for c in '蓝色天空网学习中文负号')
return fm.FontProperties(fname=str(p)),dict(path=str(p),family=face.family_name,sha256=hashlib.sha256(p.read_bytes()).hexdigest(),redistributed=False)
def rgb_float(a):
a=np.asarray(a)
if np.issubdtype(a.dtype,np.integer):
assert a.min()>=0
a=a.astype(float)/np.iinfo(a.dtype).max
else:a=a.astype(float,copy=True)
if not np.isfinite(a).all() or a.min()<0 or a.max()>1:raise ValueError('RGB values must be finite in0..1')
return a
def run(key):
parser=argparse.ArgumentParser();parser.add_argument('--output',default='generated-'+key);parser.add_argument('--font');arg=parser.parse_args()
out=Path(arg.output).resolve();out.mkdir(parents=True,exist_ok=True);records=[];images=[];rng=np.random.default_rng(20261103)
def check(name,condition,actual):
if not condition:raise AssertionError((name,actual))
records.append(dict(case=name,passed=True,actual=actual))
def save(fig,name):
fig.suptitle('MBSKY | mbsky.com — '+name,fontsize=12)
target=out/(name+'.png');fig.canvas.draw();fig.savefig(target,dpi=120)
with Image.open(target)as im:
assert im.format=='PNG'and im.width>100 and im.height>100
arr=np.asarray(im.convert('RGB'));assert arr.std()>3
size=list(im.size)
images.append(dict(file=target.name,sha256=hashlib.sha256(target.read_bytes()).hexdigest(),size=size));plt.close(fig)
def error(name,action,expected=ValueError):
try:action()
except expected as e:check(name,True,type(e).__name__)
else:raise AssertionError('Expected error: '+name)
with matplotlib.rc_context({'figure.figsize':(8,5),'figure.dpi':120,'axes.grid':False}):
if key in {'matplotlib-tutorial','matplotlib-install'}:
f,a=plt.subplots(layout='constrained');line,=a.plot([1,2,3,4],[4,7,6,10],marker='o',label='Practice');a.set(xlabel='Round',ylabel='Simulated exercises');a.legend();check('actual_version_and_backend',matplotlib.__version__=='3.11.2'and matplotlib.get_backend().lower()=='agg',dict(matplotlib=matplotlib.__version__,numpy=np.__version__,python=sys.version,backend=matplotlib.get_backend(),requires_python=__import__('importlib.metadata',fromlist=['metadata']).metadata('matplotlib').get('Requires-Python')));check('coordinates',list(line.get_ydata())==[4,7,6,10],[int(v)for v in line.get_ydata()]);save(f,'first-learning-chart')
elif key=='matplotlib-pyplot':
f,axes=plt.subplots(2,3,layout='constrained')
inputs=[([0,6],[0,100],'-'),([1,8],[3,10],'-'),([1,8],[3,10],'o'),([1,2,6,8],[3,8,1,10],'-')]
for ax,(x,y,fmt)in zip(axes.flat,inputs):
line,=ax.plot(x,y,fmt);check('explicit-'+fmt+'-'+str(len(records)),np.array_equal(line.get_xdata(),x),dict(x=x,y=y,linestyle=line.get_linestyle()));ax.set_title('Explicit x/y '+fmt)
for ax,y in zip(list(axes.flat)[4:],[[3,10],[3,8,1,10,5,7]]):
line,=ax.plot(y,'r+');check('implicit-x-'+str(len(y)),list(line.get_xdata())==list(range(len(y))),[float(v)for v in line.get_xdata()]);ax.set_title('Implicit x: 0..N-1')
save(f,'plot-coordinate-branches');f,a=plt.subplots(layout='constrained');x=np.arange(0,4*np.pi,.1);lines=a.plot(x,np.sin(x),x,np.cos(x));lines[0].set_label('sin(x)');lines[1].set_label('cos(x)');a.legend();check('sin_cos_two_series',len(lines)==2 and np.allclose(lines[1].get_ydata(),np.cos(x)),dict(points=len(x),series=2));save(f,'sin-cos');f,a=plt.subplots();l,=a.plot([2,5,3],'bo');check('blue_circle_format',l.get_color()=='b'and l.get_marker()=='o',dict(color=l.get_color(),marker=l.get_marker()));save(f,'blue-circle-format')
elif key=='matplotlib-marker':
f,axes=plt.subplots(9,5,figsize=(12,16),layout='constrained')
for ax,m in zip(axes.flat,MARKERS):
line,=ax.plot([0,1,2],[0,1,0],marker=m);ax.set_title(repr(m));check('marker-'+repr(m),line.get_marker()==m,repr(line.get_marker()))
for ax in list(axes.flat)[len(MARKERS):]:ax.set_visible(False)
save(f,'all-marker-values');f,axes=plt.subplots(1,4,figsize=(12,4),layout='constrained')
styles=[dict(ms=20),dict(ms=20,mec='red'),dict(ms=20,mfc='red'),dict(ms=20,mec='#4CAF50',mfc='#4CAF50')]
for ax,style in zip(axes,styles):
l,=ax.plot([1,3,2],marker='o',**style);check('marker-style-'+str(len(records)),l.get_markersize()==20,dict(size=l.get_markersize(),edge=str(l.get_markeredgecolor()),face=str(l.get_markerfacecolor())))
save(f,'marker-size-face-edge');f,a=plt.subplots();l,=a.plot([2,6,3],'o:r');check('format-string',l.get_marker()=='o'and l.get_linestyle()==':'and l.get_color()=='r',dict(marker=l.get_marker(),line=l.get_linestyle(),color=l.get_color()));save(f,'format-string')
elif key=='matplotlib-line':
f,axes=plt.subplots(2,4,figsize=(12,7),layout='constrained');styles=['solid','dotted','dashed','dashdot','None','',' ']
for a,s in zip(axes.flat,styles):
l,=a.plot([4,1,5,3],linestyle=s,marker='o');a.set_title(repr(s));check('linestyle-'+repr(s),l.get_linestyle()in{'-',':','--','-.','None'},l.get_linestyle())
axes.flat[-1].set_visible(False);save(f,'line-styles');f,axes=plt.subplots(2,2,layout='constrained')
for a,color in zip(axes.flat,['r','#8FBC8F','SeaGreen','b']):
l,=a.plot([2,5,3],c=color,lw=12.5);check('color-width-'+color,l.get_linewidth()==12.5,dict(color=l.get_color(),linewidth=l.get_linewidth()))
save(f,'line-color-width');f,a=plt.subplots();lines=a.plot([0,1,2],[1,4,2],[0,1,2,3],[3,1,5,2]);check('different_length_series',len(lines)==2 and len(lines[1].get_xdata())==4,[len(l.get_xdata())for l in lines]);save(f,'multiple-lines');f,axes=plt.subplots(2,4,figsize=(12,6),layout='constrained')
for a,color in zip(axes.flat,COLORS):
l,=a.plot([1,3,2],color=color);a.set_title(color);a.set_facecolor('#dddddd');check('short-color-'+color,matplotlib.colors.to_rgba(l.get_color())==COLORS[color],COLORS[color])
save(f,'all-short-line-colors')
elif key in {'matplotlib-label','matplotlib-zh'}:
prop,font=chinese_font(arg.font);f,axes=plt.subplots(1,3,figsize=(13,4),layout='constrained')
for a,loc,yloc in zip(axes,['left','center','right'],['bottom','center','top']):
a.plot([-2,-1,0,1,2],[-4,-2,0,2,4],label='学习量');a.set_title('蓝色天空网',fontproperties=prop,loc=loc,color='blue',size=16);a.set_xlabel('学习轮次',fontproperties=prop,loc=loc);a.set_ylabel('模拟练习量',fontproperties=prop,loc=yloc);a.legend(prop=prop)
with warnings.catch_warnings(record=True)as ws:
warnings.simplefilter('always');f.canvas.draw();missing=[str(w.message)for w in ws if 'Glyph'in str(w.message)]
check('actual_chinese_font_no_missing_glyphs',not missing,dict(font=font,missing=missing));save(f,'chinese-label-locations')
f,axes=plt.subplots(1,2,layout='constrained');x=np.linspace(-3,3,20)
for a,minus in zip(axes,[True,False]):
with matplotlib.rc_context({'axes.unicode_minus':minus,'font.family':font['family']}):
a.scatter(x,np.sin(x)+rng.normal(0,.2,len(x)),label='模拟观测');a.plot(x,np.sin(x),label='设定规律');a.legend(prop=prop);a.set_title('Unicode minus='+str(minus));f.canvas.draw();labels=[t.get_text()for t in a.get_xticklabels()];check('minus-'+str(minus),any(('−'if minus else '-')in t for t in labels),labels)
save(f,'noise-and-negative-ticks')
elif key=='matplotlib-grid':
f,axes=plt.subplots(2,2,layout='constrained')
for a in axes.flat:a.plot([1,2,3,4],[1,4,9,16]);a.set_xticks([1,2,3,4]);a.set_yticks([0,5,10,15])
axes[0,0].grid(True);axes[0,1].grid(True,axis='x');axes[1,0].grid(color='r',ls='--',lw=.5);axes[1,1].minorticks_on();axes[1,1].grid(True,which='both');f.canvas.draw()
x=axes[0,1].get_xgridlines();y=axes[0,1].get_ygridlines();check('x_grid_only',all(l.get_visible()for l in x)and not any(l.get_visible()for l in y),dict(x_visible=sum(l.get_visible()for l in x),y_visible=sum(l.get_visible()for l in y)));check('grid_width',all(l.get_linewidth()==.5 for l in axes[1,0].get_xgridlines()),.5);axes[0,0].grid(False);check('explicit_off',not any(l.get_visible()for l in axes[0,0].get_xgridlines()),False);axes[0,0].grid(True);save(f,'grid-branches')
elif key=='matplotlib-subplots':
f=plt.figure(layout='constrained')
for index in range(1,5):
a=f.add_subplot(2,2,index);a.plot([1,2,3],[index,2*index,index]);a.set_title('subplot index='+str(index));check('subplot-index-'+str(index),a.get_subplotspec().num1==index-1,a.get_subplotspec().num1)
save(f,'subplot-index');
for shape in [(1,1),(1,2),(2,1),(2,2)]:
f,axes=plt.subplots(*shape,squeeze=False);check('squeeze-false-'+str(shape),axes.shape==shape,list(axes.shape));plt.close(f)
for shape,expected in [((1,1),()),((1,2),(2,)),((2,1),(2,)),((2,2),(2,2))]:
f,axes=plt.subplots(*shape);check('squeeze-default-'+str(shape),np.shape(axes)==expected,list(np.shape(axes)));plt.close(f)
for share in ['none','all','row','col',True,False]:
f,axes=plt.subplots(2,2,sharex=share,sharey=share);j=axes[0,0].get_shared_x_axes();same_row=j.joined(axes[0,0],axes[0,1]);same_col=j.joined(axes[0,0],axes[1,0]);check('share-'+str(share),(same_row,same_col)==((True,True)if share in{'all',True}else(True,False)if share=='row'else(False,True)if share=='col'else(False,False)),dict(row=same_row,col=same_col));plt.close(f)
f,axes=plt.subplots(2,2,subplot_kw={'projection':'polar'},layout='constrained');x=np.linspace(0,2*np.pi,100)
for a in axes.flat:a.plot(x,1+.3*np.sin(3*x))
check('polar_axes',all(a.name=='polar'for a in axes.flat),[a.name for a in axes.flat]);save(f,'polar-subplots');f,a=plt.subplots(num=10);a.plot([1,2]);f,b=plt.subplots(num=10,clear=True);check('clear_reused_figure',len(f.axes)==1 and not b.lines,len(f.axes));plt.close(f)
elif key=='matplotlib-scatter':
f,axes=plt.subplots(2,3,figsize=(12,7),layout='constrained');x=np.arange(8);y=np.array([1,4,9,16,7,11,23,18]);sizes=np.array([20,50,100,200,500,1000,60,90]);c=axes[0,0].scatter(x,y);check('default_area',np.allclose(c.get_sizes(),[matplotlib.rcParams['lines.markersize']**2]),c.get_sizes().tolist());c=axes[0,1].scatter(x,y,s=sizes);check('per_point_area',np.array_equal(c.get_sizes(),sizes),c.get_sizes().tolist());axes[0,2].scatter(x,y,c=['red','green','black','orange','purple','beige','cyan','magenta']);axes[1,0].scatter(x,y,color='hotpink');axes[1,0].scatter(x[:5],y[:5]+2,color='#88c999')
for a,cmap in zip(axes[1,1:],['viridis','afmhot_r']):
c=a.scatter(x,y,s=sizes,c=np.linspace(0,100,8),cmap=cmap,alpha=.5);f.colorbar(c,ax=a);check('cmap-'+cmap,c.get_cmap().name==cmap and c.get_alpha()==.5,c.get_clim())
save(f,'scatter-size-color');f,a=plt.subplots();c=a.scatter(rng.random(50),rng.random(50),s=(30*rng.random(50))**2,c=rng.random(50),alpha=.5);check('random_points',c.get_offsets().shape==(50,2),list(c.get_offsets().shape));save(f,'scatter-seeded')
f,a=plt.subplots();error('normalize_vmin_conflict',lambda:a.scatter([1,2],[1,2],c=[1,2],norm=matplotlib.colors.Normalize(0,3),vmin=0));plt.close(f)
elif key=='matplotlib-bar':
f,axes=plt.subplots(2,3,figsize=(12,7),layout='constrained');names=['A','B','C','D'];values=[12,22,6,18]
for a,mode in zip(axes.flat,['vertical','horizontal','single-color','colors','thin-width','thin-height']):
if mode in{'horizontal','thin-height'}:bars=a.barh(names,values,height=.1 if mode=='thin-height'else .8);check(mode,[b.get_width()for b in bars]==values,[b.get_width()for b in bars])
else:bars=a.bar(names,values,width=.1 if mode=='thin-width'else .8,color=['#4CAF50','red','hotpink','#556B2F']if mode=='colors'else'#4CAF50');check(mode,[b.get_height()for b in bars]==values,[b.get_height()for b in bars])
a.set_title(mode)
save(f,'bar-orientation-width');f,a=plt.subplots();bars=a.bar([1,2],[4,6],width=-.4,align='edge',bottom=[1,2]);check('negative_width_right_edge',np.allclose([max(b.get_x(),b.get_x()+b.get_width())for b in bars],[1,2]),[max(b.get_x(),b.get_x()+b.get_width())for b in bars]);save(f,'bar-right-edge')
elif key=='matplotlib-pie':
f,axes=plt.subplots(2,2,figsize=(10,9),layout='constrained');values=[35,25,25,15]
for a,name,kw in zip(axes.flat,['plain','labels-colors','explode-one-decimal','two-decimal-clockwise'],[{},dict(labels=list('ABCD'),colors=['#d5695d','#5d8ca8','#65a479','#a564c9']),dict(labels=list('ABCD'),explode=[0,.1,0,0],autopct='%.1f%%',shadow=True,startangle=90),dict(labels=list('ABCD'),explode=[0,.2,0,0],autopct='%.2f%%',counterclock=False)]):
result=a.pie(values,**kw);check('pie-container-'+name,type(result).__name__=='PieContainer',dict(type=type(result).__name__,unpacked=len(tuple(result)),wedges=len(result.wedges)));angles=[abs(w.theta2-w.theta1)for w in result.wedges];check('pie-angles-'+name,np.allclose(angles,[126,90,90,54],atol=1e-4),angles);a.set_title(name)
save(f,'pie-branches');f,a=plt.subplots();p=a.pie([.2,.3],normalize=False);check('partial_pie',np.isclose(sum(w.theta2-w.theta1 for w in p.wedges),180,atol=1e-4),sum(w.theta2-w.theta1 for w in p.wedges));error('sum_over_one_without_normalization',lambda:a.pie([2,3],normalize=False));error('negative_pie',lambda:a.pie([2,-1]));save(f,'partial-pie');f,a=plt.subplots();p=a.pie([15,30,45,10],labels=list('ABCD'),radius=1.2,center=(.2,.1),frame=True,rotatelabels=True,autopct='%.1f%%',pctdistance=.5,labeldistance=.9,wedgeprops={'linewidth':2,'edgecolor':'black'},textprops={'fontsize':10});check('pie_geometry_and_text',all(np.isclose(w.r,1.2)and w.get_linewidth()==2 for w in p.wedges),dict(center=p.wedges[0].center,radius=p.wedges[0].r,return_length=len(tuple(p))));save(f,'pie-position-and-properties')
elif key=='matplotlib-hist':
import pandas as pd
f,axes=plt.subplots(2,3,figsize=(12,7),layout='constrained');data=np.array([0,.5,1,1.5,2,3,4]);edges=[0,1,2,4];n,b,_=axes[0,0].hist(data,bins=edges);check('bin_edges_last_inclusive',n.tolist()==[2,2,3],n.tolist());n,b,_=axes[0,1].hist(data,bins=edges,density=True);area=float(np.sum(n*np.diff(b)));check('density_area_not_sum',np.isclose(area,1)and not np.isclose(n.sum(),1),dict(area=area,height_sum=float(n.sum())));n,_,_=axes[0,2].hist(data,bins=edges,weights=np.arange(1,8));check('weighted_total',n.sum()==28,n.tolist());n,_,_=axes[1,0].hist(data,bins=edges,cumulative=True);check('cumulative_total',n[-1]==7,n.tolist());groups=[rng.normal(m,1,1000)for m in[0,2,-2]];axes[1,1].hist(groups,bins=np.linspace(-6,6,31),alpha=.5,label=['mean0','mean2','mean-2']);axes[1,1].legend();pd.DataFrame({'practice':rng.normal(170,10,250)}).hist(ax=axes[1,2]);save(f,'histogram-branches');f,a=plt.subplots();a.hist(pd.Series(rng.normal(size=100)),bins=10,histtype='step',orientation='horizontal');check('series_count',len(a.patches)==1,len(a.patches));save(f,'series-horizontal-step');f,a=plt.subplots();n,b,patches=a.hist([[0,1,2],[1,2,3]],bins=[0,1,2,3],stacked=True,label=['GroupA','GroupB']);a.legend();check('stacked_total',np.allclose(n[-1],[1,2,3]),n.tolist());save(f,'hist-stacked')
elif key in {'matplotlib-imshow','matplotlib-imsave','matplotlib-imread'}:
error('imsave_norm_not_supported',lambda:plt.imsave(out/'unsupported-norm.png',np.zeros((2,2)),norm=matplotlib.colors.Normalize()),TypeError);gray=np.linspace(0,1,100).reshape(10,10);rgb=np.stack([gray,np.flipud(gray),np.full_like(gray,.3)],axis=-1);rgba=np.dstack([rgb,np.full_like(gray,.7)]);plt.imsave(out/'mbsky-gray.png',gray,cmap='gray');plt.imsave(out/'mbsky-rgb.png',rgb);plt.imsave(out/'mbsky-rgb.jpg',rgb);Image.fromarray((gray*255).astype('uint8')).save(out/'mbsky-l-gray.png');plt.imsave(out/'mbsky-rgba.png',rgba)
decoded={n:plt.imread(out/n)for n in['mbsky-gray.png','mbsky-rgb.png','mbsky-rgb.jpg','mbsky-l-gray.png','mbsky-rgba.png']};check('gray_2d',decoded['mbsky-l-gray.png'].shape==(10,10),dict(shape=list(decoded['mbsky-l-gray.png'].shape),dtype=str(decoded['mbsky-l-gray.png'].dtype)));check('cmap_gray_saved_rgba',decoded['mbsky-gray.png'].shape==(10,10,4),list(decoded['mbsky-gray.png'].shape));check('jpeg_uint8',decoded['mbsky-rgb.jpg'].dtype==np.uint8,dict(dtype=str(decoded['mbsky-rgb.jpg'].dtype),shape=list(decoded['mbsky-rgb.jpg'].shape)));check('png_float',np.issubdtype(decoded['mbsky-rgb.png'].dtype,np.floating),str(decoded['mbsky-rgb.png'].dtype));check('dtype_normalization',np.allclose(rgb_float(np.array([0,255],dtype=np.uint8)),[0,1]),[0,1]);error('invalid_float_rgb',lambda:rgb_float(np.array([0.,255.])))
f,axes=plt.subplots(2,3,figsize=(12,7),layout='constrained');matrix=np.linspace(0,1,16).reshape(4,4)
for a,name,arr,kw in zip(axes.flat,['gray','RGB','hot','matrix','nearest','bicubic'],[gray,rgb,gray,gray,matrix,matrix],[dict(cmap='gray'),{},dict(cmap='hot',origin='lower',extent=[-2,2,-1,1]),{},dict(interpolation='nearest'),dict(interpolation='bicubic')]):
im=a.imshow(arr,**kw);a.set_title(name);check('image-shape-'+name,np.array_equal(im.get_array(),arr),dict(shape=list(im.get_array().shape),origin=im.origin,extent=[float(x)for x in im.get_extent()]));
if name=='hot':f.colorbar(im,ax=a)
save(f,'imshow-branches');f,a=plt.subplots();Y,X=np.mgrid[:80,:120];plan=np.zeros((80,120,3),dtype=float);plan[:]=[.9,.95,1];plan[20:60,30:90]=[.3,.65,.4];plan[:,58:64]=[.3,.6,.95];plan[38:43,:]=[.3,.6,.95];plt.imsave(out/'mbsky-simulated-plan.png',plan);opened=Image.open(out/'mbsky-simulated-plan.png');a.imshow(np.asarray(opened));a.set_axis_off();check('local_owned_plan_dependency',opened.size==(120,80),dict(size=list(opened.size),kind='Owned simulated plan, not original map or measured geography'));save(f,'owned-simulated-plan');source=rgb_float(decoded['mbsky-rgb.jpg']);f,axes=plt.subplots(2,2,layout='constrained')
for a,factor in zip(axes.flat,[1,.8,.6,.4]):a.imshow(source*factor);a.set_title('RGB scale '+str(factor));a.set_axis_off()
check('darkening_preserves_alpha',np.allclose(np.dstack([rgba[:,:,:3]*.4,rgba[:,:,3]])[:,:,3],rgba[:,:,3]),.7);save(f,'image-darkening');f,axes=plt.subplots(1,2,layout='constrained');crop=source[1:8,2:7,:];red=source.copy();red[:,:,[1,2]]=0;axes[0].imshow(crop);axes[1].imshow(red);check('crop_shape',crop.shape==(7,5,3),list(crop.shape));check('red_channels_zero',np.all(red[:,:,1:]==0)and np.any(source[:,:,1:]>0),True);save(f,'crop-and-red');
if key=='matplotlib-imsave':
f,axes=plt.subplots(1,3,figsize=(12,4),layout='constrained')
for a,name in zip(axes,['mbsky-gray.png','mbsky-rgb.png','mbsky-rgb.jpg']):
a.imshow(decoded[name]);a.set_title(name+' / '+str(decoded[name].dtype));a.set_axis_off()
save(f,'saved-arrays-and-formats')
for file in out.glob('mbsky-*'):
with Image.open(file)as im:check('saved-format-'+file.name,im.format==('JPEG'if file.suffix=='.jpg'else'PNG'),dict(format=im.format,mode=im.mode,size=list(im.size)))
elif key=='seaborn-tutorial':
import seaborn as sns,pandas as pd
df=pd.DataFrame({'group':np.repeat(['A','B','C'],20),'round':np.tile(np.arange(20),3),'value':np.concatenate([rng.normal(m,1,20)for m in[3,6,4]])});f,axes=plt.subplots(2,3,figsize=(12,8),layout='constrained')
with sns.axes_style('whitegrid'),sns.plotting_context('notebook'):
sns.scatterplot(data=df,x='round',y='value',hue='group',ax=axes[0,0]);sns.lineplot(data=df,x='round',y='value',errorbar=None,ax=axes[0,1]);sns.barplot(data=df,x='group',y='value',errorbar=None,ax=axes[0,2]);sns.boxplot(data=df,x='group',y='value',ax=axes[1,0]);sns.heatmap(pd.DataFrame({'A':[1,2,3,4,5],'B':[5,4,3,2,1]}).corr(),annot=True,fmt='.2f',cmap='coolwarm',ax=axes[1,1]);sns.violinplot(data=df,x='group',y='value',ax=axes[1,2])
expected=df.groupby('group')['value'].mean().to_numpy();actual=np.array([p.get_height()for p in axes[0,2].patches]);check('barplot_category_means',np.allclose(actual,expected),actual.tolist());check('correlation_minus_one',np.isclose(pd.Series([1,2,3,4,5]).corr(pd.Series([5,4,3,2,1])),-1),-1);save(f,'seaborn-six-functions')
for style in ['darkgrid','whitegrid','dark','white','ticks']:check('style-'+style,bool(sns.axes_style(style)),dict(sns.axes_style(style)))
for context in ['paper','notebook','talk','poster']:check('context-'+context,sns.plotting_context(context)['font.size']>0,sns.plotting_context(context)['font.size'])
elif key in {'matplotlib-func','matplotlib-apiref'}:
catalog=json.loads((Path(__file__).parent/'api-catalog.json').read_text(encoding='utf8'));missing={(t['owner'],t['name'])for r in catalog['records']for t in r.get('targets',[])if not t['exists']};check('catalog_owner_corrections',missing=={('pyplot','supxlabel'),('pyplot','supylabel')},sorted(missing));check('catalog_all_rows',len(catalog['records'])==1009,len(catalog['records']))
x=np.linspace(0,10,100);f,a=plt.subplots(layout='constrained');a.plot(x,np.sin(x),label='sin');a.plot(x,np.cos(x),'--',label='cos');index=int(np.argmax(np.sin(x)));a.scatter([x[index]],[np.sin(x[index])],s=100);a.annotate('Sampled peak',xy=(x[index],np.sin(x[index])),xytext=(4,1.2),arrowprops={'arrowstyle':'->'});a.legend();check('sampled_peak',np.sin(x[index])==max(np.sin(x)),dict(index=index,x=float(x[index]),y=float(np.sin(x[index]))));save(f,'reference-lines-peak')
f,axes=plt.subplots(2,2,layout='constrained');axes[0,0].plot(x,np.sin(x));axes[0,1].scatter(rng.random(50),rng.random(50));bars=axes[1,0].bar(['A','B','C'],[23,45,56]);axes[1,0].bar_label(bars);axes[1,1].hist(rng.normal(size=1000),bins=30);check('reference_four_panels',len(f.axes)==4,len(f.axes));save(f,'reference-four-panels')
f,axes=plt.subplots(1,2,layout='constrained');q=np.linspace(-3,3,100);X,Y=np.meshgrid(q,q);Z=np.sin(X)*np.cos(Y);im=axes[0].imshow(Z,extent=[-3,3,-3,3],origin='lower');cs=axes[1].contourf(X,Y,Z,levels=15);axes[1].contour(X,Y,Z,levels=15,colors='black',linewidths=.5);f.colorbar(im,ax=axes[0]);f.colorbar(cs,ax=axes[1]);check('reference_field',Z.shape==(100,100),list(Z.shape));save(f,'reference-heatmap-contours')
with plt.style.context('ggplot'):
f,a=plt.subplots(layout='constrained');a.plot(x,np.exp(-x/3)*np.sin(2*x),'o-',label='Damped sin');a.plot(x,np.exp(-x/3)*np.cos(2*x),'s--',label='Damped cos');a.legend();path=out/'mbsky-damped-300dpi.png';f.savefig(path,dpi=300);check('actual_300dpi_output',Image.open(path).size==(2400,1500),list(Image.open(path).size));save(f,'reference-damped-style')
f,axes=plt.subplot_mosaic([['A','A','A'],['B','C','D']],layout='constrained');axes['A'].plot(x,np.sin(x));axes['B'].pie([3,2,1]);axes['C'].bar(['X','Y','Z'],[10,25,15]);axes['D'].imshow(rng.random((5,5)));check('mosaic_four_named_axes',set(axes)==set('ABCD'),list(axes));save(f,'reference-mosaic')
f,a=plt.subplots(layout='constrained');a.plot(x,np.sin(x));twin=a.twinx();twin.plot(x,np.exp(x/5),'r--');ins=a.inset_axes([.15,.5,.3,.35]);ins.plot(x,np.sin(x));ins.set(xlim=(3,5),ylim=(-1.2,1.2));a.indicate_inset_zoom(ins);secondary=a.secondary_xaxis('top',functions=(lambda v:v*180/np.pi,lambda v:v*np.pi/180));check('twin_shared_x',a.get_shared_x_axes().joined(a,twin),True);check('secondary_inverse',np.allclose((x*180/np.pi)*np.pi/180,x),True);save(f,'reference-dual-inset-secondary')
else:raise ValueError(key)
result=dict(chapter=key,passed=True,records=records,images=images,backend=matplotlib.get_backend(),source_scripts_executed=False,scope='Own deterministic numerical/Artist/Agg file execution; not GUI, Notebook, source-semantic or user acceptance')
(out/'observations.json').write_text(json.dumps(result,ensure_ascii=False,indent=2,default=lambda v:v.item()if isinstance(v,np.generic)else str(v))+'\n',encoding='utf8');print(json.dumps(result,ensure_ascii=False,default=lambda v:v.item()if isinstance(v,np.generic)else str(v)))
所需环境:Matplotlib3.11.2/NumPy2.5.4/Pandas3.1.0/Seaborn0.13.2/Pillow13.0.0;Python3.12 Windows Agg
当前源码 SHA256:7159c5c25ec5426843135cca762df7f51a6a4c64744dacbd9decca9c67649c34
- 当前章全部明确断言通过;实际值、环境及文件哈希写入observations.json
- PNG可实际打开且属于本章,原图缺失与本站结果分开
常见错误与边界
- 把属性当方法,或把旧参数/默认值套到当前版本。
- 把Agg静态图当桌面/Notebook交互验收,或把本站复现图当原图。
练习与解答
在副本改变一个数据、格式或有效条件,先预判再运行核对。
展开参考解答
按数组形状、数值/几何、文字和图元状态分别对照,勿仅检查PNG数量。