簡體   English   中英

如何從 matplotlib/seaborn 圖中刪除或隱藏 y 軸刻度標簽

[英]How to remove or hide y-axis ticklabels from a matplotlib / seaborn plot

我做了一個看起來像這樣的情節

在此處輸入圖片說明

我想關閉沿 y 軸的刻度標簽。 要做到這一點,我正在使用

plt.tick_params(labelleft=False, left=False)

現在劇情是這樣的。 即使關閉了標簽,比例1e67仍然存在。 在此處輸入圖片說明

關閉比例1e67會使繪圖看起來更好。 我怎么做?

  • seaborn用於繪制繪圖,但它只是matplotlib的高級 API。
    • 用於刪除 y 軸標簽和刻度的函數是matplotlib方法。
  • 創建 plot 后,使用.set()
  • .set(yticklabels=[])應該刪除刻度標簽。
    • 如果您使用.set_title()則這不起作用,但您可以使用.set(title='')
  • .set(ylabel=None)應該刪除軸標簽。
  • .tick_params(left=False)將刪除刻度。
  • 同樣,對於 x 軸:如何從 seaborn / matplotlib 圖中刪除或隱藏 x 軸標簽?

示例 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()

在此處輸入圖片說明

刪除標簽

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)

在此處輸入圖片說明

刪除標簽

# plot
fig, ax = plt.subplots(figsize=(8, 8))
ax.plot('radians', 'freq: 1x', data=df)
ax.set(yticklabels=[])  # remove the tick labels
ax.tick_params(left=False)  # remove the ticks

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM