首页 > 解决方案 > 有没有办法专门为 matplotlib 中的一个图形设置绘图全局属性?

问题描述

我确实意识到这里已经解决了这个问题(例如,如何为 matplotlib 中的一个数字设置本地 rcParams 或 rcParams)不过,我希望这个问题有所不同。

我在 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

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

标签: pythonmatplotlibdata-visualization

解决方案


要仅更改一个图形的属性,您可以只在 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')

在此处输入图像描述


推荐阅读