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

Matplotlib赛博朋克风格图表X轴替换为自定义日期方法咨询

赛博朋克风格图表替换X轴刻度为自定义日期的实现方案

问题描述

使用赛博朋克风格绘制Matplotlib图表时,需要将X轴默认的0-6刻度替换为自定义日期列表(如2023-01、2023-02等),日期存储在Data列表中,现有赛博朋克风格绘图代码已给出,需修改实现刻度替换。

实现步骤

  • 确保自定义日期列表Data的长度与数据行数完全匹配(示例中DataFrame有7行数据,因此Data需包含7个日期)
  • 通过ax.set_xticks()指定X轴刻度的位置(对应原数据的索引位置)
  • 通过ax.set_xticklabels()将自定义日期设置为刻度显示文本
  • 可选:若日期标签显示拥挤,添加plt.xticks(rotation=45)旋转标签,提升可读性

修改后的完整代码

import pandas as pd
import matplotlib.pyplot as plt

plt.style.use("dark_background")

# 设置全局样式参数
for param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']:
    plt.rcParams[param] = '0.9'  # 浅灰色文本

for param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']:
    plt.rcParams[param] = '#212946'  # 蓝灰色背景

colors = [
    '#08F7FE',  # 青蓝色
    '#FE53BB',  # 粉色
    '#F5D300',  # 黄色
    '#00ff41',  # 矩阵绿
]

# 示例数据
df = pd.DataFrame({'A': [1, 3, 9, 5, 2, 1, 1],
                   'B': [4, 5, 5, 7, 9, 8, 6]})

# 自定义日期列表,长度需与数据行数一致
Data = ['2023-01', '2023-02', '2023-03', '2023-04', '2023-05', '2023-06', '2023-07']

fig, ax = plt.subplots()

df.plot(marker='o', color=colors, ax=ax)

# 绘制多层阴影线条增强赛博朋克效果
n_shades = 10
diff_linewidth = 1.05
alpha_value = 0.3 / n_shades

for n in range(1, n_shades+1):
    df.plot(marker='o',
            linewidth=2+(diff_linewidth*n),
            alpha=alpha_value,
            legend=False,
            ax=ax,
            color=colors)

# 填充线条下方区域
for column, color in zip(df, colors):
    ax.fill_between(x=df.index,
                    y1=df[column].values,
                    y2=[0] * len(df),
                    color=color,
                    alpha=0.1)

ax.grid(color='#2A3459')

# 设置X轴刻度为自定义日期
ax.set_xticks(df.index)  # 指定刻度位置为原数据索引
ax.set_xticklabels(Data)  # 设置自定义日期文本
plt.xticks(rotation=45)  # 可选:旋转标签避免拥挤

ax.set_xlim([ax.get_xlim()[0] - 0.2, ax.get_xlim()[1] + 0.2])  # 避免标记被截断
ax.set_ylim(0)

plt.tight_layout()  # 自动调整布局,防止标签被截断
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:25:21