“Matplotlib”的版本间差异

来自Shiyin's note
跳到导航 跳到搜索
 
(没有差异)

2023年10月12日 (四) 01:51的最新版本

  • ipython中事先执行 %matplotlib
交互式模式:plt.ion()
关闭交互式:plt.ioff()

配置

pyplot的style配置

  • 使用内置的style
plt.style.use('ggplot')
print(plt.style.available) (当前使用的style)
  • 可以自定义style

For example, you might want to create mpl_configdir/stylelib/presentation.mplstyle with the following:

axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16

Then, when you want to adapt a plot designed for a paper to one that looks good in a presentation, you can just add:

>>> import matplotlib.pyplot as plt
>>> plt.style.use('presentation')

matplotlib的配置

  • 使用matplotlib.rcParams
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'
  • matplotlib.rcdefaults() 恢复默认配置
  • matplotlibrc file
matplotlib.matplotlib_fname()

两种不同的画图模式

pylab风格

  • 简单的例子
plt.figure(1,figsize=(9, 3))
plt.plot(x, y,label='sin') 
plt.errorbar(x, y, xerr=0.1 * x, yerr=5.0 + 0.75 * y, ls='None', marker='s',uplims=True) #误差棒,ls='None' 表示不连线 
plt.xlim(0,3)  #调整坐标范围 或者用 plt.axis([40, 160, 0, 0.03])同时设定x和y轴的范围
plt.xscale('log') # 设置对数坐标格式,,
plt.xlabel('x label')
plt.title("Simple Plot")
plt.legend(loc='upper left') #图例  显示前面plot中的label
plt.axis('tight'); #坐标范围自动压缩
plt.show()
  • use keyword args
 lines = plt.plot(x, y)
 plt.setp(lines, color='r', linewidth=2.0) #[3]
  • plt.plot() 中的颜色,线型等
  • options for the color characters are: 'r' , 'g' , 'b' = blue, 'c' = cyan, 'm' = magenta, 'y' = yellow, 'k' = black, 'w' = white
  • Options for line styles are: '-' = solid, '--' = dashed, ':' = dotted, '-.' = dot-dashed, '.' = points, 'o' = filled circles, '^' = filled triangles
  • marker style [4]

面向对象风格

  • 通过关键词来配置图的要素,功能更强大,但是直观性稍弱
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
  • ax也可以在互动模式中通过 plt.gca()获取
ax=plt.gca()
  • axes的配置
ax.semilogx  : 对数坐标
ax. Grid :添加grid
ax.xaxis.tick_top() #坐标轴的tick显示在图的上方
ax.xaxis.set_label_position('top') #x坐标轴的label显示在图的上方,这一点似乎无法在交互式命令中简单实现

虽然大多数的plt函数都可以直接转换为ax的方法进行调用(例如plt.plot() → ax.plot(),plt.legend() → ax.legend()等),但是并不是所有的命令都能应用这种情况。特别是用于设置极值、标签和标题的函数都有一定的改变。下表列出了将 MATLAB 风格的函数转换为面向对象的方法的区别:

plt.xlabel() → ax.set_xlabel()
plt.ylabel() → ax.set_ylabel()
plt.xlim() → ax.set_xlim()
plt.ylim() → ax.set_ylim()
plt.title() → ax.set_title()
plt.subplot()等价的面向对象接口方法fig.add_subplot()

在面向对象接口中,与其逐个调用上面的方法来设置属性,更常见的使用ax.set()方法来一次性设置所有的属性:

ax = plt.axes()
ax. Plot(x, np.sin(x))
ax.set(xlim=(0, 10), ylim=(-2, 2),
      xlabel='x', ylabel='sin(x)',
      title='A Simple Plot');

专题

直方图

plt.hist()

  • 关键词有 bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None
    • bins=np.arange(2,3,0.1)
    • density=Ture #默认是False,如果是Trure相当于归一化
    • histtype: 可选{'bar', 'barstacked', 'step', 'stepfilled'}之一,默认为bar,推荐使用默认配置,step使用的是梯状,stepfilled则会对梯状内部进行填充,效果与bar类似,联合使用histtype='stepfilled'和alpha参数设置透明度在对不同分布的数据集进行比较展示时很有用:
    • log: bool,默认False,即y坐标轴是否选择指数刻度
    • ls(linestyle),这是个通用参数
linestyle	description
'-' or 'solid'	solid line
'--' or 'dashed'	dashed line
'-.' or 'dashdot'	dash-dotted line
':' or 'dotted'	dotted line
    • color,通用参数
  • 输出三个列表,前两个分别是直方图的数值和bin的取值,第三个patches啥意思不清楚
Freq, bins, patches = plt.hist(x, 50, normed=1)

二维直方图

  • 绘制二维直方图最直接的方法是使用 Matplotlib 的plt.hist2d或者hexbin:
plt.hist2d(x, y, bins=30, cmap='Blues')
plt.hexbin(x, y, gridsize=30, cmap='Blues')
  • 二维密度计算
  1. counts, xedges, yedges = np.histogram2d(x, y, bins=30)
  2. 核密度估计
  3. zdens=densxy(Spax_Ms[Lsel],Spax_RtoRe[Lsel],.10,0.05,xmin=7.,ymin=0.,nx=50,ny=60) # my own pro
from scipy.stats import gaussian_kde
data = np.vstack([x, y])
kde = gaussian_kde(data) # 产生和处理数据,初始化KDE
xgrid = np.linspace(-3.5, 3.5, 40)
ygrid = np.linspace(-6, 6, 40)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)
Z = kde.evaluate(np.vstack([Xgrid.ravel(), Ygrid.ravel()])) # 在通用的网格中计算得到Z的值

误差棒

  • plt.errorbar(x, y, yerr=dy, fmt='o', color='black',
            ecolor='lightgray', elinewidth=3, capsize=0);
  • 连续误差范围
plt.fill_between(xfit, yfit - dyfit, yfit + dyfit,
                color='gray', alpha=0.2)

图像

  • imshow()
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = np.exp(-X**2 - Y**2)
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
              origin='lower', extent=[-3, 3, -3, 3],
              vmax=abs(Z).max(), vmin=-abs(Z).max())     #lower 就是把index[0,0]放在左下,extent是数轴上标志的范围
Zm = np.ma.masked_where(Z > 1.2, Z) #mask image
plt.imshow(Zm)
  1. plt.imshow()不接受 x 和 y 网格值作为参数,因此你需要手动指定_extent_参数[xmin, xmax, ymin, ymax]来设置图表的数据范围。
  2. plt.imshow()使用的是默认的图像坐标,即左上角坐标点是原点,而不是通常图表的左下角坐标点。这可以通过设置origin参数来设置。
  3. plt.imshow()会自动根据输入数据调整坐标轴的比例;这可以通过参数来设置,例如,plt.axis(aspect='image')能让 x 和 y 轴的单位一致。

contour

X,Y=np.meshgrid(xx,yy)
plt.contour(X,Y,zdens,[50,200,500],color='blue')
plt.annotate('blue: high $\mu$ spaxels',(7.2,2.6),color='blue',size=20)
plt.contourf(X, Y, Z, 20, cmap='RdGy') #用颜色填充轮廓范围

contour不直接支持label和legend,要用legend,参见 [5]

有时可能需要将轮廓图和图像结合起来。例如,下例中我们使用了半透明的背景图像(通过alpha参数设置透明度),然后在背景图层之上绘制了轮廓图,并带有每个轮廓的数值标签(使用plt.clabel()函数绘制标签):

contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower',
          cmap='RdGy', alpha=0.5)
plt.colorbar();

colorbar

  • 自己定制的一个colorbar的实际例子,两个panel,共用一个colorbar
fig, axes=plt.subplots(2,1)
fig.subplots_adjust(right=0.9)
Mbin=np.range(5)+4
MR50=np.range(5)***2
SR50=np.ones(1)
age=np.log10(np.array([0.01,0.05,0.5,2.,8.])) #这个是颜色的取值
plt.subplot(2,1,1)#panel 1
plt.scatter(Mbin,MR50, c=age,cmap="rainbow")
plt.ylabel('Mean ln(R50) (log Age)')
plt.subplot(2,1,2)#panel 2
ax=plt.scatter(Mbin,SR50,c=age,cmap="rainbow")    
plt.xlabel('log(M*)')
plt.ylabel('$\sigma$ ln(R50) (log Age)')
position = fig.add_axes([0.92, 0.12, 0.015, .78 ])#位置[左,下,右,上]  
cb = fig.colorbar(ax,cax=position)  #color bar
cb.set_ticks(age) #设置colorbar 的ticks的位置
str=['{:.2f}'.format(v) for i,v in enumerate(10**age)] #设置colorbar的ticks的数值
cb.set_ticklabels(str)

patch

matplotlib.patches.Ellipse

  • ellipse matplotlib.patches.Ellipse(xy, width, height, angle=0, **kwargs)[6]

多个panel

  • fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
  • 可以通过plt.gca()获得当前(subplot)坐标轴的属性,通过plt.gcf()获得当前图形的属性。 同样地,plt.cla()和plt.clf()将分别清除当前的轴和图形。
 plt.subplot(211) # panels
 plt.subplots_adjust(hspace=0.3,vspace=0.3) #调整多个panel的间隔
 plt.subplot(212)
 plt.scatter(x, y) 
 plt.subtitle('Categorical Plotting')
 plt.tight_layout() #这个是重新排列的神器
 fig=plt.gcf()
 fig.suptitle('Title',fontsize=16) #给图一个总标题


  • 高级用法plt.subplot2grid()参见[7]

字体大小设置

  • plt.tick_params(labelsize=23) #设置图的坐标轴的字体大小
  • label的字体大小,直接添加 ‘size=18’这样的关键词

latex字符

plt.rc(usetex = True)
plt.xlabel('\\alpha') #转义 参见[8]
plt.xlabel(r'\alpha') #r'代表raw string

保存图片文件

  • plt.savefig("filename.png")
  • plt.savefig('SFH_LMC_miles.pdf',format='pdf')
  • 保存文件一片空白
在 plt.show() 后调用了 plt.savefig() ,在 plt.show() 后实际上已经创建了一个新的空白的图片(坐标轴),这时候你再 plt.savefig() 就会保存这个新生成的空白图片。
plt.show() 放在最后,或者
    # gcf: Get Current Figure
   fig = plt.gcf()
   plt.show()
   fig1.savefig('tessstttyyy.png', dpi=100)
  • matplotlib.use('PS') # generate postscript output by default #在importing matplotlib.pyplot之前用压倒一切设置
  • 按照原始图片分辨率保存图片
 if you want to save a image with 3841 x 7195 pixels, you could do the following:
plt.figure(figsize=(3.841, 7.195), dpi=100)
( your code ...)
plt.savefig('myfig.png', dpi=1000)

坐标变换