seaborn绘图
导入相关库
import numpy as np
import pandas as pd
import os
os.chdir(r'/Python/数据分析')
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(12,9))
plt.rcParams['font.sans-serif']=['Songti SC']#中文显示
plt.rcParams['axes.unicode_minus']=False#显示正负号
sns.set(style='darkgrid',context='notebook',font_scale=1.5)#font_scale=1.5坐标轴的刻度大小
# 忽略告警信息
import warnings
warnings.filterwarnings("ignore")
sns.set(style,context,palette)
style
——主题样式 (darkgrid
(灰白背景+网格) whitegrid
(白白背景+灰网格) dark white ticks
带坐标轴刻度)
context
——可以理解为设置输出图片元素的大小尺寸paper
,notebook
, talk
, and poster
(元素缩放)
palette
——调色板 deep, muted, pastel, bright, dark, colorblind
一般可以用默认值
sns.barplot条形图/柱状图
导入数据
air_data=pd.read_csv(r'./data/air_data.csv')
data=pd.DataFrame(air_data['FFP_TIER'].value_counts())#value_counts()计数
data=data.reset_index()
data.columns=['Membership_level','Number_of_members']#设置列名
data.columns=['会员卡等级','用户数量']#修改列名
plt.style.use('seaborn')
# 支持中文显示
plt.rcParams['font.sans-serif'] = ['Songti SC']
plt.rcParams['axes.unicode_minus'] = False
plt.bar(x=data['会员卡等级'],height =data['用户数量'],color = 'goldenrod')
plt.ylabel('用户数量',fontsize=12)
plt.xticks([4,5,6],['等级4','等级5','等级6'])#打标签
plt.title('不同会员卡等级的用户数量',fontsize =15)
# 调用seaborn第二种方法
import seaborn as sns
sns.set() # 设置背景
# 支持中文显示
plt.rcParams['font.sans-serif'] = ['Songti SC']
plt.rcParams['axes.unicode_minus'] = False
plt.bar(x=data['会员卡等级'],height =data['用户数量'],color = 'steelblue')
plt.ylabel('业务数量',fontsize=12)
plt.xticks([4,5,6],['等级4','等级5','等级6'])#打标签
plt.title('不同会员卡等级的用户数量',fontsize =15)
plt.show()
分类柱状图hue
data_1 = pd.pivot_table(data = air_data,index =['FFP_TIER','GENDER'],values ='MEMBER_NO',aggfunc='count')
data_1.reset_index(inplace = True)
dengji =['等级4','等级5','等级6']
sns.barplot(x = 'FFP_TIER',y = 'MEMBER_NO',hue='GENDER',data=data_1,color='blue',palette="husl",
orient ='vertical')
plt.ylabel('会员人数')
plt.xlabel('')
plt.xticks(np.arange(3),dengji)
plt.title('不同性别不同会员卡等级的用户数量',fontsize = 15,pad=20)
plt.legend(loc='upper right',ncol=1, frameon=False, #是否要边框
fontsize=12)
sns.histplot直方图
Age_male=air_data.AGE[air_data.GENDER=='男']
Age_female=air_data.AGE[air_data.GENDER=='女']
sns.set(style='darkgrid',context='notebook',font_scale=1.3) # 设置背景
# 支持中文显示
plt.rcParams['font.sans-serif'] = ['Songti SC']
plt.rcParams['axes.unicode_minus'] = False
sns.histplot(Age_male, bins = 30,kde = True, label = '男性年龄分布图')
plt.title('年龄分布图')
# 显示图例
plt.legend()
核密度图sns.distplot
sns.set(style='darkgrid',context='notebook',font_scale=1.2) # 设置背景
# 支持中文显示
plt.rcParams['font.sans-serif'] = ['Songti SC']
#plt.figure(figsize=(16,9))
sns.distplot(Age_Male, hist=False, kde = True, kde_kws = {'color':'steelblue'}, norm_hist=True, label = '男性年龄分布图')
sns.distplot(Age_Female, hist=False, kde = True, kde_kws = {'color':'red'}, norm_hist=True, label = '女性年龄分布图')
plt.title('年龄分布图')
# 显示图例
plt.legend()
sns.lineplot折线图
ax=sns.lineplot()
start,end=ax.get_xlim()
ax.set_xticks(np.arange(start,end,100))
air_data['FFP_DATE']=pd.to_datetime(air_data['FFP_DATE'],format='%Y/%m/%d',errors='coerce')
data=air_data.groupby(air_data['FFP_DATE'].dt.year).sum()
data=data[['FLIGHT_COUNT','SEG_KM_SUM']]
data=data.reset_index()
plt.figure(figsize=(16,9))
sns.lineplot(data=data,x='FFP_DATE',y='FLIGHT_COUNT',lw=2,color='red')
plt.ylabel('flight numbers')
plt.xlabel('year')
sns.lmplot回归图
sns.lmplot(data=data,x='FLIGHT_COUNT',y='SEG)_KM_SUM',legend_out=False,markers='o',fit_reg=True,aspect=1.3,height=8,scatter_kws={'s':20,'facecolor':'red'})
plt.title('The relationship between flights and mileage')
sns.scatterplot散点图
sns.scatterplot(data=air_data,x='FLIGHT_COUNT',y='SEG_KM_SUM',color='coral',marker='*',s=50)
plt.title('The relationship between number of flights and mileage')
plt.xlabel('The number of flights')
plt.ylabel('mileage')
分类散点图
颜色不同hue
plt.figure(figsize=(12,9))
sns.scatterplot(x = 'FLIGHT_COUNT',y = 'SEG_KM_SUM',data = air_data,hue='GENDER',
color="coral", marker='o',s=20)
plt.xlabel('飞行次数')
plt.ylabel('总飞行公里数')
plt.title('不同性别的飞行次数和总飞行公里数关系图')
形状不同
plt.figure(figsize=(12,9))
sns.scatterplot(data=air_data,x='FLIGHT_COUNT',y='SEG_KM_SUM',marker='*',s=100,style='GENDER')#style='GENDER'形状不同
plt.title('The relationship between number of flights and mileage')
plt.xlabel('The number of flights')
plt.ylabel('mileage')
sns.boxplot箱线图
画箱线图不能有缺失
air_data.dropna(subset='AGE',inplace=True)
sns.boxplot(dat=air_data,y='AGE',showmeans=True,color='steelblue',width=0.3,linewidth=2,
flierprops={'marker':'o','markerfacecolor':'red','markersize':5},
meanprops={'marker':'D','maekerfacecolor':'darkred','markersize':7},
medianprops={'linestyle':'--','color':'orange'})
plt.xlabel('')
plt.ylabel('age')
分类变量箱线图
sns.boxplot(x= 'GENDER', y = 'AGE', data = air_data,
showmeans=True,color = 'steelblue',width =0.3, linewidth=2,
flierprops = {'marker':'o','markerfacecolor':'red', 'markersize':3},
meanprops = {'marker':'D','markerfacecolor':'indianred', 'markersize':4},
medianprops = {'linestyle':'--','color':'orange'})
# 更改x轴和y轴标签
plt.xlabel('')
plt.xticks(fontsize=12)# 旋转45度
plt.ylabel('年龄')# 添加标题
plt.title('不同性别下的年龄箱线图')
sns.countplot计数图
# 绘制不同区域订单数量
plt.figure(figsize=(4,3))
sns.countplot(x ='FFP_TIER',data = air_data)
plt.rcParams['font.sans-serif'] = ['Songti SC']
plt.ylabel('用户数量')
plt.xlabel('会员卡级别')
plt.title('不同会员卡级别下的用户数量')
分组计数hue
sns.set(palette='colorblind')
# 以订单数据为例
sns.set(style='darkgrid',context='notebook',font_scale=1.0,palette='colorblind')
# 支持中文显示
sns.countplot(x ='FFP_TIER',data = air_data,hue ='GENDER')
plt.rcParams['font.sans-serif'] = ['Songti SC']
plt.ylabel('用户数量')
plt.xlabel('会员卡级别')
plt.title('不同会员卡级别下的男女用户数量')
多图
一句命令同时画多个变量的直方图
train_data[['shop_id','item_id','item_price','item_cnt_day']].hist(bins=150,figsize=(9,7),grid=True)
1行2列的图
fig1,ax=plt.subplots(1,2,figsize=(10,5),dpi=100)
train_data.item_price.plot(ax=ax[0])
train_data.item_cnt_day.plot(ax=ax[1])
1行3列的图
fig,azx=plt.subplot(ncols=3,figsize=(20,4))
fig.suptitle('Category Statistics')
sns.histplot(ax=ax[0],data=sales_train,x='item_category_id',bins=item_catogories.shape[0],
binrange=(min(item_categories['item_category_id']),max(item_categories['item_category_id'])))
sns.histplot(ax=ax[1],data=sales_train,x='item_category_id',weights=sales_train['item_price'],bins=item_categories.shape[0],
binrange=(min(item_categories['item_category_id']),max(item_categories['item_category_id'])))
sns.barplot(ax=ax[2],data=sales_train,x='item_category_id',y='item_price',palette='mako')#palette='mako'颜色
ax[1].set_ylabel('Total price')
ax[2].set_ylabel('Avg Price')
ax[2].set_xticks(ticks=[0,20,40,60,80])
2行3列的图
plt.subplots(2,3,figsize=(20,10))
ax[0][0]
ax[0][1]
ax[0][2]
ax[1][0]
ax[1][1]
ax[1][2]
2行2列的图
fig,((ax0,ax1),(ax2,ax3))=plt.subplots(2,2,figsize=(15,10),sharex=False)
ax0.scatter(train['family'],train['sales'])
ax1.scatter(train['dcoilwtico'],train['sales'],color='green')
ax2.scatter(train['cluster'],train['sales'],color='blue')
ax3.scatter(train['store_nbr'],train['sales'],color='red')
ax0.set_xlabel('family',fontsize=17)
ax1.set_xlabel('oil price',fontsize=17)
ax2.set_xlabel('cluster',fontsize=17)
ax3.set_xlabel('store number',fontsize=17)
ax0.set_ylabel('sales',fontsize=17)
ax1.set_ylabel('')
ax2.set_ylabel('')
ax3.set_ylabel('')