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

如何为Matplotlib图表添加带关键信息的多行文本侧边栏?

给Matplotlib图表添加无间距文本侧边栏

可以用Matplotlib的GridSpec实现主图表与右侧文本栏的无间距布局,同时通过text()方法自定义文本的颜色、字体样式来突出关键信息。以下是修改后的完整代码:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

plt.style.use("custom_style.mplstyle")
fig = plt.figure(figsize=(16, 9), dpi=240)

# 用GridSpec创建1行2列的无间距布局:主图占10份宽度,侧边栏占2份
gs = fig.add_gridspec(1, 2, width_ratios=[10, 2], wspace=0)
ax_main = fig.add_subplot(gs[0])  # 主图表轴
ax_sidebar = fig.add_subplot(gs[1])  # 侧边栏轴

# ---------------------- 原有折线图逻辑 ----------------------
color = "#52cc00" if float(dif) >= 0 else "#cc5240"
ax_main.plot_date(df["time"], df["close"], fmt=color, xdate=False, marker=None, linewidth=3, linestyle="-")

dateFMT = mdates.DateFormatter(r'%I%p')
ax_main.xaxis.set_major_formatter(dateFMT)
chart_name = name if isinstance(chart_name, pd.core.series.Series) else chart_name
plt.title(f"{chart_name}: {close} [{dif}%]")

ax_main.autoscale(tight=True)
# -----------------------------------------------------------

# ---------------------- 配置侧边栏文本 ----------------------
# 隐藏侧边栏的边框、刻度,只保留文本
ax_sidebar.spines[['top', 'right', 'bottom', 'left']].set_visible(False)
ax_sidebar.set_xticks([])
ax_sidebar.set_yticks([])

# 自定义多行文本,可按需修改内容和样式
text_configs = [
    ("当前价格", "#333333", 12, "normal"),
    (f"{close}", color, 16, "bold"),
    ("", "", 10, "normal"),  # 空行分隔
    ("涨跌幅", "#333333", 12, "normal"),
    (f"{dif}%", color, 14, "bold"),
    ("", "", 10, "normal"),
    ("今日最高", "#666666", 12, "normal"),
    (f"{df['high'].max()}", "#cc5240" if float(dif) < 0 else "#52cc00", 13, "semibold"),
    ("今日最低", "#666666", 12, "normal"),
    (f"{df['low'].min()}", "#52cc00" if float(dif) >= 0 else "#cc5240", 13, "semibold"),
]

# 从顶部开始排列文本,用相对坐标适配不同尺寸
y_pos = 0.9
line_spacing = 0.08
for content, text_color, font_size, font_weight in text_configs:
    if content:
        ax_sidebar.text(
            0.1, y_pos, content,
            color=text_color,
            fontsize=font_size,
            fontweight=font_weight,
            transform=ax_sidebar.transAxes
        )
    y_pos -= line_spacing
# -----------------------------------------------------------

plt.show()

核心细节说明:

  • 无间距布局:通过GridSpec的wspace=0参数消除主图与侧边栏的空隙,width_ratios可灵活调整两者的宽度占比。
  • 样式定制:每个文本行可单独设置颜色、字号和字重,比如用涨跌幅对应的颜色突出核心数值,用灰度区分标签与数据。
  • 相对坐标:使用transform=ax_sidebar.transAxes让文本位置基于侧边栏的相对坐标,避免图表尺寸变化时文本错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:06:30