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

Matplotlib 3D子图尺寸适配求助:解决绘图截断与边距冗余问题

解决3D绘图的截断与边距问题

问题描述

  • 绘图右侧被画布边缘截断
  • 上下边距过宽,需收紧左右边距

解决方案

针对这两个问题,重点修改布局参数和3D视角设置,以下是调整后的完整代码:

数据下载部分(无修改)

# Import the libraries
import numpy as np
import pandas as pd
import pandas_datareader as pdr
import datetime
import matplotlib.pyplot as plt

# Import the data
start = datetime.date(2020, 1, 1)
end = datetime.date.today()

assets = {'DGS3MO': '3m', 'DGS6MO': '6m', 'DGS1': '1y', 'DGS2': '2y', 'DGS3': '3y', 'DGS5': '5y', 'DGS7': '7y', 'DGS10': '10y', 'DGS20': '20y', 'DGS30': '30y'}
df_yields = pdr.DataReader(list(assets.keys()), 'fred', start, end)
df_yields.rename(columns=assets, inplace=True)
df_yields = df_yields.dropna(how='any')

3D绘图调整部分

# Create 3D plot
dates = np.array([x.toordinal() for x in df_yields.index])
maturities = np.array([3/12, 6/12, 1, 2, 3, 5, 7, 10, 20, 30])

X, Y = np.meshgrid(dates, maturities)
Z = df_yields.values.T

# 调整画布尺寸,适配3D图的宽高比
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
ax.set_box_aspect(aspect=(0.9, 0.5, 0.4))

surf = ax.plot_surface(X, Y, Z, rstride=10, cmap='Blues', edgecolor='black', linewidth=0.5)

ax.set_xlabel('Date')
ax.set_ylabel('Maturity (Y)')
ax.set_zlabel('Yield (%)')

years = np.arange(start.year, end.year + 1)
selected_years = np.linspace(start.year, end.year, 5, dtype=int)
ax.set_xticks([datetime.date(year, 1, 1).toordinal() for year in selected_years])
ax.set_xticklabels(selected_years)
ax.xaxis.labelpad = 5
ax.zaxis.labelpad = -1

# 修正subplots_adjust参数,避免右侧截断并收紧边距
plt.subplots_adjust(left=0.02, right=0.98, top=0.9, bottom=0.1)

# 调整3D视角,确保图形完整显示在画布内
ax.view_init(elev=30, azim=-60)

plt.show()

关键修改说明

  • 修正subplots_adjust参数:原代码中right=100是错误取值(该参数范围为0-1,代表画布比例),调整为right=0.98可避免右侧截断;同时缩小left、top、bottom的数值,收紧整体边距。
  • 调整画布尺寸:将figsize从(10,10)改为(12,8),适配3D图的宽高比例,减少上下方向的冗余空间。
  • 设置3D视角:通过ax.view_init()调整俯仰角和方位角,让图形整体在画布内完整显示,避免视角导致的区域截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 01:27:07