如何在 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()
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
解释
导入 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 是创建信息丰富且视觉吸引力的累积直方图的绝佳工具。