Skip to main content
 首页 » 编程设计

python之有没有办法使用一个命令设置图形中所有文本的格式

2024年11月01日8lhb25

当我在 matplotlib 中制作图形时,我通常希望将所有文本匹配格式(例如轴标签、图例、轴刻度)设置为粗体和大小 20。有没有一种方法可以在一个命令中执行此操作而不是而不是必须在每个文本实例上指定它?

我正在寻找的是可以改变这一点的东西:

    fig, ax = plt.figure() 
    ax.set_title("Title", fontsize = 20, fontweight = 'bold') 
    plt.xlabel("xlabel", fontsize = 20, fontweight = 'bold') 
    plt.ylabel("ylabel", fontsize = 20, fontweight = 'bold') 
    plt.xticks(fontsize = 20, fontweight = 'bold') 
    plt.yticks(fontsize = 20, fontweight = 'bold') 

在不影响输出的情况下更像这样:

    fig, ax = plt.figure() 
    alltextformat = fontsize = 20, fontweight = 'bold' 
    ax.set_title("Title") 
    plt.xlabel("xlabel") 
    plt.ylabel("ylabel") 
    plt.xticks() 
    plt.yticks() 

请您参考如下方法:

是的,您想更改您的 rcParams .一种方式是这样的:

import matplotlib.pyplot as plt 
import numpy as np 
 
x = np.arange(-10, 10) 
y = x ** 2 
with plt.rc_context(rc={'font.size': 20, 'font.weight': 'bold'}): 
    plt.plot(x, y) 
    plt.show() 

或整个 session

plt.rc('font', size=20, weight='bold') 
plt.plot(x, y) 
plt.show() 

编辑

另请参阅:https://matplotlib.org/3.1.1/tutorials/introductory/customizing.html