我有以下代码来生成模型特征重要性的视觉效果。
def plot_featu_imp(ax,df,plot_title='feature_imp'):
feature_imp = df
ax = feature_imp.plot(ax=ax,kind='barh',
x='feature_names',y='importn',color='g',sort_columns=True) #figsize=(12,10),
rects = ax.patches
for rect in rects:
# Get X and Y placement of label from rect.
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
# Number of points between bar and label. Change to your liking.
space = 5
# Vertical alignment for positive values
ha = 'left'
# If value of bar is negative: Place label left of bar
if x_value < 0:
# Invert space to place label to the left
space *= -1
# Horizontally align label at right
ha = 'right'
# Use X value as label and format number with one decimal place
label = "{:.3f}".format(x_value)
# Create annotation
ax.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(space, 0), # Horizontally shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
va='center', # Vertically center label
ha=ha,
fontsize=15,
color='tab:grey')
ax.spines['top'].set_visible(True)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.legend().set_visible(False)
ax.tick_params(top=True, labeltop=True, bottom=False, left=False, right=False, labelleft=True, labelbottom=False,labelsize=20)
ax.set_xlabel('Importance ',fontsize=20)
ax.set_ylabel('Feature names',fontsize=20)
ax.set_title(plot_title,fontsize=25)
ax.title.set_position([0.1,1])
return ax
我想为一系列模型生成此视觉效果。例如。
fig, ax = plt.subplots(2,1, figsize=(20,10), facecolor='w', edgecolor='k')
# plt.tight_layout()
for i in range(2):
df=pd.DataFrame({'feature_names':['a','b','c'],'importn':[0.1,0.3,0.6]})
plot_featu_imp(ax[i],df,'model'+str(i))
plt.show()
现在问题是标题和x标记之间有重叠 我尝试使用set_position设置标题的位置,但是没有用。有什么办法可以在这两者之间建立间隙。
先谢谢了。