天天看點

使用 Python 進行資料可視化之Seaborn

上一篇文章我們介紹了 Matplotlib,接下來讓我們繼續我們清單的第二個庫——Seaborn。Seaborn 是一個建立在 Matplotlib 之上的進階接口。 它提供了漂亮的設計風格和調色闆來制作更具吸引力的圖形。

安裝

要安裝 seaborn,請在終端中輸入以下指令。

pip install seaborn      
使用 Python 進行資料可視化之Seaborn

Seaborn 建立在 Matplotlib 之上,是以它也可以與 Matplotlib 一起使用。一起使用 Matplotlib 和 Seaborn 是一個非常簡單的過程。我們隻需要像之前一樣調用 Seaborn Plotting 函數,然後就可以使用 Matplotlib 的自定義函數了。

注意: Seaborn 加載了提示、虹膜等資料集,但在本教程中,我們将使用 Pandas 加載這些資料集。

例子:

# 導包
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 讀取資料庫
data = pd.read_csv("tips.csv")
# 畫線圖
sns.lineplot(x="sex", y="total_bill", data=data)
# 使用 Matplotlib 設定标題
plt.title('Title using Matplotlib Function')
plt.show()      

輸出:

使用 Python 進行資料可視化之Seaborn

散點圖

散點圖是使用scatterplot() 方法繪制的。這類似于 Matplotlib,但需要額外的參數資料。

# 導包
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 讀取資料庫
data = pd.read_csv("tips.csv")
sns.scatterplot(x='day', y='tip', data=data,)
plt.show()      
使用 Python 進行資料可視化之Seaborn

你會發現在使用 Matplotlib 時,如果你想根據sex為這個圖的每個點着色會很困難。 但在散點圖中,它可以在色調參數的幫助下完成。

# 導包
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 讀取資料庫
data = pd.read_csv("tips.csv")
sns.scatterplot(x='day', y='tip', data=data,
    hue='sex')
plt.show()      
使用 Python 進行資料可視化之Seaborn

線圖

Seaborn 中的 Line Plot 使用 lineplot() 方法繪制。 在這種情況下,我們也可以隻傳遞 data 參數。

示例:

# 導包
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 讀取資料庫
data = pd.read_csv("tips.csv")
sns.lineplot(x='day', y='tip', data=data)
plt.show()      

輸出:

使用 Python 進行資料可視化之Seaborn

示例 2:

# 導包
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 讀取資料庫
data = pd.read_csv("tips.csv")
# 僅使用資料屬性
sns.lineplot(data=data.drop(['total_bill'], axis=1))
plt.show()      
使用 Python 進行資料可視化之Seaborn

條形圖

Seaborn 中的條形圖可以使用barplot()方法.

# 導包
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 讀取資料庫
data = pd.read_csv("tips.csv")
sns.barplot(x='day',y='tip', data=data,
    hue='sex')
plt.show()      
使用 Python 進行資料可視化之Seaborn

直方圖

Seaborn 中的直方圖可以使用histplot() 函數繪制。

# 導包
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 讀取資料庫
data = pd.read_csv("tips.csv")
sns.histplot(x='total_bill', data=data, kde=True, hue='sex')
plt.show()      
使用 Python 進行資料可視化之Seaborn

在浏覽完所有這些繪圖後,您一定已經注意到,使用 Seaborn 自定義繪圖比使用 Matplotlib 容易得多。 它也是基于 matplotlib 建構的,那麼我們也可以在使用 Seaborn 時使用 matplotlib 函數。下一節我們繼續談第三個庫——Bokeh