目錄
- 默認barplot
- 使用案例
- 修改capsize
- 顯示error bar得值
- annotata error bar
- error bar選取sd
- 設置置信區間(68)
- 設置置信區間(95)
- dataframe aggregate函數使用
- dataframe aggregate 自定義函數
- dataframe aggregate 自定義函數2
- seaborn顯示網格
- seaborn設置刻度
- 使用其他estaimator
默認barplot
import seaborn as snsimport matplotlib.pyplot as plt import numpy as np sns.set_theme(style="whitegrid")df = sns.load_dataset("tips")#默認畫條形圖sns.barplot(x="day",y="total_bill",data=df)plt.show()#計算平均值看是否和條形圖得高度一致print(df.groupby("day").agg({"total_bill":[np.mean]}))print(df.groupby("day").agg({"total_bill":[np.std]}))# 注意這個地方error bar顯示并不是標準差
total_bill meandayThur 17.682742Fri 17.151579Sat 20.441379Sun 21.410000 total_bill stddayThur 7.886170Fri 8.302660Sat 9.480419Sun 8.832122
使用案例
# import librariesimport seaborn as snsimport numpy as npimport matplotlib.pyplot as plt# load datasettips = sns.load_dataset("tips")# Set the figure sizeplt.figure(figsize=(14, 8))# plot a bar chartax = sns.barplot(x="day", y="total_bill", data=tips, estimator=np.mean, ci=85, capsize=.2, color='lightblue')
修改capsize
ax=sns.barplot(x="day",y="total_bill",data=df,capsize=1.0)plt.show()
顯示error bar得值
import seaborn as snsimport matplotlib.pyplot as plt sns.set_theme(style="whitegrid")df = sns.load_dataset("tips")#默認畫條形圖ax=sns.barplot(x="day",y="total_bill",data=df)plt.show()for p in ax.lines: width = p.get_linewidth() xy = p.get_xydata() # 顯示error bar得值 print(xy) print(width) print(p)
[[ 0. 15.85041935] [ 0. 19.64465726]]2.7Line2D(_line0)[[ 1. 13.93096053] [ 1. 21.38463158]]2.7Line2D(_line1)[[ 2. 18.57236207] [ 2. 22.40351437]]2.7Line2D(_line2)[[ 3. 19.66244737] [ 3. 23.50109868]]2.7Line2D(_line3)
annotata error bar
fig, ax = plt.subplots(figsize=(8, 6))sns.barplot(x='day', y='total_bill', data=df, capsize=0.2, ax=ax)# show the meanfor p in ax.patches: h, w, x = p.get_height(), p.get_width(), p.get_x() xy = (x + w / 2., h / 2) text = f'Mean:n{h:0.2f}' ax.annotate(text=text, xy=xy, ha='center', va='center')ax.set(xlabel='day', ylabel='total_bill')plt.show()
error bar選取sd
import seaborn as snsimport matplotlib.pyplot as plt sns.set_theme(style="whitegrid")df = sns.load_dataset("tips")#默認畫條形圖sns.barplot(x="day",y="total_bill",data=df,ci="sd",capsize=1.0)## 注意這個ci參數plt.show()print(df.groupby("day").agg({"total_bill":[np.mean]}))print(df.groupby("day").agg({"total_bill":[np.std]}))
total_bill meandayThur 17.682742Fri 17.151579Sat 20.441379Sun 21.410000 total_bill stddayThur 7.886170Fri 8.302660Sat 9.480419Sun 8.832122
設置置信區間(68)
import seaborn as snsimport matplotlib.pyplot as plt sns.set_theme(style="whitegrid")df = sns.load_dataset("tips")#默認畫條形圖sns.barplot(x="day",y="total_bill",data=df,ci=68,capsize=1.0)## 注意這個ci參數plt.show()
設置置信區間(95)
import seaborn as snsimport matplotlib.pyplot as plt sns.set_theme(style="whitegrid")df = sns.load_dataset("tips")#默認畫條形圖sns.barplot(x="day",y="total_bill",data=df,ci=95)plt.show()#計算平均值看是否和條形圖得高度一致print(df.groupby("day").agg({"total_bill":[np.mean]}))
total_bill meandayThur 17.682742Fri 17.151579Sat 20.441379Sun 21.410000
dataframe aggregate函數使用
#計算平均值看是否和條形圖得高度一致df = sns.load_dataset("tips")print("="*20)print(df.groupby("day").agg({"total_bill":[np.mean]})) # 分組求均值print("="*20)print(df.groupby("day").agg({"total_bill":[np.std]})) # 分組求標準差print("="*20)print(df.groupby("day").agg({"total_bill":"nunique"})) # 這里統計得是不同得數目print("="*20)print(df.groupby("day").agg({"total_bill":"count"})) # 這里統計得是每個分組樣本得數量print("="*20)print(df["day"].value_counts())print("="*20)
==================== total_bill meandayThur 17.682742Fri 17.151579Sat 20.441379Sun 21.410000==================== total_bill stddayThur 7.886170Fri 8.302660Sat 9.480419Sun 8.832122==================== total_billdayThur 61Fri 18Sat 85Sun 76==================== total_billdayThur 62Fri 19Sat 87Sun 76====================Sat 87Sun 76Thur 62Fri 19Name: day, dtype: int64====================
dataframe aggregate 自定義函數
import numpy as npimport pandas as pddf = pd.DataFrame({'Buy/Sell': [1, 0, 1, 1, 0, 1, 0, 0], 'Trader': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']})print(df)def categorize(x): m = x.mean() return 1 if m > 0.5 else 0 if m < 0.5 else np.nanresult = df.groupby(['Trader'])['Buy/Sell'].agg([categorize, 'sum', 'count'])result = result.rename(columns={'categorize' : 'Buy/Sell'})result
Buy/Sell Trader0 1 A1 0 A2 1 B3 1 B4 0 B5 1 C6 0 C7 0 C
dataframe aggregate 自定義函數2
df = sns.load_dataset("tips")#默認畫條形圖def custom1(x): m = x.mean() s = x.std() n = x.count()# 統計個數 #print(n) return m+1.96*s/np.sqrt(n)def custom2(x): m = x.mean() s = x.std() n = x.count()# 統計個數 #print(n) return m+s/np.sqrt(n)sns.barplot(x="day",y="total_bill",data=df,ci=95)plt.show()print(df.groupby("day").agg({"total_bill":[np.std,custom1]})) # 分組求標準差sns.barplot(x="day",y="total_bill",data=df,ci=68)plt.show()print(df.groupby("day").agg({"total_bill":[np.std,custom2]})) #
?[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-pkCx72ui-1658379974318)(output_24_0.png)]
total_bill std custom1dayThur 7.886170 19.645769Fri 8.302660 20.884910Sat 9.480419 22.433538Sun 8.832122 23.395703
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-GFyIePmW-1658379974318)(output_24_2.png)]
total_bill std custom2dayThur 7.886170 18.684287Fri 8.302660 19.056340Sat 9.480419 21.457787Sun 8.832122 22.423114
seaborn顯示網格
ax=sns.barplot(x="day",y="total_bill",data=df,ci=95)ax.yaxis.grid(True) # Hide the horizontal gridlinesax.xaxis.grid(True) # Show the vertical gridlines
seaborn設置刻度
fig, ax = plt.subplots(figsize=(10, 8))sns.barplot(x="day",y="total_bill",data=df,ci=95,ax=ax)ax.set_yticks([i for i in range(30)])ax.yaxis.grid(True) # Hide the horizontal gridlines
使用其他estaimator
#estimator 指定條形圖高度使用相加得和sns.barplot(x="day",y="total_bill",data=df,estimator=np.sum)plt.show()#計算想加和看是否和條形圖得高度一致print(df.groupby("day").agg({"total_bill":[np.sum]}))''' total_bill sumdayFri 325.88Sat 1778.40Sun 1627.16Thur 1096.33'''
到此這篇關于Python seaborn barplot畫圖案例得內容就介紹到這了,更多相關Python seaborn barplot 內容請搜索之家以前得內容或繼續瀏覽下面得相關內容希望大家以后多多支持之家!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。