有没有办法专门为 matplotlib 中的一个图形设置绘图全局属性?

Is there a way to set the plotting global properties specifically for just one figure in matplotlib?

我知道这已经在这里解决了(例如,how to set local rcParams or rcParams for one figure in matplotlib)不过,我希望这个问题有所不同。

我在 python 中有一个绘图功能 matplotlib,其中包括 global properties,因此所有新绘图都将更新为 global properties

def catscatter(data,colx,coly,cols,color=['grey','black'],ratio=10,font='Helvetica',save=False,save_name='Default'):
    '''
    This function creates a scatter plot for categorical variables. It's useful to compare two lists with elements in common.
    '''

    df = data.copy()
    # Create a dict to encode the categeories into numbers (sorted)
    colx_codes=dict(zip(df[colx].sort_values().unique(),range(len(df[colx].unique()))))
    coly_codes=dict(zip(df[coly].sort_values(ascending=False).unique(),range(len(df[coly].unique()))))
    
    # Apply the encoding
    df[colx]=df[colx].apply(lambda x: colx_codes[x])
    df[coly]=df[coly].apply(lambda x: coly_codes[x])
    
    
    # Prepare the aspect of the plot
    plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
    plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
    plt.rcParams['font.sans-serif']=font
    
    plt.rcParams['xtick.color']=color[-1]
    plt.rcParams['ytick.color']=color[-1]
    plt.box(False)

    
    # Plot all the lines for the background
    for num in range(len(coly_codes)):
        plt.hlines(num,-1,len(colx_codes),linestyle='dashed',linewidth=2,color=color[num%2],alpha=0.5)
    for num in range(len(colx_codes)):
        plt.vlines(num,-1,len(coly_codes),linestyle='dashed',linewidth=2,color=color[num%2],alpha=0.5)
        
    # Plot the scatter plot with the numbers
    plt.scatter(df[colx],
               df[coly],
               s=df[cols]*ratio,
               zorder=2,
               color=color[-1])
    
    # Change the ticks numbers to categories and limit them
    plt.xticks(ticks=list(colx_codes.values()),labels=colx_codes.keys(),rotation=90)
    plt.yticks(ticks=list(coly_codes.values()),labels=coly_codes.keys())


    # Save if wanted
    if save:
        plt.savefig(save_name+'.png')

下面是我在函数内部使用的属性,

plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True

我希望这些 properties 仅在我调用 catscatter 函数时应用。

有没有办法专门为一个图形设置绘图 global properties,而不影响 jupyter notebook[ 中的其他绘图=35=]?

或者至少有一种好方法可以更改一个绘图函数的属性,然后将它们更改回之前使用的值(不一定是 rcdefaults

要仅更改一个图形的属性,您可以只在 Figure 或 Axes 实例上使用相关方法,而不是使用 rcParams

在这种情况下,您似乎想要将 x 轴标签和刻度设置为出现在图的顶部而不是底部。您可以使用以下方法来实现这一点。

ax.xaxis.set_label_position('top')
ax.xaxis.set_ticks_position('top')

考虑以下最小示例:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_xlabel('label')

ax.xaxis.set_label_position('top')
ax.xaxis.set_ticks_position('top')