如何从matplotlib/seaborn图中删除或隐藏y轴刻度标签

13

我做了一个看起来像这样的图表

此处输入图片描述

我想关闭y轴上的刻度标签。我使用以下代码实现:


```python ax = plt.gca() ax.tick_params(axis='y', which='both', labelleft=False, labelright=False) ```
plt.tick_params(labelleft=False, left=False)

现在情节看起来是这样的。尽管标签被关闭,比例尺1e67仍然存在。 enter image description here

关闭比例尺1e67会让情节看起来更好。我该怎么做?


这个回答解决了你的问题吗?如何从 seaborn/matplotlib 图表中删除或隐藏 x 轴标签 - Uchendu
1个回答

22
  • seaborn被用来绘制图表,但它只是matplotlib的高级API。
  • 调用函数以删除y轴标签和刻度线使用的是matplotlib方法。
  • 创建图表后,使用.set()
  • .set(yticklabels=[])可用于删除刻度标签。
    • 如果使用.set_title(),这将无效,但可以使用.set(title='')
  • .set(ylabel=None)可用于删除轴标签。
  • .tick_params(left=False)将删除刻度线。
  • 同样,对于x轴:如何从seaborn/matplotlib图表中删除或隐藏x轴标签?
  • python 3.11pandas 1.5.2matplotlib 3.6.2seaborn 0.12.1中进行测试

示例1

import seaborn as sns
import matplotlib.pyplot as plt

# load data
exercise = sns.load_dataset('exercise')
pen = sns.load_dataset('penguins')

# create figures
fig, ax = plt.subplots(2, 1, figsize=(8, 8))

# plot data
g1 = sns.boxplot(x='time', y='pulse', hue='kind', data=exercise, ax=ax[0])

g2 = sns.boxplot(x='species', y='body_mass_g', hue='sex', data=pen, ax=ax[1])

plt.show()

进入图片描述

去除标签


(注:此处指IT技术中的“标签”,非商品标签等其他含义)
fig, ax = plt.subplots(2, 1, figsize=(8, 8))

g1 = sns.boxplot(x='time', y='pulse', hue='kind', data=exercise, ax=ax[0])

g1.set(yticklabels=[])  # remove the tick labels
g1.set(title='Exercise: Pulse by Time for Exercise Type')  # add a title
g1.set(ylabel=None)  # remove the axis label

g2 = sns.boxplot(x='species', y='body_mass_g', hue='sex', data=pen, ax=ax[1])

g2.set(yticklabels=[])  
g2.set(title='Penguins: Body Mass by Species for Gender')
g2.set(ylabel=None)  # remove the y-axis label
g2.tick_params(left=False)  # remove the ticks

plt.tight_layout()
plt.show()

示例2

在这里输入图片描述

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# sinusoidal sample data
sample_length = range(1, 1+1) # number of columns of frequencies
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([(np.cos(t*rads)*10**67) + 3*10**67 for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])
df.reset_index(inplace=True)

# plot
fig, ax = plt.subplots(figsize=(8, 8))
ax.plot('radians', 'freq: 1x', data=df)

# or skip the previous two lines and plot df directly
# ax = df.plot(x='radians', y='freq: 1x', figsize=(8, 8), legend=False)

输入图像描述

移除标签

# plot
fig, ax = plt.subplots(figsize=(8, 8))
ax.plot('radians', 'freq: 1x', data=df)

# or skip the previous two lines and plot df directly
# ax = df.plot(x='radians', y='freq: 1x', figsize=(8, 8), legend=False)

ax.set(yticklabels=[])  # remove the tick labels
ax.tick_params(left=False)  # remove the ticks

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接