1、 seaborn
作用:更高效地绘图
pip3 install seaborn
import seaborn as sns
单变量:直方图或核密度曲线 双变量:散点图、二维直方图、
主要函数:distplot()与joinplot()函数
1.1 单变量绘图
API
import seaborn as sns
import numpy as np
np.random.seed(0)
arr = np.random.rand(100)
sns.distplot(arr,bins=10,hist=True,kde=True,rug=True)
1.2 双变量绘图
散点图-kind = ‘scatter’
import pandas as pd
df = pd.DataFrame({'x':np.random.randn(500),'y':np.random.randn(500)})
df.head()
sns.joinplot('x','y',data = df)
核密度估计曲形-kind = ‘kde’
sns.joinplot('x','y',data = df,kind = 'kde')
颜色越深,表示数据越密集
二维直方图-kind = ‘hex’
sns.joinplot('x','y',data = df,kind = 'hex')
多个成对的双变量分布
dataset = sns.load_dataset('iris')
sns.pairplot(dataset)
1.3 总结
- 绘制单变量分布图像:seaborn.distplot()
- 绘制双变量分布图像:seaborn.jointplot()
- 绘制成对的双变量分布图像:seaborn.pairplot()
2、分类数据绘图
2.1 类别散点图
data = sns.load_dataset('tips')
data.load()
sns.stripplot(x='day',y='total_bill',data=data)
sns.stripplot(x='day',y='total_bill',data=data,hue='time')
sns.stripplot(x='day',y='total_bill',data=data,hue='time',jitter=True)
sns.swarmplot('day','total_bill',data=data)
2.2 类别内的数据发布
箱线图、小提琴图 小提琴图结合了箱线图和密度图的特征,主要用来显示数据的分布 箱线图API
seaborn.boxplot(x=None,y=None,hue=None,data=None,orient=None,color=None,saturation=0.9)
sns.boxplot('day','total_bill',data=data)
小提琴图
seaborn.violinplot(x=None,y=None,hue=None,data=None)
sns.violinplot('day','total_bill',data=data)
条形图sns.barplot与点图sns.pointplot
sns.barplot(x='day',y='total_bill',data=tips)
sns.pointplot(x='day',y='total_bill',data=tips)
3、案例:NBA球员数据分析
NBA数据
3.1获取数据且初识数据
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = pd.read_csv('F:/人工智能/nba_2017_nba_players_with_salary.csv')
data.head()
data.shape
data.describe()
3.2 热力图
data_cor = data.loc[:,['RPM','AGE','SALARY_MILLIONS','ORB','DRB','TRB','AST','STL','BLK','TOV','PF','POINTS','GP','MPG','ORPM','DRPM']]
data_cor.head()
corr = data_cor.corr()
corr.head()
plt.figure(figsize=(20,8),dpi=100)
sns.heatmap(corr,square=True,linewidths=0.1,annot=True)
3.3数据排名分析
data.loc[:,['PLAYER','RPM','AGE']].sort_values(by='RPM',ascending=False).head()
data.loc[:,['PLAYER','RPM','AGE','SALARY_MILLIONS']].sort_values(by='SALARY_MILLIONS',ascending=False).head()
3.4seaborn常用的三个数据可视化方法
3.4.1单变量
sns.set_style('darkgrid')
plt.figure(figsize=(10,10))
plt.subplot(3,1,1)
sns.distplot(data['SALARY_MILLIONS'])
plt.ylabel('salary')
plt.subplot(3,1,2)
sns.distplot(data['RPM'])
plt.ylabel('RPM')
plt.subplot(3,1,3)
sns.distplot(data['AGE'])
plt.ylabel('AGE')
3.4.2双变量-散点图
sns.jointplot(data.AGE,data.SALARY_MILLIONS,kind='hex')
3.4.3多变量
multi_data = data.loc[:,['RPM','SALARY_MILLIONS','AGE','POINTS']]
multi_data.head()
sns.pairplot(multi_data)
3.5 衍生变量的一些可视化实践-以年龄为例
自定义了一个年龄分层
def age_cut(df):
if df.AGE <=24:
return 'young'
elif df.AGE >=30:
return 'old'
else:
return 'best'
data['age_cut'] = data.apply(lambda x:age_cut(x),axis=1)
data.head()
分层散点图
data['cut'] = 1
data.loc[data.age_cut == 'best'].SALARY_MILLIONS.head()
sns.set_style('darkgrid')
plt.figure(figsize=(10,10),dpi=100)
plt.title('RPM and SALARY')
x1 = data.loc[data.age_cut == 'old'].SALARY_MILLIONS
y1 = data.loc[data.age_cut == 'old'].RPM
plt.plot(x1,y1,"^")
x2 = data.loc[data.age_cut == 'best'].SALARY_MILLIONS
y2 = data.loc[data.age_cut == 'best'].RPM
plt.plot(x2,y2,"^")
x3 = data.loc[data.age_cut == 'young'].SALARY_MILLIONS
y3 = data.loc[data.age_cut == 'young'].RPM
plt.plot(x3,y3,".")
成对双变量绘图pairplot
dat2 = data.loc[:,['RPM','POINTS','TRB','AST','STL','BLK','age_cut']]
sns.pairplot(dat2,hue='age_cut')
3.6 球队数据分析
查看不同类别下的情况,求均值,最值等—agg聚合函数 排名sort_values
data.groupby(by='age_cut').agg({"SALARY_MILLIONS":np.mean})
data_team = data.groupby(by='TEAM').agg({"SALARY_MILLIONS":np.mean})
data_team.sort_values(by='SALARY_MILLIONS',ascending=False).head(10)
data_rpm = data.groupby(by=['TEAM','age_cut']).agg({"SALARY_MILLIONS":np.mean,"RPM":np.mean,"PLAYER":np.size})
data_rpm.sort_values(by=['PLAYER','RPM'],ascending=False).head()
用图像来展示各球队的情况
sns.set_style('whitegrid')
plt.figure(figsize=(20,10))
data_team2 = data[data.TEAM.isin(['GS','CLE','SA','LAC','OKC','UTAH','CHA','TOR','NO','BOS'])]
plt.subplot(3,1,1)
sns.boxplot(x='TEAM',y='SALARY_MILLIONS',data =data_team2)
plt.subplot(3,1,2)
sns.boxplot(x='TEAM',y='AGE',data =data_team2)
plt.subplot(3,1,3)
sns.boxplot(x='TEAM',y='MPG',data =data_team2)
sns.set_style('whitegrid')
plt.figure(figsize=(20,10))
plt.subplot(3,1,1)
sns.violinplot(x='TEAM',y='3P%',data =data_team2)
plt.subplot(3,1,2)
sns.violinplot(x='TEAM',y='POINTS',data =data_team2)
plt.subplot(3,1,3)
sns.violinplot(x='TEAM',y='eFG%',data =data_team2)
4、案例:北京租房数据统计分析
需求: 链家北京租房数据
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
file_data = pd.read_csv('F:/淘宝-人工智能-课件/链家北京租房数据.csv')
file_data
file_data.shape
file_data.info()
file_data.describe()
数据基本处理
4.1,重复值和空值处理
file_data = file_data.drop_duplicates()
file_data.shape
file_data = file_data.dropna()
file_data.shape
4.2 数据类型转换
想把”面积列“转换成float类型 户型列的表达,有“几房间几厅”的表达,把该列统一为“几室几厅”的表达
file_data['面积(㎡)'].values
file_data['面积(㎡)'].values[0][:-2]
data_new = np.array([])
data_area = file_data['面积(㎡)'].values
for i in data_area:
data_new = np.append(data_new,np.array(i[:-2]))
data_new
data_new = data_new.astype(np.float64)
data_new
file_data.loc[:,'面积(㎡)'] = data_new
file_data.head()
house_data = file_data['户型']
temp_list=[]
for i in house_data:
new_info = i.replace('房间','室')
temp_list.append(new_info)
file_data.loc[:,"户型"] = temp_list
file_data
调整后的数据
p0655
|