如何避免图例与标题重叠(在matplotlib绘图中)?

2024-04-26 10:53:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的matplotlib绘图中,图例与标题重叠: Script run in IPython

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as mpatches

color1=[0, 0, 1]
color2=[1, 0, 0]

X, Y = np.meshgrid(range(0, 11), range(0, 6))

Z1 = np.random.random((6, 11))
Z2 = np.random.random((6, 11))

mpl.rcParams['toolbar'] = 'None'

fig = plt.figure(figsize=(9, 8))
fig.canvas.set_window_title('Title')
ax = fig.add_subplot(111, projection='3d')

ax.plot_surface(X, Y, Z1, rstride=1, cstride=1, color=color1, alpha=0.5)
ax.plot_surface(X, Y, Z2, rstride=1, cstride=1, color=color2, alpha=0.5)

plt.xlabel('x')
plt.ylabel('y')

fig.suptitle('Title', fontsize=14, fontweight='bold')

patch1 = plt.Rectangle((0, 0), 1, 1, fc=color1)
patch2 = plt.Rectangle((0, 0), 1, 1, fc=color2)
ax.legend([patch1, patch2],
          [r'Very long description of plot 1 (Source: D:\my data folder\subfolder\another subfolder\filename.xml)',
           r'Description of plot 2'], loc='upper left')

fig.tight_layout()

plt.show()

我怎么能让图例显示在左上角,但在标题之下?在

为什么当我直接从命令窗口调用脚本时,与在IPython(在Spyder中)中运行脚本时,我的绘图看起来会不同(我指的是不同的字体大小和灰色背景,而不是不同的随机数据;-): Script run in command window


Tags: import绘图标题plotmatplotlibasnpfig