matplotlib 如何手动删除特定的ticklabel?

aiazj4mn  于 2023-05-01  发布在  其他
关注(0)|答案(3)|浏览(137)

在下面的图中,我想去掉一个特定的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比图中显示的多两个?

ss2ws0br

ss2ws0br1#

一个选择:

for tl in ax.get_yticklabels():
    if tl.get_text() == '0.0':  # or   if tl.get_text() in {'0.0'}:
        tl.set_visible(False)

plt.show()

另一个:

ax.set_yticks(np.arange(0.2, 1.1, 0.2))

plt.show()

输出:

r3i60tvu

r3i60tvu2#

您可以设置所需的显式刻度:

ax.set_yticks([.2, .4, .6, .8, 1.0])
ax.plot(x, y)
plt.show()

j2qf4p5b

j2qf4p5b3#

您可以使用自定义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)

输出:

相关问题