如何使用变量表示plt.title中的10个列名

2024-10-01 11:26:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我从col1到col10有10列,我把它们放在一个变量col中。我想为每列绘制一个单独的条形图,所以会生成10个条形图

我的问题是如何在plt.title中表示这10个列名

例如,共10个标题应为INS%按列1、INS%按列2、INS%按列3、…、INS%按列10

非常感谢你

col = ['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10']

for col in num_columns:

     totals = df.groupby(col)['INS'].count() 
     pos_counts = df.groupby(col)['INS'].sum()


     pos_pcts = pos_counts / totals
     neg_pcts = 1 - pos_pcts


     plt.figure(figsize=(10,7))
     plt.barh(pos_pcts.index, pos_pcts.values, label='likelihood of buying INS')
     plt.barh(neg_pcts.index, neg_pcts.values, label='likelihood of not buying INS',
     left=pos_pcts) # neg_pcts bars have their leftmost point where the pos_pcts end
     plt.title(f'INS % by col')
     plt.legend()
     plt.show()

Tags: posdftitlepltcolcol1条形图groupby