【问题标题】:Is there a way to set the plotting global properties specifically for just one figure in matplotlib?有没有办法专门为 matplotlib 中的一个图形设置绘图全局属性?
【发布时间】:2021-10-20 09:51:39
【问题描述】:

我确实意识到这里已经解决了这个问题(例如,.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 中的其他绘图?

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

【问题讨论】:

    标签: python matplotlib data-visualization


    【解决方案1】:

    如果只更改一个图形的属性,您可以只在图形或轴实例上使用相关方法,而不是使用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')
    

    【讨论】:

    • 使用轴应用对我不起作用?也许是由于我的编码限制。包括我的完整工作代码。你能帮我解决这个问题吗?
    • 在你的代码中你没有定义ax是什么......所以你可以在使用.set_label_position().set_ticks_position()之前在某个地方使用ax=plt.gca()
    • 而不是 plt.rcParams ,我应该使用 .set_label_position().set_ticks_position()ax 对吗?
    • 是的,完全正确。一个建议是在开始使用 plt.subplots 绘制之前创建 Figure 和 Axes 实例,就像我在最小示例中所做的那样,然后使用相关的 object-oriented methods 绘制数据并设置轴标签等,所以你可以确定你的所有方法都在正确的图形和轴实例上工作。
    • 好的,谢谢@tmdavison 的建议
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    相关资源
    最近更新 更多