首页 > 解决方案 > matplotlib:为所有图形设置单个标题(不是子图)

问题描述

我想给我的代码中的所有数字一个单独的标题#Variable_cycles。数字不是子图,而是单独绘制的。我正在使用 %matplotlib 在单独的窗口中显示绘图。据我所知 plt.rcParams 没有这样的密钥

import matplotlib.pyplot as plt

%matplotlib

plt.figure(1), plt.scatter(x,y,marker='o'),
plt.title("Variable_cycles"),
plt.show

plt.figure(2),
plt.scatter(x,y,marker='*'),
plt.title("Variable_cycles"),
plt.show

标签: pythonmatplotlib

解决方案


我不相信 rcParams 或类似设置中有这样的设置,但如果您为所有图形设置了选项,您可以创建一个简单的辅助函数来创建图形,应用这些设置(例如标题、轴标签、等),并返回图形对象,那么您只需要为每个新图形调用一次该函数。一个简单的例子是:

import matplotlib.pyplot as plt

%matplotlib

def makefigure():
    
    # Create figure and axes
    fig, ax = plt.subplots()
    
    # Set title
    fig.suptitle('Variable cycles')

    # Set axes labels
    ax.set_xlabel('My xlabel')
    ax.set_ylabel('My ylabel')

    # Put any other common settings here...

    return fig, ax

fig1, ax1 = makefigure()
ax1.scatter(x, y, marker='o')           

fig2, ax2 = makefigure()
ax2.scatter(x, y, marker='*')
   

推荐阅读