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

如何在Seaborn绘图中设置X轴刻度为每月第一天?

问题:Seaborn股票价格图仅显示每月第一天的X轴刻度

我在练习用Seaborn做可视化,基于自己创建的股票数据,希望在价格走势图的X轴上仅显示每月第一天作为刻度,但目前用固定步长设置xticks的方法不适用,请问怎么通过xticks()实现这个需求?

示例数据

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

# 创建示例数据集
np.random.seed(42)
num_entries = 100

start_date = datetime(2023, 1, 1)
date_list = [start_date + timedelta(days=i) for i in range(num_entries)]
prices = np.random.uniform(50, 200, num_entries)
volumes = np.random.randint(1000, 10000, num_entries)
returns = np.random.uniform(-0.1, 0.1, num_entries)

data = {
    "Date": date_list,
    "Price": prices,
    "Volume": volumes,
    "Returns": returns
}

df = pd.DataFrame(data)

原绘图代码

import seaborn as sns
import matplotlib.pyplot as plt

sns.lineplot(x = "Date", y = "Price", data = df)
plt.title("股价走势")
plt.xlabel("日期")
plt.xticks(ticks = np.arange(0,101,step=31))
plt.ylabel("股价")
plt.show()

解决方案

核心思路是先从DataFrame中筛选出每月第一天对应的行,提取它们的索引位置作为刻度位置,再将这些日期格式化后作为刻度标签,具体实现如下:

修改后的完整绘图代码

import seaborn as sns
import matplotlib.pyplot as plt

# 筛选每月第一天的记录,提取对应索引和格式化日期标签
month_start_indices = df.index[df['Date'].dt.day == 1]
month_start_labels = df['Date'][df['Date'].dt.day == 1].dt.strftime('%Y-%m-%d')

# 绘制折线图
sns.lineplot(x = "Date", y = "Price", data = df)
plt.title("股价走势")
plt.xlabel("日期")
# 设置自定义X轴刻度:位置为每月第一天的索引,标签为格式化后的日期
plt.xticks(ticks=month_start_indices, labels=month_start_labels, rotation=45)
plt.ylabel("股价")
plt.tight_layout()  # 自动调整布局,避免标签被截断
plt.show()

关键代码说明

  • df['Date'].dt.day == 1:利用pandas日期属性筛选出每月第一天的记录
  • df.index[...]:获取这些记录在DataFrame中的索引位置,作为xticks的ticks参数
  • dt.strftime('%Y-%m-%d'):将日期格式化为易读的字符串,作为刻度标签
  • rotation=45:旋转刻度标签,避免日期文本重叠
  • plt.tight_layout():自动调整图表布局,防止标签被边缘截断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:57:42