如何在 Python Plotly 的 3D 散点图中显示图例和标签轴?

Plotly 是一个用于创建图表的开源 Python 库。Python 用户可以使用 Plotly 创建基于 Web 的交互式可视化效果,这些可视化效果可以显示在 Jupyter 笔记本中,保存到独立的 HTML 文件中,或者作为使用 Dash 的 Web 应用程序的一部分。

在本教程中,我们将展示如何使用 Plotly 在 3D 散点图中显示图例和标签轴。

  • 在这里,我们将使用plotly.express来生成图形。它包含许多自定义图表并将其呈现为 HTML 格式的方法。

  • 我们将使用可用于创建生成 DataFrame的Pandas模块。

  • 此外,我们将使用该方法生成具有不同图的图形。plotly.graphs_obj()

按照下面给出的步骤显示图例和标签轴。

步骤1

plotly.express将模块和别名导入为px

importplotly.expressas px

第2步

使用 Pandas 创建数据框。

data = {
   'gadget' : ['mobile','tablet','ipad','laptop'],
   'rating' :[3,4,2,1],
   'price':[20000,50000,30000,90000]
}
df = pd.DataFrame(data)

步骤 3

使用scatter_3d()方法通过应用 X 和 y 坐标值创建散点图 3D 图 -

#创建 scatter_3d 图
fig = px.scatter_3d(
   df, x = 'gadget',
   y = 'rating',z = 'price',
   title="scatter 3D plot"
)

步骤4

使用该update_layout()方法使用以下属性更新布局 -

fig.update_layout(
   font_family="Courier New",
   font_color="blue",
   title_font_family="Times New Roman",
   title_font_color="red",
   legend_title_font_color="green"
)

示范

在 3D 散点图中显示图例和标签轴的完整代码如下 -

importplotly.expressas px
import pandas as pd
#创建数据框
data = {
   'gadget' : ['mobile','tablet','ipad','laptop'],
   'rating' :[3,4,2,1],
   'price':[20000,50000,30000,90000]
}

df = pd.DataFrame(data)

#创建 scatter_3d 图
fig = px.scatter_3d(df, x = 'gadget', y = 'rating',z = 'price', title="scatter 3D plot", width=716, height=750)

#更新图形布局
fig.update_layout(
   font_family="Courier New",
   font_color="blue",
   title_font_family="Times New Roman",
   title_font_color="red",
   legend_title_font_color="green"
)
fig.show()
输出结果

执行时,它将在浏览器上显示以下输出 -

猜你喜欢