在下面的图中,我想去掉一个特定的ticklabel:
下面是生成图像的代码:
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比图中显示的多两个?
3条答案
按热度按时间ss2ws0br1#
一个选择:
另一个:
输出:
r3i60tvu2#
您可以设置所需的显式刻度:
j2qf4p5b3#
您可以使用自定义formatter:
更新:也可以简单使用
ax.set_ylim(ymin=1e-9)
。输出: