如何删除特定的网格线?

How to remove a particular grid line?

请看下面的结果图。

我希望只删除 y 轴值为 10 处的一条主要网格线(蓝色水平线),并保留所有其他网格线。

有办法吗?

    plt.rcParams['font.family'] = 'Arial'
    fig, ax = plt.subplots(figsize=(14.78, 9.84))
    plt.xlim(0, 105)
    plt.ylim(0, 10)
    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.yaxis.set_minor_locator(AutoMinorLocator(2))
    ax.spines['bottom'].set_linewidth(1.5)
    ax.spines['left'].set_linewidth(1.5)
    ax.spines['top'].set_linewidth(0)
    ax.spines['right'].set_linewidth(0)
    # Grid setting
    plt.grid(True, color='#0100FF', which="major", ls="-")
    plt.grid(True, color='#0BC904', which="minor", ls="-")
    plt.xlabel("Indicator Amplitude, %FSH", fontsize=28, labelpad=15)
    plt.ylabel("Function Generator Output, V", fontsize=28, labelpad=15)
    # Axis setting
    plt.tick_params(which="major", labelsize=22, length=10, pad=10, width=1.5)
    plt.tick_params(which="minor", length=8, width=1.5)
    # Plot scatter & line
    plt.plot(FSH_axis, x_value[2:], color='black', marker='^', linewidth=1.5, markersize=8, label="40 dB")
    plt.plot(FSH_axis, y_value[2:], color='red', marker='o', linewidth=1.5, markersize=8, label="60 dB")
    plt.plot(FSH_axis, z_value[2:], color='blue', marker='v', linewidth=1.5, markersize=8, label="80 dB")

    plt.legend(loc=(1 / 16, 58 / 90), ncol=1, fontsize=20, frameon=True, framealpha=1, edgecolor="black")
    plt.show()

我们可以使用 get_ygridlines() 捕获所有网格线,然后将单个网格线作为 Line2D 对象访问以修改它们:

from matplotlib import pyplot as plt
from matplotlib.ticker import AutoMinorLocator

plt.rcParams['font.family'] = 'Arial'
fig, ax = plt.subplots(figsize=(14.78, 9.84))
plt.xlim(0, 105)
plt.ylim(0, 10)
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))

ax.spines['bottom'].set_linewidth(1.5)
ax.spines['left'].set_linewidth(1.5)
ax.spines['top'].set_linewidth(0)
ax.spines['right'].set_linewidth(0)
# Grid setting
plt.grid(True, color='#0100FF', which="major", ls="-")
plt.grid(True, color='#0BC904', which="minor", ls="-")

#this part is added
#set the last horizontal gridline invisible 
ygridlines = ax.get_ygridlines()
gridline_of_interest = ygridlines[-1]
gridline_of_interest.set_visible(False)

plt.xlabel("Indicator Amplitude, %FSH", fontsize=28, labelpad=15)
plt.ylabel("Function Generator Output, V", fontsize=28, labelpad=15)
# Axis setting
plt.tick_params(which="major", labelsize=22, length=10, pad=10, width=1.5)
plt.tick_params(which="minor", length=8, width=1.5)
# Plot scatter & line
FSH_axis = [10, 40, 100]

plt.plot(FSH_axis, [1, 3, 2], color='black', marker='^', linewidth=1.5, markersize=8, label="40 dB")
plt.plot(FSH_axis, [2, 2, 3], color='red', marker='o', linewidth=1.5, markersize=8, label="60 dB")
plt.plot(FSH_axis, [2, 1, 1], color='blue', marker='v', linewidth=1.5, markersize=8, label="80 dB")

plt.legend(loc=(1 / 16, 58 / 90), ncol=1, fontsize=20, frameon=True, framealpha=1, edgecolor="black")
plt.show()

示例输出:

当然对应的get_xgridlines()也存在