Matplotlib调用set_visible(False)后Y轴仍可见,如何彻底移除?
I'm trying to plot a chart with Matplotlib and want to completely remove the Y-axis. My current code only removes the Y-axis ticks, but the axis line is still visible. Here's my code:
import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.stats import skewnorm f = plt.figure(figsize=(8,4)) ax = f.add_subplot(111) colors = ["windows blue", "faded green", "dusty purple"] colors = sns.xkcd_palette(colors) b = 4 for j, a in enumerate([(0, 'No skew'), (b, 'Positive skew'), (-b, 'Negative skew')]): x = np.linspace(skewnorm.ppf(0.001, a[0]), skewnorm.ppf(0.999, a[0]), 100) y = skewnorm.pdf(x, a[0]) plt.plot(x, y, label=a[1], color=colors[j]) ax.yaxis.set_visible(False) plt.legend(loc=2) sns.despine()
Great question! The issue here is that ax.yaxis.set_visible(False) only hides the Y-axis ticks, tick labels, and axis label—it doesn't touch the vertical axis line (called a "spine" in Matplotlib terminology).
To fully remove the Y-axis including the spine, you have two straightforward options:
Option 1: Update sns.despine() to remove the left spine
By default, sns.despine() only removes the top and right spines. Add the left=True parameter to tell it to also remove the left (Y-axis) spine:
import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.stats import skewnorm f = plt.figure(figsize=(8,4)) ax = f.add_subplot(111) colors = ["windows blue", "faded green", "dusty purple"] colors = sns.xkcd_palette(colors) b = 4 for j, a in enumerate([(0, 'No skew'), (b, 'Positive skew'), (-b, 'Negative skew')]): x = np.linspace(skewnorm.ppf(0.001, a[0]), skewnorm.ppf(0.999, a[0]), 100) y = skewnorm.pdf(x, a[0]) plt.plot(x, y, label=a[1], color=colors[j]) ax.yaxis.set_visible(False) plt.legend(loc=2) sns.despine(left=True) # Modified line to remove left spine plt.show()
Option 2: Directly hide the left spine via Matplotlib
If you prefer not to rely on seaborn for this, you can directly access the left spine and set it to invisible:
# Add this line right after ax.yaxis.set_visible(False) ax.spines['left'].set_visible(False)
Either approach will give you a plot with no trace of the Y-axis—no ticks, no labels, and no vertical line.
内容的提问来源于stack exchange,提问作者Tim

