如何在 Seaborn 中將圖形樣式更改為深色?
在 Seaborn 中,圖形樣式指的是繪圖的整體視覺外觀和美觀性。Seaborn 提供了幾種內建的圖形樣式,可用於增強視覺化的外觀和感覺。這些圖形樣式會影響各種元素,例如顏色、網格線、背景、字型等。
要在 Seaborn 中設定圖形樣式,我們可以使用sns.set_style()函式。在本文中,我們將瞭解如何在 Seaborn 中將圖形樣式更改為深色。以下是需要遵循的步驟。
安裝 Seaborn 庫
首先,我們必須確保 Seaborn 已安裝在我們的 Python 環境中。我們可以使用pip包管理器透過在終端或命令提示符中執行以下命令來安裝它。
pip install seaborn
匯入必要的庫
接下來,我們必須在 Python 指令碼或 Jupyter Notebook 中匯入所需的庫,例如 Seaborn 和 Matplotlib.pyplot。這些庫提供了建立和自定義繪圖的功能。
import seaborn as sns import matplotlib.pyplot as plt
設定圖形樣式
接下來,我們必須在 Seaborn 中將圖形樣式更改為“dark”,使用 sns.set_style() 函式。此函式允許我們修改 Matplotlib 的預設樣式以匹配所選的 Seaborn 樣式。
sns.set_style("dark")
建立和自定義我們的繪圖
設定圖形樣式後,我們可以繼續使用 Seaborn 和 Matplotlib 建立和自定義我們的繪圖。
示例
在此示例中,sns.scatterplot()使用 Seaborn 建立散點圖。後續行使用 Matplotlib 設定 x 軸標籤、y 軸標籤和標題。最後,plt.show()顯示繪圖。
import seaborn as sns import matplotlib.pyplot as plt sns.set_style("dark") # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Create a scatter plot sns.scatterplot(x=x, y=y) # Set labels and title plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("Scatter Plot") # Display the plot plt.show()
輸出
在輸出中,我們可以觀察到圖形樣式為深色,因為我們透過使用.set_style()函式將其設定為深色。
進一步自定義
我們可以使用各種 Seaborn 函式和 Matplotlib 選項進一步自定義我們的繪圖。例如,我們可以修改調色盤、字型大小、標記樣式等。
以下幾行演示了一些其他自定義。sns.set_palette()將調色盤更改為“dark”。plt.xticks()和plt.yticks()分別設定 x 軸和 y 軸刻度的字型大小。
示例
import seaborn as sns import matplotlib.pyplot as plt sns.set_style("dark") # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Create a scatter plot sns.scatterplot(x=x, y=y) # Set labels and title plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("Scatter Plot") sns.set_palette("Oranges") # Change the color palette plt.xticks(fontsize=12) # Set x-axis tick font size plt.yticks(fontsize=12) # Display the plot plt.show()