【发布时间】:2021-09-03 15:10:11
【问题描述】:
我是 Python 新手,我一直在使用虚拟数据集来练习 Python。以前我在生成子图、然后绘制频率和比例 % 时遇到了麻烦,但现在我今天已经克服了它们。现在,我正在努力修复一些装饰性的东西,尤其是传说和情节标题。
这是生成整个虚拟数据集的可重现代码:
d = {
'SeniorCitizen': [0,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0] ,
'CollegeDegree': [0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1] ,
'Married': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1] ,
'FulltimeJob': [1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,1] ,
'DistancefromBranch': [7,9,14,20,21,12,22,25,9,9,9,12,13,14,16,25,27,4,14,14,20,19,15,23,2] ,
'ReversedPayment': [0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,1,0] }
CarWash = pd.DataFrame(data = d)
categoricals = ['SeniorCitizen','CollegeDegree','Married','FulltimeJob','ReversedPayment']
numerical = ['DistancefromBranch']
CarWash[categoricals] = CarWash[categoricals].astype('category')
下面是我尝试生成频率和比例%,并列比较:
plt.suptitle("Distribution of target variable across the categorical variables - frequencies # and proportions %")
nrow = 1
ncol = len(categoricals[:-1])
figure, axes = plt.subplots(nrow,ncol, figsize = (40,10))
for i,ax in zip(categoricals[:-1],axes.flatten()):
# plots frequencies
CarWash.groupby([i,'ReversedPayment']).size().reset_index().pivot(index = i,columns = 'ReversedPayment').plot(kind = 'bar', stacked = True, ax = ax, sharey=True)
ax.tick_params(axis='both', labelsize = 25, labelrotation = 0)
ax.set_title(i,fontsize = 30)
ax.set_xlabel("")
#ax.get_legend().remove()
# labels data
for p in ax.patches:
x_adjust = 0.25
value = p.get_height()
X = p.get_x() + x_adjust
Y = p.get_y() + p.get_height()/2
XY = (X,Y)
if value != 0:
ax.annotate(int(value),XY,fontsize = 25)
nrow = 1
ncol = len(categoricals[:-1])
figure, axes = plt.subplots(nrow,ncol, figsize = (40,10))
for i,ax in zip(categoricals[:-1],axes.flatten()):
# plots proportions
CarWash.groupby([i,'ReversedPayment']).size().reset_index().pivot(index = i, columns = 'ReversedPayment').apply(lambda x: x/x.sum(),axis=1).plot(kind = 'bar', stacked = True, ax = ax)
ax.tick_params(axis='both', labelsize = 25, labelrotation = 0)
ax.set_title(i,fontsize = 30)
ax.set_xlabel("")
#ax.get_legend().remove()
# labels data
for p in ax.patches:
x_adjust = 0.25/3
value = p.get_height()
X = p.get_x() + x_adjust
Y = p.get_y() + p.get_height()/2
XY = (X,Y)
if value != 0:
ax.annotate(str(round(value*100,1)) + "%",XY,fontsize = 25)
下面是我的输出:
所以,我对化妆品编码的问题是:
-
标题:我尝试使用
plt.suptitle()引入一个主标题,但这并没有达到预期效果(我看不到任何输出)。还尝试了其他方法,但其他所有方法都引发了错误。 -
Legend:Legend 看起来很难看,我不需要它们用于所有子情节。我正在尝试为所有子图只获取一个图例,这将非常棒并且可以节省空间。我尝试了类似
plt.legend([CarWash[i],CarWash['ReversedPayment']], ['Blue', 'Orange'])的方法,但没有成功。
欢迎和非常感谢任何 cmets / 建议。谢谢。
【问题讨论】:
-
try figure.suptitle("目标变量在分类变量中的分布-频率#和比例%",fontsize=20)
标签: python matplotlib