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

如何修改Matplotlib代码使控制台生成的图表与Jupyter Notebook效果一致?

解决Matplotlib图表在控制台与Jupyter显示效果不一致的问题

问题场景

以下代码在Jupyter Notebook中配合%matplotlib inline运行时,能生成符合预期的图表,但在控制台运行(注释掉%matplotlib inline)时效果不佳,尝试使用add_axes调整也未得到理想结果:

import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np

fig, ax = plt.subplots(facecolor='lightgrey')

# Define some graph offsets
start_x = 18
start_y = 18
end_x = 24
end_y = 24

# Draw an arrow
ax.annotate('Target',
            xy = (18, 20),
            xytext = (14, 20),
            arrowprops = dict(facecolor ='red', shrink = 0.05, width = 2.5),
            ha = 'center')

# Set the limits of the plot
ax.set_xlim(start_x, end_x)
ax.set_ylim(start_y, end_y)

# Customize the grid
plt.gca().set_aspect('equal', adjustable='box') # Make the grid equal in both dimensions
ax.set_ylim(ax.get_ylim()[::-1])                # Invert the y axis
ax.xaxis.tick_top()                             # Move the X-Axis to the top

# Title
middle_x = 14+(end_x-14)/2
plt.text(middle_x, 18, "THE TITLE" + '\nSubtitle\n 1\n 2\n 3\n 4\n\n', color = 'k', fontsize = 18, ha = 'center')

plt.grid()
plt.show()

解决方案

核心问题是Jupyter的inline后端会自动调整图表布局适配内容,而控制台默认的交互式后端需要手动调整画布尺寸和坐标轴位置,避免元素被裁剪或错位。修改后的代码如下:

import matplotlib.pyplot as plt
import numpy as np

# 手动设置画布尺寸,预留左侧空间放置标题和箭头
fig = plt.figure(figsize=(10, 8), facecolor='lightgrey')
# 调整坐标轴位置,左侧留足空间
ax = fig.add_axes([0.35, 0.1, 0.6, 0.8])  # 参数:[left, bottom, width, height]

# Define some graph offsets
start_x = 18
start_y = 18
end_x = 24
end_y = 24

# Draw an arrow
ax.annotate('Target',
            xy=(18, 20),
            xytext=(14, 20),
            arrowprops=dict(facecolor='red', shrink=0.05, width=2.5),
            ha='center')

# Set the limits of the plot
ax.set_xlim(start_x, end_x)
ax.set_ylim(start_y, end_y)

# Customize the grid
ax.set_aspect('equal', adjustable='box')  # 直接操作ax对象,避免上下文混淆
ax.set_ylim(ax.get_ylim()[::-1])          # 反转y轴
ax.xaxis.tick_top()                       # 将X轴移到顶部

# Title - 改用画布坐标定位,确保在控制台显示正常
middle_x = 14 + (end_x - 14)/2
# 使用fig.text基于画布比例定位,而非坐标轴坐标
fig.text(0.175, 0.5, "THE TITLE" + '\nSubtitle\n 1\n 2\n 3\n 4', 
         color='k', fontsize=18, ha='center', va='center')

ax.grid()
plt.show()

关键改动说明

  • 手动设置画布尺寸:通过figsize=(10,8)定义合适的画布大小,避免内容拥挤。
  • 精确控制坐标轴位置:add_axes([0.35,0.1,0.6,0.8])在左侧预留足够空间放置标题和箭头,避免元素被坐标轴遮挡。
  • 文本定位改用画布坐标:用fig.text替代plt.text,基于整个画布的比例坐标定位标题,确保在不同后端下位置一致。
  • 直接操作目标坐标轴:避免使用plt.gca(),直接对ax对象进行设置,减少上下文切换导致的布局问题。

内容的提问来源于stack exchange,提问作者Brian O'Donnell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:17:12