matplotlib图片/子图标题置于底部 设置坐标轴位置 python

In my thesis, I need to show three activation functions’ figures in one row. There are 3 points should be considered:

  1. show subplots
  2. move the axis to the center of the figure, like a normal coordinate system
  3. put the title at the bottom of the figure (default is at the top)
  4. only specific ticks showed on the axis

The one big figure also can be used in this way with similar functions.

Let’s do it!

subplots

fig = plt.figure(figsize=(16, 4))
ax = fig.add_subplot(1, 3, i+1)

move the position of the axis to center

ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

set title at the bottom

The parameter y in ax.set_title means “Set the y position of the text” (same as x).

  • 1: top
  • 0: bottom of graphic part
  • <0: lower than graphic part (too low will be out of the fig.)
  • >1: higher than the top (too high will be out of the fig.)
ax.set_title('('+letter[i]+') '+functions[i].__name__, y=-0.15, fontsize=14)

show the specific ticks on the axis

Only show [-1, -0.5, 0.5, 1] of y-aixs.

ax.set_yticks([-1, -0.5, 0.5, 1])

complete code and figure

def Sigmoid(x):	return 1.0/(1+np.exp(-1.0*x))
def sigmoid2(x):return 1.0/(1+np.exp(-1.0*x))-0.5
def TanH(x):	return 2.0/(1+np.exp(-2.0*x))-1
def ReLU(x):	return np.maximum(0, x)

functions = [Sigmoid, TanH, ReLU]
x = np.arange(-6.5, 6.5, 0.01)
letter = list(map(chr, range(ord('a'), ord('z') + 1))) 

fig = plt.figure(figsize=(16, 4))
plt.subplots_adjust(wspace=0.06)#, hspace =0.1)
for i in range(0, len(functions)):
	ax = fig.add_subplot(1,3,i+1)
	ax.spines['top'].set_color('none')
	ax.spines['right'].set_color('none')
	ax.xaxis.set_ticks_position('bottom')
	ax.spines['bottom'].set_position(('data', 0))
	ax.yaxis.set_ticks_position('left')
	ax.spines['left'].set_position(('data', 0))

	# set the title and move it to the bottom
	ax.set_title('('+letter[i]+') '+functions[i].__name__, y=-0.15, fontsize=14) 

	if i != 2: ax.set_yticks([-1, -0.5, 0.5, 1]) # change axis ticks
	elif i == 2: ax.set_yticks(list(np.arange(1,7,1)))
	plt.plot(x, functions[i](x),  linestyle="-", linewidth=2)

matplotlib图片/子图标题置于底部 设置坐标轴位置 python_第1张图片

Reference

matplotlib.axes.Axes.set_title

Mark a tutorial in Chinese

matplotlib图中的文本

Color and linestyle

python中matplotlib的颜色及线条控制

你可能感兴趣的:(Python)