You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用seaborn whitegrid风格时如何显示x轴刻度线?

问题:启用Seaborn whitegrid风格后X轴刻度线消失

启用Seaborn的whitegrid风格后,X轴刻度线无法显示;不使用该风格时刻度线可正常显示。查阅seaborn.axes_style官方文档后仍未找到导致刻度线消失的配置项,使用的代码如下:

import datetime
import itertools
import random

import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.dates as mdates

chronos = np.arange('2024-03-01', '2024-07-01',  dtype='datetime64[D]')

with sns.axes_style("whitegrid"):
    sns.set({'xtick.bottom': True, 'xtick.top': True, 'patch.edgecolor': 'b'})
    fig, ax = plt.subplots(figsize=(20, 4), layout='constrained')
    sns.barplot(    
        x=chronos, 
        y=[random.randint(0, 10) for _ in chronos],
        ax=ax,
        width=1,
    )
    ax.tick_params(
        axis='x', 
        rotation=30
    )
    ax.tick_params(axis="both", colors="black")
    ax.xaxis.set_major_locator(
        mdates.MonthLocator(
            interval=1, 
            bymonthday=1
        )
    )

解决方案

方式一:通过tick_params强制开启刻度线

修改X轴的tick_params配置,添加bottom=True参数,直接强制显示底部刻度线:

ax.tick_params(
    axis='x', 
    rotation=30,
    bottom=True  # 新增此行,强制显示X轴底部刻度线
)

方式二:在启用风格时直接覆盖默认配置

whitegrid风格默认将xtick.bottom设为False,你可以在启用风格时直接传入自定义参数覆盖默认值,无需单独调用sns.set():

with sns.axes_style("whitegrid", {'xtick.bottom': True, 'xtick.top': True, 'patch.edgecolor': 'b'}):
    fig, ax = plt.subplots(figsize=(20, 4), layout='constrained')
    # 后续绘图代码保持不变

原因说明:之前在with块内调用sns.set()的配置会被axes_style上下文管理器的默认样式覆盖,所以无法生效。上述两种方式都能绕过这个覆盖逻辑,让刻度线正常显示。


内容的提问来源于stack exchange,提问作者Pablo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:20:05