📜  plotly facet_grid python (1)

📅  最后修改于: 2023-12-03 15:03:47.405000             🧑  作者: Mango

使用 Plotly 的 facet_grid 在 Python 中进行面板图绘制

Plotly 是一款强大的数据可视化工具,它提供了许多种不同的图表类型和交互方式。其面板图(facet_grid)功能可以使您在单个绘图中绘制多个小图,并将它们的排列方式和大小指定为网格。在这篇介绍中,我们将演示如何在 Python 中使用 Plotly 的 facet_grid 绘制面板图。

准备工作

要使用 Plotly 的 facet_grid 功能,您首先需要安装 Plotly 库并导入所需的模块。您可以使用以下命令安装 Plotly:

!pip install plotly

在导入所需的模块之前,我们将生成一个示例数据集以供使用。我们将使用 Seaborn 库中的“titanic”数据集,并将其加载到 Pandas 数据框中。

import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go

df = sns.load_dataset("titanic")
绘制面板图

一旦你准备好了你的数据集,你就可以使用 Plotly 的 facet_grid 绘制面板图了。以下是一个基本的例子:

fig = px.scatter(df, x="age", y="fare", color="sex")
fig.update_layout(
    width=800,
    height=600,
    title="Titanic Passenger Ages and Fares by Sex",
    font=dict(size=18),
    margin=dict(l=50, r=50, b=100, t=100, pad=4),
    showlegend=False,
)
fig.show()

在这个例子中,我们使用了 Plotly 的 px.scatter 函数绘制了散点图。我们可以添加 color 参数以按性别对点进行着色。然后,我们使用图表的 update_layout 方法来设置一些图表特征,例如标题,字体大小和绘图区的边距。最后,我们调用图表的 show 方法来绘制图表。该图表将绘制单独的小图,每个小图都是根据性别进行分组的。

顺序调整

您还可以使用 Plotly 的 subplot 布局功能对面板图的顺序进行微调。例如,在下面的例子中,我们将按 pclass 列对图表进行分组,并通过 layout.grid 函数指定网格的行和列。

fig = make_subplots(rows=2, cols=3)

for pclass in sorted(df.pclass.unique()):
    df_class = df[df.pclass == pclass]
    row = ((pclass - 1) // 3) + 1
    col = ((pclass - 1) % 3) + 1
    fig.add_trace(
        go.Histogram(x=df_class.age, nbinsx=30),
        row=row,
        col=col,
    )

fig.update_layout(
    width=800,
    height=600,
    title="Titanic Passenger Ages by Class",
    font=dict(size=18),
    margin=dict(l=50, r=50, b=100, t=100, pad=4),
    showlegend=False,
)
fig.show()

在这个例子中,我们使用身份分组旅客的 Pclass (乘客等级),并使用 subplot 布局将它们排列成 2×3 网格形式。我们使用 sorted 函数将乘客等级按递增顺序进行排序,并计算每个图的行和列。接下来,我们使用 add_trace 函数添加一个直方图到对应的行和列。最后,我们使用 update_layout 函数调整一些图表特性,并将其与 UI 视图(show)关联起来。

结论

Plotly 的 facet_grid 功能可大大增强您的数据可视化。它使您可以轻松地绘制具有多个小图的复合图,并将它们的大小和位置指定为网格布局。在本文中,我们学习了如何在 Python 中使用 Plotly 快速轻松地实现面板图。