Python数据可视化-seaborn
詳細介紹可以看seaborn官方API和example galler。
1 set_style( ) set( )
set_style( )是用來設置主題的,Seaborn有五個預設好的主題: darkgrid , whitegrid , dark , white ,和 ticks 默認:darkgrid
importmatplotlib.pyplotasplt
importseabornassns
sns.set_style("whitegrid")
plt.plot(np.arange(10))
plt.show()
set( )通過設置參數可以用來設置背景,調色板等,更加常用。
importseabornassns
importmatplotlib.pyplotasplt
sns.set(style="white",palette="muted",color_codes=True)#set()設置主題,調色板更常用
plt.plot(np.arange(10))
plt.show()
2 distplot( ) kdeplot( )
distplot( )為hist加強版,kdeplot( )為密度曲線圖
importmatplotlib.pyplotasplt
importseabornassns
df_iris=pd.read_csv('../input/iris.csv')
fig,axes=plt.subplots(1,2)
sns.distplot(df_iris['petallength'],ax=axes[0],kde=True,rug=True)#kde密度曲線rug邊際毛毯
sns.kdeplot(df_iris['petallength'],ax=axes[1],shade=True)#shade陰影
plt.show()
importnumpyasnp
importseabornassns
importmatplotlib.pyplotasplt
sns.set(palette="muted",color_codes=True)
rs=np.random.RandomState(10)
d=rs.normal(size=100)
f,axes=plt.subplots(2,2,figsize=(7,7),sharex=True)
sns.distplot(d,kde=False,color="b",ax=axes[0,0])
sns.distplot(d,hist=False,rug=True,color="r",ax=axes[0,1])
sns.distplot(d,hist=False,color="g",kde_kws={"shade":True},ax=axes[1,0])
sns.distplot(d,color="m",ax=axes[1,1])
plt.show()
3 箱型圖boxplot( )
importmatplotlib.pyplotasplt
importseabornassns
df_iris=pd.read_csv('../input/iris.csv')
sns.boxplot(x=df_iris['class'],y=df_iris['sepalwidth'])
plt.show()
plt.rc('font',family='SimHei',size=13)
#fliersize=1將異常點虛化,showmeans=True顯示平均值,order表示按x軸顯示進行排序
sns.boxplot(x='is_overdue',y='gjj_loan_balance',hue='education',hue_order=['HighSchool','Colege','University','Master','other'],data=df,showmeans=True,fliersize=1,order=['0','1-15','15-30','30-45','45+'])
plt.legend(loc='upper right')#圖示靠右顯示
plt.show
4 聯合分布jointplot( )
tips=pd.read_csv('../input/tips.csv')#右上角顯示相關系數
sns.jointplot("total_bill","tip",tips)
plt.show()
tips=pd.read_csv('../input/tips.csv')
sns.jointplot("total_bill","tip",tips,kind='reg')
plt.show()
5 熱點圖heatmap( )
internal_chars = ['full_sq', 'life_sq', 'floor', 'max_floor', 'build_year', 'num_room', 'kitch_sq', 'state', 'price_doc']
corrmat = train[internal_chars].corr()
f, ax = plt.subplots(figsize=(10, 7))
plt.xticks(rotation='90')
sns.heatmap(corrmat, square=True, linewidths=.5, annot=True)
plt.show()
6 散點圖scatter( )
f, ax = plt.subplots(figsize=(10, 7))
plt.scatter(x=train['full_sq'], y=train['price_doc'], c='r')
plt.xlim(0,500)
plt.show()
7.pointplot畫出變量間的關系
grouped_df = train_df.groupby('floor')['price_doc'].aggregate(np.median).reset_index()
plt.figure(figsize=(12,8))
sns.pointplot(grouped_df.floor.values, grouped_df.price_doc.values, alpha=0.8, color=color[2])
plt.ylabel('Median Price', fontsize=12)
plt.xlabel('Floor number', fontsize=12)
plt.xticks(rotation='vertical') plt.show()
8pairplot( )
importseabornassns
importmatplotlib.pyplotasplt
iris=pd.read_csv('../input/iris.csv')
sns.pairplot(iris,vars=["sepalwidth","sepallength"],hue='class',palette="husl")
plt.show()
9 FacetGrid( )
facetGrid可以根據類別特征各種不同組合進行顯示,下面就是根據婚姻與學歷情況進行分成了10組,橫(row)的表示按婚姻分類顯示,豎(col)的表示按學歷分類顯示
grid=sns.FacetGrid(df,row='martial_status',col='education',palette='seismic',size=4) grid.map(plt.scatter,'gjj_loan_balance','max_overduer_days') grid.add_legend() plt.show()
10 barplot( )
f, ax=plt.subplots(figsize=(12,20))
#orient='h'表示是水平展示的,alpha表示顏色的深淺程度
sns.barplot(y=group_df.sub_area.values, x=group_df.price_doc.values,orient='h', alpha=0.8, color='red')
#設置y軸、X軸的坐標名字與字體大小
plt.ylabel('price_doc', fontsize=16)
plt.xlabel('sub_area', fontsize=16)
#設置X軸的各列下標字體是水平的
plt.xticks(rotation='horizontal')
#設置Y軸下標的字體大小
plt.yticks(fontsize=15)
plt.show()
注:如果orient='v'表示成豎直顯示的話,一定要記得y=group_df.sub_area.values, x=group_df.price_doc.values調換一下坐標軸,否則報錯
f, ax=plt.subplots(figsize=(12,20))
sns.barplot(y='area', x='fre',data=df_idcard_city,orient='h', color='red')
plt.ylabel('地域', fontsize=16)
plt.xlabel('頻數', fontsize=16)
plt.xticks(rotation='horizontal')
plt.yticks(fontsize=15)
plt.show()
11.bar圖
import matplotlib.pyplot as plt
import numpy as np
plt.rc('font', family='SimHei', size=13)
num = np.array([13325, 9403, 9227, 8651])
ratio = np.array([0.75, 0.76, 0.72, 0.75])
men = num * ratio
women = num * (1-ratio)
x = ['聊天','支付','團購
優惠券','在線視頻']
width = 0.5
idx = np.arange(len(x))
plt.bar(idx, men, width, color='red', label='男性用戶')
plt.bar(idx, women, width, bottom=men, color='yellow', label='女性用戶') #這一塊可是設置bottom,top,如果是水平放置的,可以設置right或者left。
plt.xlabel('應用類別')
plt.ylabel('男女分布')
plt.xticks(idx+width/2, x, rotation=40)
#bar圖上顯示數字
for a,b in zip(idx,men):
plt.text(a, b+0.05, '%.0f' % b, ha='center', va= 'bottom',fontsize=12)
for a,b,c in zip(idx,women,men):
plt.text(a, b+c+0.5, '%.0f' % b, ha='center', va= 'bottom',fontsize=12)
plt.legend()
plt.show()
12、雙Y軸繪圖
本例主要用dataframe的兩個列進行雙Y軸畫圖
eng_name,chn_name,GDP,rate
a, 中國,100,0.6
b,美國,180,0.3
c,日本,80,0.2
d,瑞典,65,0.15
f,荷蘭,56,0.23
#讀取的時候,講索引列變為chn_name,這樣畫圖時候X軸自動為索引
df=pd.read_csv('b.csv',index_col='chn_name') df.index.name='國家'#這樣x軸的label就變成‘國家了’。
plt.rc('font', family='SimHei', size=13) plt.figure() df['GDP'].plot(kind='bar') plt.ylabel('GDP') plt.title('國家發展情況對比') p = df['rate'] p.plot(color='black',secondary_y=True,style='--o',linewidth=2) #style--表示虛線,-表示實線 plt.ylabel('增長速度')
x=[0,1,2,3,4]#因為x軸是漢字,所以默認對應的數值是從0開始的
for a,b in zip(x,p):
plt.text(a+0.1, b+0.02, '%.2f' % b, ha='center', va= 'bottom',fontsize=12)
education=df.education.value_counts()
df_education=pd.DataFrame({'education':education.index[1:],'fre':education.values[1:]})
df_education.index=df_education.education
plt.figure()
df_education.fre.plot(kind='bar')
plt.ylabel('人數')
plt.xlabel('學歷')
plt.title('學歷分布情況')
plt.show()
13、畫餅狀圖
import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt
#根據value_counts()結果畫餅圖
phone=df.phone_operator.value_counts()
df_phone=pd.DataFrame({'phone_operator':phone.index[1:],'fre':phone.values[1:]})
plt.rc('font', family='SimHei', size=13)
fig = plt.figure()
plt.pie(df_phone.fre,labels=df_phone.phone_operator,autopct='%1.2f%%') #畫餅圖(數據,數據對應的標簽,百分數保留兩位小數點)
plt.title("手機運營商分布")
plt.show()
來源:http://blog.csdn.net/qq_34264472/article/details/53814653
也可以參考:http://seaborn.pydata.org/tutorial/distributions.html
知乎專欄關于seaborn的:https://zhuanlan.zhihu.com/p/27570774
總結
以上是生活随笔為你收集整理的Python数据可视化-seaborn的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CoAP协议
- 下一篇: 怎么创建具有真实纹理的CG场景岩石?