在下面的情节中,我想去掉一个特定的刻度标签:
这里是生成图像的代码:
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(-6, 6, 600)
def sigmoid(x):
return 1/(1+np.exp(-x))
y = sigmoid(x)
fig, ax = plt.subplots(figsize=(3,3), dpi=300)
# Move left y-axis and bottom x-axis to centre, passing through (0,0)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
# Eliminate upper and right axes
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# Show ticks in the left and lower axes only
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Set axis range
ax.set_xlim(-6, 6)
# ax.set_ylim(-2, 2)
# Set axis labels
ax.set_xlabel(r"$x$", loc='right')
ax.set_ylabel(r"sigmoid$(x)$", loc='top')
# Set axes facecolor
ax.set_facecolor('none')
print(ax.get_yticklabels())
ax.plot(x,y)
print(ax.get_yticklabels())
plt.show()
然后我在
plt.plot(x,y)
之前得到以下yticklabels:
[Text(0, 0.0, '0.0'), Text(0, 0.2, '0.2'), Text(0, 0.4, '0.4'), Text(0, 0.6000000000000001, '0.6'), Text(0, 0.8, '0.8'), Text(0, 1.0, '1.0')]
还有这些在
plt.plot(x,y)
之后
[Text(0, -0.2, '−0.2'), Text(0, 0.0, '0.0'), Text(0, 0.2, '0.2'), Text(0, 0.4000000000000001, '0.4'), Text(0, 0.6000000000000001, '0.6'), Text(0, 0.8, '0.8'), Text(0, 1.0000000000000002, '1.0'), Text(0, 1.2000000000000002, '1.2')
我的想法是使用如下代码更改标签:
ylabels = ax.get_yticklabels()
for lbl in ylabels:
lbl_txt = lbl.get_text().replace('−', '-') # replace U+2212 with normal '-' (U+002d)
if float(lbl_txt) == 0.:
lbl.set_text('')
ylabels = ax.get_yticklabels()
ax.set_yticklabels(ylabels)
但是,代码成功地将'0.0'标签替换为空字符串,但图形看起来是一样的。另外为什么返回的 yticklabels 比图中显示的多两个?
您可以使用自定义formatter:
from matplotlib.ticker import FuncFormatter
formatter = lambda x, pos: '' if np.isclose(x, 0) else np.round(x, 1)
ax.yaxis.set_major_formatter(formatter)
更新:您也可以简单地使用
ax.set_ylim(ymin=1e-9)
.
输出: