如何在 Plotly 中建立累積直方圖?
累積直方圖是一種直方圖,它顯示資料集的累積分佈函式 (CDF)。CDF 表示資料集中的隨機觀測值小於或等於某個值的機率。當您想要比較兩個或多個數據集的分佈或想要視覺化低於某個閾值的資料點的比例時,累積直方圖很有用。
Plotly 是一個用於建立互動式和出版質量視覺化的 Python 庫。它構建在 D3.js 視覺化庫之上,並提供各種視覺化型別,包括散點圖、條形圖和直方圖。Plotly 還支援互動式功能,如縮放、平移和懸停工具提示。
要在 Plotly 中建立累積直方圖,您首先需要將資料載入到 Pandas DataFrame 中。將資料載入到 DataFrame 後,您可以使用 Plotly Express 建立資料的直方圖。
建立累積直方圖
累積直方圖是一種直方圖,它顯示資料集的累積分佈函式 (CDF)。它不是顯示每個區間內資料點的頻率,而是顯示資料點累積到該區間的頻率。可以透過在 Plotly 中建立直方圖時將 cumulative 引數設定為 True 來建立此類直方圖。
現在讓我們建立一些累積直方圖。請考慮以下示例。
示例 1:垂直累積直方圖
垂直累積直方圖是一種直方圖,其中累積頻率顯示在 y 軸上,變數值顯示在 X 軸上。請考慮以下程式碼。
import plotly.express as px import plotly.graph_objects as go # Load the Iris dataset from Plotly Express iris_data = px.data.iris() # Create a new figure with a cumulative histogram fig = go.Figure( data=[go.Histogram( x=iris_data['sepal_width'], # Use sepal width as the variable cumulative_enabled=True # Enable cumulative mode )] ) # Add labels and titles to the figure fig.update_layout( title='Cumulative Histogram of Sepal Width in Iris Dataset', xaxis_title='Sepal Width', yaxis_title='Cumulative Frequency' ) # Show the figure fig.show()
解釋
匯入 Plotly Express 和 Plotly 圖形物件庫。
將 Plotly Express 中的 Iris 資料集載入到名為“iris_data”的變數中。
使用“go.Figure”方法建立一個帶有累積直方圖的新圖形。
使用“go.Histogram”方法設定直方圖的資料,並將要繪製的變數指定為 Iris 資料集中“sepal_width”列。
透過將“cumulative_enabled”設定為 True 來啟用直方圖的累積模式。
使用“update_layout”方法向圖形新增標籤和標題,指定標題、x 軸標籤和 y 軸標籤。
使用“show”方法顯示生成的圖形。
輸出
在執行程式碼之前,請確保您的系統上安裝了 Plotly。如果沒有,您可以使用 pip 包管理器安裝它。
執行程式碼後,您將在瀏覽器上看到以下圖形:
示例 2:水平累積直方圖
水平累積直方圖是一種直方圖,其中累積頻率顯示在 X 軸上,變數值顯示在 Y 軸上。請考慮以下程式碼。
import plotly.express as px import plotly.graph_objects as go # Load the Iris dataset from Plotly Express iris_data = px.data.iris() # Create a new figure with a horizontal cumulative histogram fig = go.Figure( data=[go.Histogram( y=iris_data['sepal_width'], # Use sepal width as the variable cumulative_enabled=True, # Enable cumulative mode orientation='h' # Set orientation to horizontal )] ) # Add labels and titles to the figure fig.update_layout( title='Horizontal Cumulative Histogram of Sepal Width in Iris Dataset', xaxis_title='Cumulative Frequency', yaxis_title='Sepal Width' ) # Show the figure fig.show()
解釋
匯入 Plotly Express 和 Plotly 圖形物件庫。
將 Plotly Express 中的 Iris 資料集載入到名為“iris_data”的變數中。
使用“go.Figure”方法建立一個帶有水平累積直方圖的新圖形。
使用“go.Histogram”方法設定直方圖的資料,並將要繪製的變數指定為 Iris 資料集中“sepal_width”列。
透過將“cumulative_enabled”設定為 True 來啟用直方圖的累積模式。
透過將“orientation”設定為“h”將直方圖的方向設定為水平方向。
使用“update_layout”方法向圖形新增標籤和標題,指定標題、x 軸標籤和 y 軸標籤。
使用“show”方法顯示生成的圖形。
輸出
執行程式碼後,您將在瀏覽器上看到以下圖形:
結論
總之,在 Plotly 中建立累積直方圖是一個簡單的過程。它涉及使用“cumulative_enabled”引數啟用直方圖的累積模式並指定要繪製的變數。Plotly 提供各種自定義選項,例如設定方向、向圖形新增標籤和標題以及調整直方圖的外觀。憑藉其互動式和動態功能,Plotly 是建立資訊豐富且視覺吸引力的累積直方圖的絕佳工具。