matplotlib笔记
有一个在线使用matplotlib的网址
cmap
选择cmap
choose colormap
创建cmap
create colormap
下面自定义从白色变到红色的cmap
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
N = 256
vals = np.ones((N, 4))
vals[:, 0] = np.linspace(1, 1, N)
vals[:, 1] = np.linspace(1, 0, N)
vals[:, 2] = np.linspace(1, 0, N)
newcmp = ListedColormap(vals)
def plot_examples(cms):
"""
helper function to plot two colormaps
"""
np.random.seed(19680801)
data = np.random.randn(30, 30)
fig, axs = plt.subplots(1, 2, figsize=(6, 3), constrained_layout=True)
for [ax, cmap] in zip(axs, cms):
psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4)
fig.colorbar(psm, ax=ax)
plt.show()
plot_example(newcmp)
当然也可以对已有的cmap进行修改,比如把最下面的部分值映射到白色
jet = cm.get_cmap('jet')
newcolors = jet(np.linspace(0, 1, 256))
white = np.array([250/256, 250/256, 250/256, 1])
newcolors[:25, :] = white
newcmp1 = ListedColormap(newcolors)
子图
断点轴(Broken axis)
这里有官方介绍利用子图画断点轴的方式
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
fig.subplots_adjust(hspace=0.05) # adjust space between axes
# hide the spines between ax and ax2
ax1.spines.bottom.set_visible(False)
ax2.spines.top.set_visible(False)
ax1.xaxis.tick_top()
ax1.tick_params(labeltop=False) # don't put tick labels at the top
ax2.xaxis.tick_bottom()
d = .5 # proportion of vertical to horizontal extent of the slanted line
kwargs = dict(marker=[(-1, -d), (1, d)], markersize=12,
linestyle="none", color='k', mec='k', mew=1, clip_on=False)
ax1.plot([0, 1], [0, 0], transform=ax1.transAxes, **kwargs)
ax2.plot([0, 1], [1, 1], transform=ax2.transAxes, **kwargs)
子图大小
matplotlib v3.6可以在subplots
中指定width_ratio
来控制子图的比例,但是在以前的版本,需要使用gridspec_kw={'width_ratios': [...]}
坐标轴
scale
默认有linear
,log
等,也可以自定义函数调整数值,例如下面使用两个匿名函数定义坐标变化
ax.set_yscale('function', functions=(lambda x: x**2, lambda x: x**0.5))
需要注意上述方法对于线性变换不起作用,需要直接修改tick的值,但是有时候需要细调细节,如下所示对于实际的数据值,坐标轴显示都除以binwidth
from matplotlib.ticker import FuncFormatter
ticks = FuncFormatter(lambda x, pos: '{0:.1E}'.format(x/binwidth))
ax.yaxis.set_major_formatter(ticks)
ax.yaxis.set_minor_formatter(ticks)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)