import pandas as pd
import numpy as np
import os
pd.set_option('display.max_columns',None)
pd.set_option('display.max_rows',None)
import matplotlib
import numpy as np
import pandas as pd
from pylab import *
%matplotlib
inline
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
pd.options.display.max_columns = 777
font_ch = mpl.font_manager.FontProperties(fname='/simhei.ttf')
def catgroy_plot(col_list):
def get_col_data(colname):
feaindex, all_index, positive, negative = [], [], [], []
a_dict, b_dict = {}, {}
a = df1[str(colname)].value_counts(dropna=False)
a_sum = a.values.sum()
b = df2[str(colname)].value_counts(dropna=False)
b_sum = b.values.sum()
for index, value in a.items():
a_dict[index] = value / a_sum
all_index.append(index)
for index, value in b.items():
b_dict[index] = value / b_sum
all_index.append(index)
all_index = list(set(all_index))
all_index.sort()
for key in all_index:
if not (key in a_dict):
a_dict[key] = 0
positive.append(a_dict[key])
if not (key in b_dict):
b_dict[key] = 0
negative.append(b_dict[key])
feaindex.append(key)
return feaindex, positive, negative
for i in range(len(col_list)):
colname = col_list[i]
feaindex, positive, negative = get_col_data(colname)
ind = np.arange(len(feaindex)) # the x locations for the groups
width = 0.35 # the width of the bars
if len(feaindex) < 4:
fig, ax = plt.subplots(figsize=(6, 4))
else:
fig, ax = plt.subplots(figsize=(10, 6))
rects1 = ax.bar(ind - width / 2, positive, width, label='positive', alpha=0.5)
rects2 = ax.bar(ind + width / 2, negative, width, label='negative')
ax.set_ylabel('count')
ax.set_title('{} static'.format(colname))
ax.set_xticks(ind)
[label.set_fontproperties(font_ch) for label in ax.get_xticklabels()]
# if len(feaindex) < 10:
if len(feaindex) < 4:
ax.set_xticklabels(feaindex, fontsize=15)
else:
# ax.set_xticklabels(feaindex,rotation=60,fontsize=15)
ax.set_xticklabels(feaindex, rotation=90, fontsize=15)
ax.legend()
fig.tight_layout()
plt.show()
def num_feats_plot(col, df1, df2):
for i in range(len(col)):
colname = col[i]
pdata = df1[~df1[colname].isnull()]
ndata = df2[~df2[colname].isnull()]
pdata[colname] = pdata[colname].astype("float")
ndata[colname] = ndata[colname].astype("float")
plt.figure(figsize=(6, 4), dpi=80)
sns.kdeplot(pdata[colname].values, shade=False, label='positive')
sns.kdeplot(ndata[colname].values, shade=False, label='negative')
plt.title('{}'.format(colname), fontsize=10)
plt.show()
df=pd.read_csv('data.csv')
# col_list = cate_feas+bin_feats
# col_num = num_feas
col_list = [x for x in df.columns.tolist() if x not in(['id','label'])]
df1 = df[df['label']==1]
df2 = df[df['label']==0]
print(len(df1),len(df2))
catgroy_plot(col_list)
matplotlib绘图
于 2024-06-22 17:58:15 首次发布