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 Express加载鸢尾花数据集到名为”iris_data”的变量中。
-
使用”go.Figure”方法创建一个新的图表,使用累积直方图。
-
使用”go.Histogram”方法设置直方图的数据,并指定要绘制的变量为鸢尾花数据集中的”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 Graph Objects库。
-
从Plotly Express加载鸢尾花数据集到名为”iris_data”的变量中。
-
使用”go.Figure”方法创建一个新的图,并制作一个水平的累积直方图。
-
使用”go.Histogram”方法设置直方图的数据,并将要绘制的变量指定为鸢尾花数据集中的”sepal_width”列。
-
通过将”cumulative_enabled”设置为True,启用直方图的累积模式。
-
将直方图的方向设置为水平,通过将”orientation”设置为’h’。
-
使用”update_layout”方法向图添加标签和标题,指定标题、x轴标签和y轴标签。
-
使用”show”方法显示结果图。
输出
执行代码后,您将在浏览器中看到以下图表:
结论
总之,在Plotly中创建累积直方图是一个简单的过程。它涉及使用”cumulative_enabled”参数启用直方图的累积模式,并指定要绘制的变量。Plotly提供了各种自定义选项,如设置方向、向图表添加标签和标题以及调整直方图的外观。通过其互动和动态的特性,Plotly是创建信息丰富且具有视觉吸引力的累积直方图的优秀工具。