【发布时间】: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